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

Kubernetes中Nginx代理Next.js报502 Bad Gateway的排查与解决

解决Kubernetes Pod内Nginx无法连接同Pod内Next.js服务的502错误

问题概述

  • 技术栈:Next.js 14 + Turbo单仓架构,Kubernetes集群部署,每个Pod包含my-project-nextjs(监听9000端口)和my-project-nginx两个容器(Nginx为默认容器)
  • 异常现象:访问应用URL时返回Nginx 502 Bad Gateway,Nginx容器日志报错:

    connect() failed (111: Connection refused) while connecting to upstream

  • 前置排查:
    • 所有Pod状态均为Running,Next.js容器日志显示服务已正常启动并监听9000端口
    • 尝试更换Nginx基础镜像(debian:stretch-slim、nginx:stable-alpine),问题复现
    • 修改Nginx配置中proxy_pass地址为localhost:9000、http://127.0.0.1:9000、http://0.0.0.0:9000,均无法解决502错误

解决方案

通过以下两步操作解决问题:

  1. 更新Kubernetes Service配置:添加Next.js容器的端口映射规则,确保Service能路由到Next.js服务:
    # Service配置片段
    apiVersion: v1
    kind: Service
    metadata:
      name: my-project
    spec:
      selector:
        app: my-project # 匹配你的Pod标签
      ports:
        - port: 80
          targetPort: 80
          name: nginx
        - port: 9000
          targetPort: 9000
          protocol: TCP
          name: nextjs
    
  2. 修改Nginx配置:将proxy_pass的上游地址替换为Kubernetes Service名称my-project:
    # Nginx配置片段
    location / {
      proxy_pass http://my-project:9000;
      # 补充必要的代理头配置
      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;
    }
    
  3. 重新部署Service和Pod后,访问应用URL,502错误消除,服务正常响应。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 02:37:05