解决 Nginx 报错 502 Bad Gateway: connect() failed (111: Connection refused) 修复
排查 Nginx 反向代理提示 502 Bad Gateway 错误,分析后端进程宕机、本地端口监听失配与 Unix Socket 权限问题。
问题现象
用户访问网站时,网页直接展示 502 错误页面:
<html>
<head><title>502 Bad Gateway</title></head>
<body>
<center><h1>502 Bad Gateway</h1></center>
<hr><center>nginx</center>
</body>
</html>
查看 Nginx 日志 /var/log/nginx/error.log:
2026/11/15 18:15:22 [error] 1420#0: *9812 connect() failed (111: Connection refused) while connecting to upstream, client: 198.51.100.5, server: example.com, request: "GET / HTTP/1.1", upstream: "http://127.0.0.1:3000/", host: "example.com"
触发根因
HTTP 502(Bad Gateway)表示 Nginx 尝试将请求转发给配置的 upstream 后端服务,但在网络层与后端进行 TCP 握手时,直接收到了操作系统协议栈回复的 RST 拒绝响应(errno 111: Connection refused):
- 后端应用进程根本没有运行:Node.js、Python、Go 或 Java 服务因异常抛出崩溃退出或被 OOM Killer 杀除;
- 端口或地址配置错误:后端服务实际监听在
127.0.0.1:4000或本地 Unix Socket,而在 Nginx 配置中误写为了127.0.0.1:3000; - 后端监听仅绑定在 IPv6 或回环地址:服务配置了监听
::1或192.168.1.10,导致向127.0.0.1发送握手被拒绝; - SELinux 阻断了 Nginx 发起网络代理:在 RHEL/CentOS 上,SELinux 默认禁止 Nginx 进程向其他网络端口发起 outbound 连接。
解决步骤
1. 检查后端应用进程与端口监听状态
在服务器上核查目标端口(如 3000)是否正处于 LISTEN 状态:
sudo ss -tulpn | grep 3000
若无任何输出,说明后端服务已宕机。检查进程管理器日志并拉起服务:
# 若使用 systemd
sudo systemctl status myapp
sudo journalctl -u myapp -n 30 --no-pager
# 若使用 PM2
pm2 status
pm2 logs myapp
2. 核对 Nginx 的 proxy_pass 目标配置
检查 /etc/nginx/conf.d/ 或 /etc/nginx/sites-available/ 下的配置:
location / {
proxy_pass http://127.0.0.1:3000;
proxy_set_header Host $host;
}
确认 IP 与端口与 ss -tulpn 中查得的一致。
3. 检查并放开 SELinux 网络代理权限
若系统开启了 SELinux(getenforce 返回 Enforcing),检查是否有 AVC 拒绝日志:
sudo grep nginx /var/log/audit/audit.log | grep denied
执行命令允许 Nginx 转发网络流量:
sudo setsebool -P httpd_can_network_connect 1
4. 若使用 Unix Domain Socket,检查文件权限
若配置为 proxy_pass http://unix:/run/php/php-fpm.sock;,检查该 sock 文件的权限与属主:
ls -la /run/php/php-fpm.sock
确保运行 Nginx 的用户(nginx 或 www-data)对其具备读写(rw)权限:
sudo chmod 660 /run/php/php-fpm.sock
sudo chown www-data:www-data /run/php/php-fpm.sock
验证确认
在本地直接向后端发起探测:
curl -I http://127.0.0.1:3000/
返回 HTTP 200。再次通过公网域名访问,Nginx 成功代理输出网页,502 Bad Gateway 彻底清除。


