← 返回博客

Nginx 反代 502 Bad Gateway 排查清单

upstream 挂了、超时、或 DNS 解析失败时,按这份顺序排查 Nginx 502。

TensorView Lab · 2026-09-01

现象

浏览器或 curl 访问域名返回 502 Bad Gateway,Nginx error log 里常见:

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

upstream timed out

先确认三件事

  1. 上游进程是否在听端口(例如 127.0.0.1:3000
  2. proxy_pass 写的地址/端口是否一致
  3. 防火墙是否拦了本机回环以外的流量(少见,但 Docker 网络常踩)
sudo ss -lntp | grep -E '3000|8080'
sudo tail -n 50 /var/log/nginx/error.log
curl -v http://127.0.0.1:3000/

常见修复

上游没起来

用 systemd / Docker 把应用拉起来后再 reload Nginx:

sudo systemctl status your-app
# 或
docker compose ps
sudo nginx -t && sudo systemctl reload nginx

超时

长耗时接口(构建、推理)需要加大:

proxy_connect_timeout 60s;
proxy_send_timeout 300s;
proxy_read_timeout 300s;

SELinux / 权限(部分发行版)

# CentOS/RHEL 示例
getsebool -a | grep httpd_can_network_connect
sudo setsebool -P httpd_can_network_connect 1

什么时候该换环境

如果你在共享主机、NAT 混乱、或本地 WSL 端口转发反复丢连接,换一台干净的海外 Linux VPS 做反代联调通常更快。

自检清单

  • nginx -t 通过
  • 本机 curl 上游成功
  • error.log 不再刷 Connection refused
  • 对外 HTTPS 证书与 server_name 匹配

也可以试试 TensorView 小工具集合