DEV Community

jun liu
jun liu

Posted on

Nginx 502/504 Troubleshooting: A Field Engineer's Checklist

Nginx 502/504 Troubleshooting: A Field Engineer's Checklist

When your upstream returns 502 or 504, here's the systematic approach I use.

The Two Error Codes

Code Meaning Typical Cause
502 Bad Gateway Nginx can't reach upstream Upstream down, wrong port, firewall
504 Gateway Timeout Upstream too slow Heavy query, connection pool full

Step 1: Check the Error Log First

sudo tail -f /var/log/nginx/error.log
Enter fullscreen mode Exit fullscreen mode

Look for strings like:

  • upstream prematurely closed connection
  • connect() failed (111: Connection refused)
  • upstream timed out (110: Connection timed out)

Step 2: Verify Upstream is Alive

# Check if upstream process is running
ps aux | grep [n]ginx
ps aux | grep [p]hp-fpm

# Check listening ports
sudo ss -tlnp | grep :80
sudo ss -tlnp | grep :9000
Enter fullscreen mode Exit fullscreen mode

Step 3: Test Upstream Directly

Bypass Nginx and test the backend directly:

# Test PHP-FPM
curl -I http://127.0.0.1:9000

# Test upstream application
curl -v http://127.0.0.1:3000/health
Enter fullscreen mode Exit fullscreen mode

Common Fixes

Issue 1: PHP-FPM Worker Exhaustion

# Check worker count
sudo systemctl status php8.2-fpm

# Restart if needed
sudo systemctl restart php8.2-fpm
Enter fullscreen mode Exit fullscreen mode

Issue 2: Upstream Timeout Too Short

# In nginx.conf
location / {
    proxy_connect_timeout 60s;
    proxy_read_timeout 300s;
    proxy_send_timeout 60s;
}
Enter fullscreen mode Exit fullscreen mode

Issue 3: Firewall Blocking

# Check firewall rules
sudo iptables -L -n | grep 80
sudo ufw status
Enter fullscreen mode Exit fullscreen mode

Prevention Checklist

  • [ ] Monitor upstream health with Prometheus
  • [ ] Set up alerting for 5xx errors
  • [ ] Regular log rotation and cleanup
  • [ ] Load testing before traffic spikes

More ops guides: ops.jiunotes.top

Top comments (0)