Nginx 502 Bad Gateway: How to Diagnose and Fix It
A 502 means nginx reached your upstream but got an invalid (or no) response. Nginx itself is fine — the answer is in the error log and the state of the backend. Here's how to read it.
Step 1 — Read the error log
sudo tail -n 50 /var/log/nginx/error.log
The exact message tells you the cause:
- connect() failed (111: Connection refused) — the backend isn't listening; it's down or on the wrong port.
- upstream prematurely closed connection — the backend started replying then crashed or timed out (often a PHP-FPM worker dying, or an app exception).
- no live upstreams — every server in the upstream block is marked down.
- upstream sent too big header — the response headers exceed nginx's buffer.
Step 2 — Check the backend is up
sudo systemctl status php8.3-fpm # or your app service
ss -ltnp | grep -E ':8080|php-fpm|\.sock'
If the service is down, start it and confirm it's listening on the address/port (or socket) that nginx points to. A wrong proxy_pass / fastcgi_pass target is a common cause after a config change.
Step 3 — Fix by cause
- Backend down/refused: restart the upstream service; fix the
proxy_pass/fastcgi_passaddress or socket path; for a Unix socket, check its permissions/ownership so nginx can read it. - Premature close / timeouts: raise
proxy_read_timeout/fastcgi_read_timeoutfor slow responses, and fix the crashing worker (check the app/FPM log). - Too big header: increase
proxy_buffer_size/fastcgi_buffer_size(and the buffers count).
After any change: sudo nginx -t && sudo systemctl reload nginx.
How Tech Matrix solves this in ~60 seconds
Every 502 has a precise reason in the error log, but mapping it to the backend, the proxy_pass target, socket permissions or buffer sizes takes time. Tech Matrix reads the nginx error log and your upstream/service state together, names the exact cause, and gives the matching fix for your config — with your approval before any reload.
Frequently asked questions
Nginx reached the upstream backend but got an invalid or no response. The backend is down, unreachable, crashing mid-response, or sending headers too large for nginx's buffers.
Read /var/log/nginx/error.log. Messages like 'connection refused', 'upstream prematurely closed connection', 'no live upstreams', or 'upstream sent too big header' each point to a specific cause.
Confirm the FPM service is running and listening on the socket/port nginx points to, fix the fastcgi_pass target and socket permissions, raise fastcgi_read_timeout for slow scripts, and reload nginx.