You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Docker环境下Nginx反向代理报错connect() failed (111)求助

问题分析与解决

核心问题是Nginx配置中错误使用了宿主机映射端口,而非容器内部监听端口,同时容器启动顺序可能导致服务未就绪时Nginx尝试连接。

1. 修正Nginx代理端口

容器间通过Docker网络通信时,必须使用容器内部实际监听的端口,而非docker-compose.yml中ports字段里的宿主机映射端口。

修改nginx.conf:

events { worker_connections 1024; }

http {

  server {
    listen 80;

    location / {
      # 前端容器内部端口是5000,而非宿主机的3000
      proxy_pass http://frontend:5000;
      # 可选:添加常用代理头,避免前端出现跨域或路径问题
      proxy_set_header Host $host;
      proxy_set_header X-Real-IP $remote_addr;
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_set_header X-Forwarded-Proto $scheme;
    }

    location /api/ {
      proxy_set_header Host $host;
      # 后端容器内部端口是9000,而非宿主机的7000
      proxy_pass http://backend:9000/api/;
    }
  }
}

2. 可选:确保服务就绪后Nginx再启动

depends_on仅保证容器启动顺序,不确保服务已就绪。可添加健康检查,让Nginx等待前端/后端服务启动完成:

修改docker-compose.yml:

version: '3.8'
services:
  proxy:
    image: nginx:1.19-alpine
    container_name: proxy_server
    restart: unless-stopped
    ports:
      - 80:80
    volumes:
      - ./nginx.conf:/etc/nginx/nginx.conf:ro
    depends_on:
      frontend:
        condition: service_healthy
      backend:
        condition: service_healthy
    networks:
      - networkName
  frontend:
    image: front-end
    build: ./
    container_name: simple-front-end
    ports:
      - 3000:5000
    networks:
      - networkName
    healthcheck:
      # 根据React服务实际情况调整检查命令,比如curl容器内部5000端口
      test: ["CMD", "curl", "-f", "http://localhost:5000"]
      interval: 5s
      timeout: 5s
      retries: 5
  backend:
    image: back-end
    build: ./back-end
    container_name: simple-back-end
    ports:
      - 7000:9000
    networks:
      - networkName
    healthcheck:
      # 根据Go服务实际情况调整检查命令,比如curl容器内部9000的健康检查接口
      test: ["CMD", "curl", "-f", "http://localhost:9000/health"]
      interval: 5s
      timeout: 5s
      retries: 5
networks:
  networkName:

验证修改

  1. 停止并删除现有容器:docker-compose down
  2. 重新启动服务:docker-compose up --build
  3. 访问http://localhost,验证是否能通过Nginx正常访问前端,以及/api路径是否能正确代理到后端。

内容的提问来源于stack exchange,提问作者nishant singh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 09:33:00