502 Bad Gateway (nginx): causes and how to fix it
502 Bad Gateway means nginx (acting as a reverse proxy) connected to your upstream application but received an invalid or empty response — the app crashed, isn't listening, or closed the connection.What causes 502 Bad Gateway
The upstream app (PHP-FPM, Node, Gunicorn, etc.) is down or crashing; the wrong upstream host/port/socket in the nginx config; the app restarted mid-request; or the upstream closed the connection due to its own error.
How to diagnose it
Check the nginx error log: tail -f /var/log/nginx/error.log — it names the upstream and reason (e.g. connect() failed (111: Connection refused)). Confirm the app is listening on the proxy_pass / upstream target.
How to fix 502 Bad Gateway
- Restart and verify the upstream app. Make sure your app process (PHP-FPM, Gunicorn, Node) is running and listening on the expected port or socket.
- Check the nginx upstream config. Confirm
proxy_pass/upstreampoints at the right host:port or unix socket, thennginx -t && systemctl reload nginx. - Raise timeouts if the app is slow. Increase
proxy_read_timeout/proxy_connect_timeout, and fix the slow upstream (a 504 is the timeout variant).
Example log line
2026/10/05 02:14:11 [error] 920#920: *5 connect() failed (111: Connection refused) while connecting to upstream, client: 1.2.3.4, upstream: "http://127.0.0.1:8000/"
How LogLens detects 502 Bad Gateway
LogLens flags 502 spikes in nginx access logs and correlates them with the upstream app's crash or restart lines. LogLens AI is a free, self-hosted AI log analyzer that surfaces lines like this automatically, groups them into one incident, and explains them in plain language.
Related errors
FAQ
What is the difference between 502 and 504?
502 means the upstream gave an invalid/no response (often down or crashed). 504 means the upstream was reached but did not respond within nginx's timeout (too slow).
Why do I get 502 only sometimes?
Intermittent 502s usually mean the upstream is crash-looping or restarting, or you have too few worker processes for the load.