解决 Nginx 报错 502 Bad Gateway connect refused 上游拒绝
分析 Nginx 反向代理返回 502 并在错误日志中记录 connect refused while connecting to upstream 的根因与端口服务排查指南。
问题现象
用户访问页面时返回 502 Bad Gateway,查看 Nginx 的 error.log:
2026/11/15 11:00:00 [error] 1234#1234: *1 connect() failed (111: Connection refused) while connecting to upstream, client: 192.168.1.10, server: example.com, request: "GET / HTTP/1.1", upstream: "http://127.0.0.1:8000/", host: "example.com"
触发根因
- 上游后端服务(如 Node.js、Gunicorn、PHP-FPM、Java Tomcat)进程崩溃或未启动。
- Nginx 配置的
proxy_pass目标端口与后端实际监听的端口不匹配(例如配置了 8000,应用实际监听 3000)。 - SELinux 开启并阻止了 Nginx 向外发起 TCP 网络连接(
httpd_can_network_connect)。
解决步骤与操作命令
步骤一:检查后端进程与端口监听状态
sudo ss -tulpn | grep 8000
# 或
ps aux | grep gunicorn
若服务未运行,重启后端守护进程:
sudo systemctl restart my-backend-service
步骤二:核实 proxy_pass 配置
确保 upstream 指向正确的地址与协议:
location / {
proxy_pass http://127.0.0.1:8000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
步骤三:排查 SELinux 限制(CentOS/RHEL 系统)
若进程正常监听但 Nginx 仍报 Connection refused,放行 SELinux 网络策略:
sudo setsebool -P httpd_can_network_connect 1
验证确认
从本地直接验证后端接口,再通过 Nginx 验证:
curl -I http://127.0.0.1:8000/
curl -I http://example.com/
返回 HTTP/1.1 200 OK,502 报错彻底消除。


