0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

React Native アプリからローカルコンテナ上の API にアクセスする方法まとめ

0
Last updated at Posted at 2026-02-02

React Native アプリから Docker コンテナ上で動いている Laravel API に接続する際、
多くの人が最初にハマるのが「localhost問題」です。

この記事では、ローカル開発環境で RN → コンテナAPI へ接続する方法を整理します。


想定構成

[React Native App]  →  [Laravel API(Docker)]  →  [MySQL(Docker)]

API は Docker コンテナ内で起動:

docker run -p 8000:8000 my-laravel-api

❌ よくある失敗

fetch("http://localhost:8000/api/users")

これ 動きません

理由:

環境 localhost が指す先
PCブラウザ 自分のPC
React Nativeアプリ アプリが動いている端末(エミュレータ or 実機)

つまり RN から見る localhost開発PCではない


✅ 解決方法一覧

環境によって接続先を変えます。


🟢 iOSシミュレータ

iOSシミュレータはホストマシンをそのまま見られるのでOK:

const API_URL = "http://localhost:8000";

🟢 Androidエミュレータ

Androidは特別なIPを使います:

const API_URL = "http://10.0.2.2:8000";
アドレス 意味
10.0.2.2 Androidエミュレータから見たホストPC

🟢 実機テスト(同じWi-Fi接続時)

PCのローカルIPアドレスを使います。

Mac:

ifconfig

Windows:

ipconfig

例:

const API_URL = "http://192.168.1.15:8000";

⚠ Laravel コンテナは 0.0.0.0 バインド必須


🐘 Laravel 側の設定

サーバ起動(コンテナ内)

php artisan serve --host=0.0.0.0 --port=8000

または nginx / Apache を使う場合も
外部アクセス可能なポート公開が必要


CORS設定

fruitcake/laravel-cors(Laravel標準)で対応:

config/cors.php

'paths' => ['api/*'],
'allowed_origins' => ['*'],
'allowed_methods' => ['*'],
'allowed_headers' => ['*'],

Docker側の確認ポイント

ポート公開されているか確認

docker ps

表示例:

0.0.0.0:8000->8000/tcp

これが無いと外部から接続できません。


環境ごとに自動切替するコード

import { Platform } from "react-native";

const API_PORT = 8000;

const getBaseUrl = () => {
  if (Platform.OS === "android") return `http://10.0.2.2:${API_PORT}`;
  return `http://localhost:${API_PORT}`;
};

export const API_URL = getBaseUrl();

よくあるトラブル一覧

症状 原因
timeout Laravel が 0.0.0.0 で待ち受けていない
接続拒否 Dockerでポート公開していない
Androidだけ繋がらない 10.0.2.2 を使っていない
実機で繋がらない PCと同じWi-Fiに接続していない
CORSエラー Laravel側CORS未設定

まとめ

環境 接続先
iOSシミュレータ localhost
Androidエミュレータ 10.0.2.2
実機 PCのローカルIP

結論

React Native からローカルAPIに繋がらない原因の大半は

localhostの指す先を誤解していること

Docker・React Native・エミュレータの
ネットワークの見え方の違いを理解すれば一発で解決できます。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?