跳转至

Nginx 502/504 排查

现象

  • 页面返回 502 Bad Gateway
  • 页面返回 504 Gateway Time-out
  • Nginx 正常运行,但后端服务不可用或响应慢。

快速判断

systemctl status nginx
tail -n 100 /var/log/nginx/error.log
curl -I http://127.0.0.1

排查命令

# 查看 upstream 配置
nginx -T | grep -n "upstream\\|proxy_pass"

# 测试后端端口
nc -vz 127.0.0.1 8080

# 查看后端端口监听
ss -tulnp | grep ':8080'

# 查看 Nginx 错误日志
grep -iE "upstream|connect|timeout|refused" /var/log/nginx/error.log | tail -n 50

常见原因

  • 后端服务没有启动。
  • 后端端口配置错误。
  • 后端响应超时。
  • Nginx 到后端网络不通。
  • 后端连接数耗尽。
  • 代理超时时间设置过短。

处理建议

  • 先确认后端服务是否可直接访问。
  • 再确认 proxy_pass 地址、端口和协议是否正确。
  • 如果是 504,重点看后端响应时间、慢查询、线程池和连接池。
  • 修改 Nginx 配置后先执行 nginx -t
nginx -t
systemctl reload nginx

高危提醒

  • 不要只重启 Nginx,502/504 很多时候根因在后端服务。
  • 修改超时时间只能缓解现象,不能替代后端性能排查。

相关专题