🔧 Error Fixes
· 2 min read
Last updated on

Nginx 502 Bad Gateway — How to Fix It


502 Bad Gateway — nginx

What causes this

A 502 means Nginx received an invalid response from the upstream server it’s proxying to. In practice, this almost always means one of:

  • Your backend application (Node.js, Python, PHP-FPM, etc.) has crashed or isn’t running
  • Nginx is pointing to the wrong port or socket
  • The backend is too slow and Nginx timed out waiting for a response
  • A Unix socket has wrong permissions

Fix 1: Check if your backend is actually running

# If your app runs on port 3000
curl http://localhost:3000

# Check the process
systemctl status myapp
# or
ps aux | grep node

If the backend crashed, check its logs and restart it. This is the cause 90% of the time.

Fix 2: Verify the proxy_pass target

Make sure Nginx is pointing to the right place:

# Check your Nginx config
server {
    location / {
        # ❌ Wrong port — your app is on 3000, not 3001
        proxy_pass http://localhost:3001;

        # ✅ Correct port
        proxy_pass http://localhost:3000;
    }
}

If you’re using a Unix socket:

location / {
    # Make sure this socket file actually exists
    proxy_pass http://unix:/run/myapp.sock;
}

After changing the config, test and reload:

sudo nginx -t
sudo systemctl reload nginx

Fix 3: Check Nginx error logs

The error log usually tells you exactly what went wrong:

tail -50 /var/log/nginx/error.log

Common messages you’ll see:

  • connect() failed (111: Connection refused) — backend isn’t running
  • no live upstreams — all upstream servers are down
  • upstream timed out — backend is too slow

Fix 4: Increase timeouts

If your backend needs more time (heavy API calls, file processing):

location / {
    proxy_pass http://localhost:3000;
    proxy_connect_timeout 60s;
    proxy_send_timeout 60s;
    proxy_read_timeout 60s;
}

Fix 5: Fix PHP-FPM issues

If you’re running PHP, the 502 often means PHP-FPM crashed or ran out of workers:

# Check PHP-FPM status
sudo systemctl status php8.2-fpm

# Increase workers in /etc/php/8.2/fpm/pool.d/www.conf
pm.max_children = 50
pm.start_servers = 10
pm.min_spare_servers = 5
pm.max_spare_servers = 20

# Restart
sudo systemctl restart php8.2-fpm

How to prevent it

  • Set up process managers (systemd, PM2) to auto-restart your backend if it crashes
  • Monitor your backend’s memory usage — OOM kills are a common cause of 502s
  • Use health checks in your Nginx upstream configuration
  • Set up alerting on 502 error rates so you catch issues before users report them
  • Check out our Nginx config generator for a properly configured setup
📘