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

Angular应用Docker部署Nginx反向代理遇502 Bad Gateway错误求助

问题排查与修复方案

核心错误原因

你的502错误源于Nginx无法连接到Angular应用容器,日志里的connect() failed (111: Connection refused)指向三个关键问题:

  • Angular开发服务器默认仅绑定127.0.0.1,同一Docker网络内的Nginx容器无法访问
  • 同时执行docker run和docker compose up导致容器环境混乱,端口与服务冲突
  • 配置中存在端口绑定、服务访问规则的错误

步骤1:修正Dockerfile

Angular的ng serve默认只监听本地回环地址,需强制绑定0.0.0.0让容器间能访问,同时暴露服务端口:

FROM node:latest as build

WORKDIR /usr/local/app

COPY package.json .
RUN npm install
COPY . .

# 暴露4200端口,允许容器间通信
EXPOSE 4200
# 启动开发服务器并绑定所有可访问地址
CMD ["ng", "serve", "--host", "0.0.0.0"]

步骤2:修正docker-compose.yml

规范服务依赖关系,添加健康检查确保Angular启动完成后Nginx再转发请求:

version: "3.9"

services:
  app:
    container_name: app
    build:
      context: .
    # 可选:暴露端口到主机,方便直接测试Angular服务
    # ports:
    #   - "4200:4200"
    # 健康检查:确认Angular服务就绪
    healthcheck:
      test: ["CMD", "curl", "-f", "http://localhost:4200"]
      interval: 10s
      timeout: 5s
      retries: 5

  nginx:
    container_name: nginx
    image: nginx
    ports:
      - "80:80"
    depends_on:
      app:
        condition: service_healthy # 等待app健康检查通过
    volumes:
      - ./default.conf:/etc/nginx/conf.d/default.conf

步骤3:修正Nginx的default.conf

调整server_name匹配外部访问规则,优化代理配置:

server {
    listen 80;
    # 匹配所有请求,或指定为localhost
    server_name _;
    location / {
        proxy_pass http://app:4200;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
        # 添加超时设置,适配Angular热重载
        proxy_connect_timeout 30s;
        proxy_send_timeout 30s;
        proxy_read_timeout 30s;
    }
}

步骤4:清理并重新部署

  1. 停止并删除所有旧容器,避免环境冲突:
docker stop $(docker ps -aq) && docker rm $(docker ps -aq)
  1. 重新构建镜像并启动服务:
docker compose build && docker compose up -d
  1. 访问http://localhost(Nginx已映射主机80端口)即可正常加载Angular应用。

内容的提问来源于stack exchange,提问作者Ian Brandon

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 21:53:11