nginx 502 Bad Gateway: what it means and how to find the break
nginx returns 502 Bad Gateway when it acts as a proxy and receives an invalid response from the upstream server, or no usable response at all. That narrows the problem to the chain between nginx and your backend, which is exactly where this checklist looks. Sources: MDN for the status code semantics and the official NGINX admin guide for the proxy configuration.
What 502 actually means
Per MDN, 502 is specific to the point in the request chain where things broke: the gateway (nginx) got something invalid from the origin. Two useful distinctions: if the origin sent a valid HTTP error, nginx passes that through instead of a 502, and if the origin never answered at all, the client sees 504 Gateway Timeout instead.
Checklist, in order
- Is the backend up? Check the app itself (its process, its port). nginx can only proxy to something that listens.
- Does proxy_pass point at the right place? The NGINX admin guide passes requests to an HTTP proxied server with
proxy_passinside a location:location /app/ { proxy_pass http://127.0.0.1:8000; }Confirm the IP and port match what your backend actually binds. A backend that moved from8000to8080is a classic 502 cause. - Trailing slashes and paths: the guide notes the difference between
proxy_pass http://host/link/;(URI is replaced) and a URI-less form; a mismatch can send requests to paths the backend does not serve. - More than one backend? The guide covers named server groups: define an
upstreamblock with several servers and proxy to the group, so requests are distributed and one sick backend matters less. - Source IP restrictions: if your backend accepts connections only from particular IP ranges and your proxy has several interfaces, the guide's
proxy_binddirective lets you choose the source address nginx connects from.
Quick diagnosis table
| Symptom | Likely cause | Check |
|---|---|---|
| 502 on every request | Backend down or wrong proxy_pass target | Backend process and port |
| 502 on some paths only | proxy_pass URI replacement mismatch | Trailing slashes in location and proxy_pass |
| 504 instead of 502 | Backend accepts but never answers | Backend hang, not a refused connection |
Client-side note from MDN: if the site works for other visitors, a visitor's own network (VPN, DNS, proxy settings) can produce 502s too; that is the exception, not the rule.
Working with Docker backends? Read Docker Compose .env files and variables to keep ports and hosts consistent across environments. For managed help, see monitoring and support.
