DevOpsil
NginxCritical

Fix: Nginx 502 Bad Gateway

Users see '502 Bad Gateway' error page

!Symptoms

  • Users see '502 Bad Gateway' error page
  • Nginx error log shows 'connect() failed (111: Connection refused)'
  • Upstream application is not responding to Nginx
  • Intermittent 502 errors under load

?Root Causes

  • Upstream application (Node.js, Python, PHP-FPM) is down or crashed
  • Upstream is listening on a different port or socket than configured in Nginx
  • Upstream ran out of worker processes or connections
  • Firewall or SELinux blocking Nginx from connecting to the upstream
  • Upstream is too slow and Nginx times out (but usually results in 504)

#Diagnosis Steps

  1. 1Check Nginx error log: `tail -f /var/log/nginx/error.log`
  2. 2Verify upstream is running: `systemctl status <service>` or `ss -tlnp | grep <port>`
  3. 3Test upstream directly: `curl http://127.0.0.1:<upstream-port>/`
  4. 4Check if SELinux is blocking: `setsebool -P httpd_can_network_connect 1`
  5. 5Review Nginx upstream config: `nginx -T | grep upstream -A 10`

>Fix

  1. 1Restart the upstream application: `systemctl restart <service>`
  2. 2Fix the port mismatch between Nginx proxy_pass and the upstream listener
  3. 3Increase upstream worker count or connection pool size
  4. 4Allow Nginx network connections in SELinux: `setsebool -P httpd_can_network_connect on`
  5. 5If socket-based, ensure the socket file exists and has correct permissions

*Prevention

  • Set up process managers (PM2, systemd) to auto-restart crashed upstreams
  • Monitor upstream health with Nginx upstream health checks
  • Use multiple upstream servers with load balancing for redundancy
  • Set up alerting on 5xx error rates in your monitoring stack
  • Implement proper graceful shutdown in upstream applications

Related Error Messages

502 Bad Gatewayconnect() failed (111: Connection refused)no live upstreams while connecting to upstreamupstream prematurely closed connectionrecv() failed (104: Connection reset by peer)