【问题标题】:Nginx can't find upstream host in multi-container docker compose setupNginx 在多容器 docker compose 设置中找不到上游主机
【发布时间】:2019-08-08 18:58:38
【问题描述】:

我正在使用 docker-compose 在本地运行一个多 docker 容器,这些容器是 React 前端“客户端”、一个 Nodejs 应用程序“api”,以及一个位于两个前面的 Nginx 代理。我一直在使用 docker-compose 设置,如下所示

version: '3'
services:
  client:
    build:
      dockerfile: Dockerfile.dev
      context: ./client
    volumes:
      - /usr/app/node_modules
      - ./client:/usr/app
  api:
    build:
      dockerfile: Dockerfile.dev
      context: ./server
    volumes:
      - /usr/app/node_modules
      - ./server:/usr/app
  nginx:
    restart: always
    build:
      dockerfile: Dockerfile.dev
      context: ./nginx
    ports:
      - '8080:80'

我的 Nginx 设置如下

upstream client {
    server client:3000;
}

upstream api {
    server api:5000;
}

server {
    listen 80;
    server_name _;

    location / {
        if ($http_x_forwarded_proto != 'https') {
            return 301 https://$host$request_uri;
        }
        proxy_pass http://client;
    }

    location /api {
        if ($http_x_forwarded_proto != 'https') {
            return 301 https://$host$request_uri;
        }
        rewrite /api/(.*) /$1 break;
        proxy_pass http://api;
    }
}

最近尝试启动容器时,出现以下错误:

nginx_1   | 2019/08/08 18:11:12 [emerg] 1#1: host not found in upstream "client:3000" in /etc/nginx/conf.d/default.conf:2
nginx_1   | nginx: [emerg] host not found in upstream "client:3000" in /etc/nginx/conf.d/default.conf:2

知道为什么 nginx 找不到上游吗?

我已尝试添加指向 nginx 设置块的链接,如下所示:

  nginx:
    restart: always
    build:
      dockerfile: Dockerfile.dev
      context: ./nginx
    links:
      - client:client
      - api:api
    ports:
      - '8080:80'

我还尝试了“depends_on”而不是链接。添加链接后,nginx不再抱怨并以代码0退出。但是当我访问localhost:8080时, 它提供了一个 301 重定向到https://localhost

非常感谢任何帮助或指导!!!

【问题讨论】:

  • 向您的 nginx 服务添加一个“depends_on”节,以确保您的上游服务在 nginx 服务启动之前正在运行/可访问,参考。 stackoverflow.com/a/56976398/1423507

标签: docker nginx docker-compose containers


【解决方案1】:

您应该检查您的服务的名称。 Docker compose 将在名为 [YOUR_PROJECT_NAME]_api_1 的 pod 中启动您的服务 api。仅启动 api 和客户端并检查 docker ps 的输出。您应该列出 pod 的名称。

在较新的 docker_compose 语法版本中,您可以使用 link_external 将 [YOUR_PROJECT_NAME]_api_1 映射到 api。

【讨论】:

  • nginx 配置很好,OP 可以docker-compose up --scale api=3 client=3nginx(默认)将循环分配连接(服务负载平衡) - 你不需要链接。
猜你喜欢
  • 1970-01-01
  • 2019-09-01
  • 2021-02-26
  • 2020-07-08
  • 2018-03-03
  • 2020-06-15
  • 2018-02-06
  • 2018-12-28
  • 1970-01-01
相关资源
最近更新 更多