【问题标题】:I got problem while using Nginx to direct requests to services defined in docker-compose.yml我在使用 Nginx 将请求定向到 docker-compose.yml 中定义的服务时遇到问题
【发布时间】:2019-07-10 16:11:52
【问题描述】:

我正在设置一个包含多个容器的应用程序,并使用 nginx 将请求重定向到正确的容器。但是,我遇到了 502 Bad Gateway 错误。

实际上,代码来自 Udemy 的一门课程:Docker 和 Kubernetes。 我只是复制并粘贴代码,它在讲师机器上运行,但不是我的。我在我的 Windows 和我的 macbook 上尝试过,重新启动 docker,但仍然没有希望。我在其他 stackoverflow 帖子和其他一些文章中寻找解决方案,但没有人告诉我为什么它可以在其他机器上运行,而在我的机器上不行。

这里是repo of the code。

docker-compose.yml (full code):

version: "3"
services:
  postgres:
    ...
  redis:
    ...
  nginx:
    restart: always
    build:
      dockerfile: Dockerfile.dev
      context: ./nginx
    ports:
      - "3050:80"
  api:
    ...
  client:
    ...
  worker:
    ...

nginx/Dockerfile.dev

FROM nginx
COPY ./default.conf /etc/nginx/conf.d/default.conf

nginx/default.conf

upstream client {
  server client:3000;
}

upstream api {
  server api:5000;
}

server {
  listen 80;
  server_name  localhost;

  location / {
    proxy_pass http://client;
  }

  location /api {
    rewrite /api/(.*) /$1 break;
    proxy_pass http://api;
  }
}

它在教师的机器和其他学习者的机器上运行得很好,但在我的机器上却不行。连接http://localhost:3050和http://localhost:3050/api时出错:

nginx_1     | 2019/07/08 02:52:35 [error] 6#6: *1 connect() failed (111: Connection refused) while connecting to upstream, client: 172.25.0.1, server: , request: "GET / HTTP/1.1", upstream: "http://125.235.4.59:3000/", host: "localhost:3050"
nginx_1     | 172.25.0.1 - - [08/Jul/2019:02:52:35 +0000] "GET / HTTP/1.1" 502 559 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36" "-"
nginx_1     | 2019/07/08 02:52:57 [error] 6#6: *1 connect() failed (111: Connection refused) while connecting to upstream, client: 172.25.0.1, server: , request: "GET /favicon.ico HTTP/1.1", upstream: "http://125.235.4.59:3000/favicon.ico", host: "localhost:3050", referrer: "http://localhost:3050/"
nginx_1     | 172.25.0.1 - - [08/Jul/2019:02:52:57 +0000] "GET /favicon.ico HTTP/1.1" 502 559 "http://localhost:3050/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36" "-"

感谢任何帮助。

【问题讨论】:

  • 代理配置看起来是正确的,但是看起来你并没有暴露客户端/api端口。可以测试在 docker-compose.yml 中添加端口以“公开”吗?
  • 您的意思是客户端和api文件夹中Dockerfile中的EXPOSE标志?
  • 我试过了,还是不行
  • 可以向你的 nginx 服务添加一个“depends_on: ...”客户端/api,以确保这些服务在 nginx 启动之前启动(暴露依赖服务的端口)?
  • 是的,它现在可以工作了,非常感谢@masseyb

标签: docker nginx docker-compose dockerfile


【解决方案1】:

需要修改docker-compose.yml:

  1. 上游服务应公开其端口,以便nginx 服务可以连接,即:
  api:
    expose:
    - '5000'

  client:
    expose:
    - '3000'

  1. nginx 服务depends_on 上游服务:
  nginx:
    depends_on:
    - 'client'
    - 'api'

【讨论】:

  • 实际上,我检查过,只有depends_on 可以解决问题,'expose' 部分就像开发人员之间交流的注释,nginx 不会读取该属性。但是,其他一些服务可能会读取它,例如 AWS Elastic Beanstalk 会读取它来进行自动映射。
猜你喜欢
  • 2016-09-18
  • 2021-02-14
  • 1970-01-01
  • 1970-01-01
  • 2016-12-16
  • 1970-01-01
  • 2021-12-01
  • 2011-11-25
  • 2023-03-24
相关资源
最近更新 更多