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?

More than 1 year has passed since last update.

【Docker】コンテナ間で通信する場合のネットワーク設定について

Posted at

概要

  • Railsのみで構成していたアプリケーションを、Next.js×Rails APIのSPA構成に変更した
  • 本番環境のデプロイ先はAWS ECS Fargateを想定している
  • 本番環境へのデプロイ前に、本番環境frontend用のコンテナが正常に動作するかを、ローカル環境で確認した
  • その際にbackendへのAPI通信でエラーが発生したため、原因と対応をまとめる

環境

  • backend
    • ruby 3.0.2
    • rails 6.1.4 (APIモード)
  • frontend
    • react 18.2.0
    • next 13.1.6

関連ファイル

  • 開発環境で利用していたAPI構成のdocker-compose.yml
example-app/docker-compose.yml
version: '3'
services:
  db:
    image: mysql:8.0
    env_file: .env
    ports:
      - 4306:3306
    volumes:
      - db_data:/var/lib/mysql
  back:
    env_file: .env
    stdin_open: true
    tty: true
    build:
      context: ./back/
      dockerfile: Dockerfile
    volumes:
      - ./back:/back
      - gem_data:/usr/local/bundle
    ports:
      - '3000:3000'
    depends_on:
      - db
  front:
    build:
      context: ./front/
      dockerfile: Dockerfile
    volumes:
      - ./front/app:/usr/src/app
    command: 'yarn dev'
    ports:
      - "8000:3000"
volumes:
  db_data:
  gem_data:
  • 新たに作成した本番環境frontend用Dockerfile
example-app/front/docker/production/Dockerfile
FROM node:lts-buster-slim

WORKDIR /usr/src/app

COPY ../../app ./

RUN yarn install && \
    yarn build

EXPOSE 3000

CMD ["yarn", "start"]

問題発生までの手順

  1. 本番環境frontend用のDockerfileを作成、ビルド、コンテナ起動
  2. 開発環境用docker-compose.ymlの中で、dbとbackのみを起動
  3. 1.のコンテナは起動はできているが、2.で起動したAPIとの通信ができない旨のエラーが発生

※APIエンドポイントを記載した.env.productionについては、ビルドコンテキストに含まれており、起動時ログからも読み込みに問題は無い。

原因

docker-composeで起動されるコンテナは自動的に同じネットワークに参加するが、手動で起動したコンテナはネットワークを指定する必要があるよう。

対応

  • docker-composeで利用しているネットワークを確認
example-app ❯❯❯docker network ls

NETWORK ID     NAME                 DRIVER    SCOPE
77bacbced6ed   bridge               bridge    local
a162dferji42   example-app_default  bridge    local
662dadfasdfs   host                 host      local
919sadfa68d2   none                 null      local
  • frontendのコンテナを対象ネットワークに接続
docker network connect example-app_default xxxxxxxxxxxx(frontendのimageのハッシュ)

これにより、ローカル環境にて、本番環境frontend用コンテナから、docker-composeで起動した開発環境用backendコンテナとの通信ができた。

参考

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?