1
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?

Docker Composeで「host not found in upstream」が発生する原因と解決策

Posted at

やりたいこと

Docker Composeを使用して、

  1. PHP(php-container
  2. PostgreSQL(postgres
  3. nginx(nginx

の3つのコンテナを同時に立ち上げたい。

発生したエラー

docker-compose up でコンテナを立ち上げたが、nginx コンテナが起動せず、ブラウザで http://localhost/calculate.php にアクセスしても「このサイトにアクセスできません」となる。

nginxの起動時に下記のログを出力。

2025/03/12 12:53:45 [emerg] 1#1: host not found in upstream "php-container" in /etc/nginx/conf.d/default.conf:16
nginx: [emerg] host not found in upstream "php-container" in /etc/nginx/conf.d/default.conf:16

調査

  1. docker ps でコンテナの状態を確認したところ、nginx が起動していない。
  2. docker logs [nginxのコンテナ名] でログを確認すると、以下のエラーを出力。
2025/03/08 06:41:55 [emerg] 1#1: "server" directive is not allowed here in /etc/nginx/nginx.conf:1
nginx: [emerg] "server" directive is not allowed here in /etc/nginx/nginx.conf:1

原因

nginx から php-container に接続する際、コンテナ名 (php-container) を指定していたが、Docker では、異なるコンテナ間での名前解決を自動的にしてくれるわけではない。
→ そのためnginx が php-container を見つけられない。

解決策

docker-compose.yml にネットワークを定義、すべてのコンテナを同じネットワークに入れる。下記を全コンテナのプロパティに追記。

    networks:
      - app-network

修正後のdocker-compose.yml

version: '3.8'
services:
  php-container:
    image: php:8.2-fpm
    networks:
      - app-network

  postgres:
    image: postgres:15
    environment:
      POSTGRES_USER: user
      POSTGRES_PASSWORD: password
    networks:
      - app-network

  nginx:
    image: nginx:latest
    networks:
      - app-network
    volumes:
      - ./nginx/conf.d:/etc/nginx/conf.d

networks:
  app-network:
    driver: bridge

これで全コンテナが同じじネットワーク内で通信可能になる。
nginx が php-container のコンテナ名で通信できるようになり、名前解決ができる。エラー解消しました。

1
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
1
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?