Docker nginx 反向代理返回 502 bad gateway “连接到上游时连接被拒绝”

2024-03-21

我正在尝试在一个容器中设置 nginx 反向代理到运行我的应用程序的另一个容器。这是我的 nginx.conf:

    daemon off;

    user  nginx;
    worker_processes  1;

    error_log  /var/log/nginx/error.log warn;
    pid        /var/run/nginx.pid;


    events {
        worker_connections  1024;
    }


    http {
        include       /etc/nginx/mime.types;
        default_type  application/octet-stream;

        log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                        '$status $body_bytes_sent "$http_referer" '
                        '"$http_user_agent" "$http_x_forwarded_for"';

        access_log  /var/log/nginx/access.log  main;

        sendfile        on;

        upstream appserver {
            server app:3000;
        }

        server {
            listen 80;
            server_name localhost;

            location / {
                proxy_pass http://appserver/;
                proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
                proxy_set_header Host $http_host;
                proxy_redirect off;        
            }
        }
    }

我的 docker-compose.yml 如下所示:

version: '3'
services:
  db:
    image: postgres
  redis:
    image: redis
  web:
    build: ./web
    image: web
    ports:
      - "8080:80"
  app:
    build: ./app
    image: app
    command: puma
    volumes:
      - ./app:/app
    expose:
      - "3000"
    ports:
      - "3000:3000"
    depends_on:
      - db
      - redis
      - web

反向代理的 Dockerfile 只需复制配置文件并启动 nginx 服务。这是我的问题:

当在主机浏览器上访问 localhost:8080 时,nginx 返回 502 Bad Gateway。日志显示“web_1 | 2017/02/26 22:55:15 [错误] 12#12: *1 connect() 失败(111:连接被拒绝),同时连接到上游,客户端:172.25.0.1,服务器:localhost,请求:“GET / HTTP/1.1”,上游:“http://127.0.53.53:3000/ http://127.0.53.53:3000/”,主机:“本地主机:8080” 网络_1 | 172.25.0.1 - - [26/2/2017:22:55:15 +0000]“GET / HTTP/1.1”502 576“-”“Mozilla/5.0(Windows NT 10.0;Win64;x64)AppleWebKit/537.36(KHTML) ,如 Gecko)Chrome/56.0.2924.87 Safari/537.36" "-""

现在我立即认为 nginx 无法访问我的应用程序容器,但是,在“web”容器中运行“curl app:3000”会返回正确的响应。当端口转发时,我还可以直接在端口 3000 上访问应用程序。所以我觉得问题在于我的 nginx.conf 如何尝试访问该资源。我已经在这件事上用头撞墙有一段时间了。有任何想法吗?


重写 docker-compose.yml 通过确保应用程序在 nginx 反向代理之前启动来消除该问题。

version: '3'
services:
  db:
    image: postgres
  redis:
    image: redis
  web:
    build: ./web
    image: web
    ports:
      - "8080:80"
    depends_on:
      - app
  app:
    build: ./app
    image: app
    command: puma
    volumes:
      - ./app:/app
    expose:
      - "3000"
    ports:
      - "3000:3000"
    depends_on:
      - db
      - redis
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Docker nginx 反向代理返回 502 bad gateway “连接到上游时连接被拒绝” 的相关文章

随机推荐