A 502 is nginx telling you it reached out to your application and got back nothing it could use. The reflex is to restart nginx. The fault is almost never nginx.
When a 502 Bad Gateway lands in production, the pressure is to do something visible. Restarting the web server feels like doing something. It almost never helps, because nginx is the proxy, not the origin of the problem: it dialled your upstream, and the upstream refused, closed the connection, or answered with something nginx could not parse. The fix is to work the error backwards from the one line nginx already wrote down, not to guess. Here is the order I run every time, on nginx 1.26.
Who this is for
- The engineer holding the pager when a Django, Rails, Node or FastAPI app behind nginx starts throwing 502s and the deploy that caused it is not obvious.
- The sysadmin who moved an app onto RHEL, Rocky or Alma and hit a 502 that never appeared on the old Ubuntu box — because SELinux is now in the way.
- The founder-CTO who owns the whole stack and needs a repeatable diagnosis rather than a folk remedy pulled off a forum.
Read the error before you touch anything
nginx logs the exact reason for a 502 in its error log. That line tells you which of the four common causes you are dealing with, so read it first and let it route the rest of the work.
Free · 4 minutes
Is your engineering team shipping safely, or quietly accumulating risk?
Fourteen questions on how work gets from idea to production — cadence, testing, rollback, and the key-person risk in your delivery. Banded finding on screen, full sheet by email.
# The last upstream errors nginx actually recorded
sudo tail -n 50 /var/log/nginx/error.log
# On a systemd host the same errors also surface here
journalctl -u nginx --since "10 min ago" --no-pager
You are looking for one of these, each of which points somewhere different:
- connect() failed (111: Connection refused) — the upstream is not listening where nginx expects it.
- connect() to unix:/run/app.sock failed (13: Permission denied) — the socket exists but nginx is not allowed to open it. This is the SELinux and file-permission case.
- no live upstreams while connecting to upstream — nginx has marked every backend in the pool as down after repeated failures.
- upstream prematurely closed connection while reading response header — the app accepted the connection and then died or timed out mid-request.
- upstream sent too big header — the response is valid but larger than nginx’s header buffer.
Is the upstream actually listening?
For a “Connection refused”, the question is blunt: is anything bound to the address nginx is proxying to? Confirm it with ss rather than assuming. The flags are -l listening, -t TCP, -n numeric (do not resolve ports to names), -p process.
# TCP backend: is anything listening on the port nginx proxies to?
sudo ss -ltnp | grep ':8000'
# Unix-socket backend: list listening unix sockets (-x)
sudo ss -lxnp | grep app.sock
# Reproduce nginx's own request against the backend, bypassing nginx entirely
curl -v http://127.0.0.1:8000/health
curl -v --unix-socket /run/app.sock http://localhost/health
Two failure modes show up here. If ss returns nothing, the app is not running — check its own service (systemctl status and its logs) and stop touching nginx. If ss shows it bound to 127.0.0.1:8001 while your proxy_pass points at :8000, you have a mismatch. And a subtle one: an app bound to 127.0.0.1 is unreachable from nginx if your proxy_pass resolves to the machine’s LAN address, and vice versa. The curl against the backend settles it — if curl gets a clean response and nginx does not, the app is fine and the problem is between them.
Permission denied: file mode, then SELinux
A “13: Permission denied” on a unix socket has two layers. First the ordinary one: the nginx worker runs as nginx or www-data, and if the socket is mode 0660 owned by your app’s user and group, nginx is not in that group and cannot open it. Fix the socket’s group or permissions in the app’s own service definition, not in nginx.
Then the layer that catches people migrating to RHEL-family hosts: SELinux. By default SELinux does not let the web server make network connections or reach a socket outside its expected contexts, and it does this silently as far as nginx’s own log is concerned — the denial lands in the audit log. This is the single most common reason a config that worked on Ubuntu throws 502s on Rocky.
# RHEL / Rocky / Alma: find the denial nginx triggered
sudo ausearch -m avc -ts recent | grep nginx
# The usual culprit: the web server is not allowed to open network connections
getsebool httpd_can_network_connect
sudo setsebool -P httpd_can_network_connect 1 # -P makes it persist a reboot
# Debian / Ubuntu equivalent: check AppArmor and the kernel log
sudo aa-status
sudo dmesg | grep -i denied
Set httpd_can_network_connect only if the app is on a different host or a TCP port; for a local unix socket the fix is usually the correct file context on the socket path instead. Do not disable SELinux to make a 502 go away — you are removing a control to paper over a two-line boolean.
Under load, and the 504 next door
“upstream prematurely closed connection” and “no live upstreams” are load and stability symptoms. The app worker is being killed mid-request — an application-level timeout (Gunicorn’s default 30-second worker timeout is a classic), an out-of-memory kill, or a crash under concurrency. nginx faithfully reports the disconnect as a 502; the cause lives in the app, so read its logs. If nginx has marked the whole pool down, it is because max_fails failures inside fail_timeout tripped, and it will retry once the window passes.
Worth knowing precisely: if the app is merely slow and nginx gives up waiting, you get a 504 Gateway Timeout, not a 502 — the log line is “upstream timed out”. Different error, adjacent diagnosis. nginx’s proxy_connect_timeout, proxy_read_timeout and proxy_send_timeout all default to 60 seconds. Raising them hides a slow endpoint rather than fixing it, but a large-header 502 is a genuine buffer fix:
location / {
proxy_pass http://127.0.0.1:8000;
proxy_connect_timeout 5s; # fail fast if the backend is down
proxy_read_timeout 60s; # default; raise only for genuinely long requests
# Fixes: "upstream sent too big header while reading response header"
proxy_buffer_size 16k;
proxy_buffers 4 16k;
proxy_busy_buffers_size 32k;
}
Then validate and reload rather than restart, so a config typo cannot take the site fully down:
sudo nginx -t && sudo systemctl reload nginx
If you are here because the proxy layer itself is fighting your app — headers dropped, the wrong host passed through — the underlying config is worth getting right once; I walk through a clean version in an nginx reverse proxy config that passes the right headers to your app. This is the same genre of fix as reading the machine backwards from its own error output, which is exactly how I approach stubborn BorgBackup lock errors too.
Where this fits
A 502 that recurs is rarely a one-off; it is usually an operational gap — no alerting on the app process, no health check nginx can act on, no runbook that starts with the error log. Building that muscle is part of what I do as a fractional CTO through my fractional CTO and delivery services: turning firefights into a diagnosis anyone on the team can run. Engagements are fixed monthly retainers rather than day rates, so the incident work and the prevention work are the same budget line.
The discipline is simple and it holds under pressure: a 502 is a message from nginx about someone else. Read what it actually said, reproduce it with curl, and fix the thing it named — not the proxy that reported it.
Build and rescue work
Hands-on delivery of this kind is handled by Sixteen Pillars Studio.
Free interactive tool
Website compliance checklist
What your site has to do, based on what it actually does
Answer as much or as little as you like — the list builds as you go. Nothing is stored against your name and no email is required.
Everything that applies
Ordered by what to do first: legal requirements you can close quickly, then larger pieces of work, then what is expected rather than required. Not exhaustive, and not a legal audit.
Dated PDF, yours to keep or circulate.
Most technology problems are not technology problems. They are control problems.
The systems exist. The investment has been made. The question is whether leadership can understand, direct, evidence, and sustain what those systems produce. Find out where control exists — and where it only appears to.