HTTP 502 Bad Gateway — Proxy and Upstream Errors

Debug HTTP 502 Bad Gateway errors. Learn about reverse proxy configuration, upstream server failures, timeout tuning, and health checks for Nginx, Apache, and cloud load balancers.

HTTP Status Codes

Detailed Explanation

HTTP 502 Bad Gateway

A 502 error means the server acting as a gateway or proxy received an invalid response from an upstream server. The proxy itself is working, but it cannot get a valid response from the backend.

Architecture

Client -> Nginx (Proxy) -> Application Server (upstream)
                           ^
                           502 = this connection failed

Common Causes

1. Upstream server crashed:

# Check if the application is running
systemctl status myapp
pm2 status

# Check application logs
journalctl -u myapp -f
tail -f /var/log/myapp/error.log

2. Nginx proxy misconfiguration:

# Wrong upstream address or port
upstream backend {
    server 127.0.0.1:3000;  # Is the app really on port 3000?
}

server {
    location / {
        proxy_pass http://backend;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
    }
}

3. Application returns invalid HTTP response: If the upstream server returns a response that the proxy cannot parse (e.g., truncated headers, invalid status line), the proxy returns 502.

4. Socket/pipe issues:

# PHP-FPM socket not found or wrong permissions
upstream php {
    server unix:/run/php/php8.2-fpm.sock;
}

5. Memory exhaustion on upstream: The upstream application ran out of memory (OOM killed), causing the process to disappear.

502 vs 503 vs 504

Code Meaning Cause
502 Bad Gateway Upstream returned invalid response or connection refused
503 Service Unavailable Server intentionally rejecting (overloaded/maintenance)
504 Gateway Timeout Upstream did not respond within timeout

Prevention

  1. Health checks — Configure proxy to check upstream health
  2. Process managers — Use PM2, systemd, or supervisord to auto-restart
  3. Monitoring — Alert on upstream process crashes
  4. Graceful shutdown — Drain connections before stopping upstream
  5. Multiple upstreams — Load balance across several instances

Use Case

502 errors are the primary indicator of backend failures in production systems using reverse proxies. Whether you run Nginx, HAProxy, AWS ALB, or Cloudflare, understanding the proxy-upstream relationship and how to quickly identify whether the issue is in the proxy configuration, the upstream application, or the network between them is essential for incident response.

Try It — Error Code Reference

Open full tool