4
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

コンテナ間通信でハマった話

Last updated at Posted at 2025-02-05

1.はじめに

GoとReactを使ったアプリケーションをdockerで作成しているとき、GoとReactの通信が上手くいかず数時間ハマったので原因と解決策を備忘録としてまとめます。

2.何が起こったのか

下記のdocker-compose.ymlでGo,React,DB用のコンテナを三つ立てていました。

docker-compose.yml
volumes:
  postgres-data:


services:
  reactapp:
    build: ./front
    tty: true
    working_dir: /app
    volumes:
      - ./front:/app
    command: sh -c "npm start"
    ports:
      - "3000:3000"
    networks:
      - net_test
    env_file:
      - .env
  goapp:
    build: ./backend
    volumes:
      - ./backend:/app
    # command: sleep infinity
    command: air
    # network_mode: service:db
    ports:
      - "8080:8080"
    networks:
      - net_test
    env_file:
      - .env
  db:
    image: postgres:latest
    restart: unless-stopped
    volumes:
      - postgres-data:/var/lib/postgresql/data
    networks:
      - net_test
    ports:
      - "5432:5432"
    env_file:
      - .env
networks:
  net_test:
    external: true

異なるコンテナ間の通信はサービス名で名前解決できるとのことだったので、http://${サービス名}:${ポート名}という感じでReactからバックエンド(Go)にアクセスを行うようにしました。

.env
REACT_APP_GO_BASE_URL=http://goapp:8080
login.jsx
try {
    const response = await axios.post("`${process.env.REACT_APP_GO_BASE_URL}/registerPhoto", {
                username,
                likedPhotoStatus: photosArray})
} catch (error) {
    console.error("CannotRegisterLikedPhoto", error)
}

すると、net::ERR_NAME_NOT_RESOLVEDというエラーが出ました。どうやら、名前解決ができていないようです。
?????サービス名で名前解決できるんじゃないの!?

3 原因と解決策

色々調べてみると、Reactは当然ですがブラウザ上で動いています。なので、Reactはコンテナの上で動いているのではなくあくまでもぶらうざの上で動いているということなのです。
そのため、http://${サービス名}:${ポート名}でアクセスするのではなくhttp://localhost:${ポート名}でアクセスする必要があるとのことでした。
localhostに変更したら無事バックエンドへのアクセスができました!!

.env
REACT_APP_GO_BASE_URL=http://localhost:8080

参考

4
2
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
4
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?