502 Bad Gateway: Causes and How to Fix It
A 502 Bad Gateway means a proxy (nginx, Apache, a load balancer or a CDN) tried to get a response from the application behind it and got nothing usable back. The proxy is alive; the thing it forwards to is down, unreachable or answering garbage. This guide walks through the causes in the order you are most likely to hit them, with the log lines that identify each one, the commands to confirm it and the config change that fixes it.
Where a 502 comes from
A typical modern stack has at least two hops: client → proxy → upstream. The upstream might be PHP-FPM behind nginx, a Node.js or Gunicorn process behind nginx, or your whole server behind Cloudflare. A 502 is generated by the proxy when:
- it can't connect to the upstream at all (nothing listening, wrong address, permission denied);
- the upstream accepted the connection but closed it before sending a valid response (it crashed or was killed mid-request);
- the upstream sent a response the proxy can't accept (for example headers too large for the buffer).
If instead the upstream is alive but too slow, you get a 504 Gateway Timeout, which has its own causes; see diagnosing 504 Gateway Timeout and slow responses.
Step 1: read the proxy's error log
The browser page says almost nothing. The nginx error log says exactly what went wrong:
sudo tail -n 50 /var/log/nginx/error.log
# or follow it while you reproduce the error
sudo tail -f /var/log/nginx/error.log
Match the message against this table:
| nginx error log contains | Meaning | Go to |
|---|---|---|
connect() failed (111: Connection refused) | Nothing listening on that host:port | Upstream down |
connect() to unix:/run/php/... failed (2: No such file or directory) | Socket file doesn't exist | Upstream down, or socket path wrong |
connect() to unix:... failed (13: Permission denied) | nginx can't open the socket | Socket permissions (or SELinux) |
connect() to unix:... failed (11: Resource temporarily unavailable) | Socket backlog full; all workers busy | Overloaded upstream |
upstream prematurely closed connection while reading response header | Upstream died or killed the request mid-flight | Crashes, OOM kills, worker timeouts |
recv() failed (104: Connection reset by peer) | Upstream reset the connection | Crashes, OOM kills, worker timeouts |
upstream sent too big header while reading response header | Response headers exceed the buffer | Buffers |
no live upstreams while connecting to upstream | Every server in the upstream block is marked failed | Upstream down (all of them) |
On Apache with mod_proxy, look in the error log for AH01102 ("error reading status line from remote server") or AH00957 / AH01114 (the connection to the backend failed); the logic below applies the same way.
Cause 1: the upstream service is down
By far the most common cause. PHP-FPM was stopped by a package upgrade, the Node process crashed and nothing restarted it, Gunicorn failed to start after a deploy because of an import error.
# is the service running? (adjust the name: php8.3-fpm, gunicorn, your-app)
systemctl status php8.2-fpm
journalctl -u php8.2-fpm --since "30 min ago"
# is anything listening where nginx expects it?
sudo ss -ltnp | grep ':3000' # TCP upstream
ls -l /run/php/ # unix sockets
Fix: start it, then find out why it stopped. Read the service's journal before restarting: a Python traceback, EADDRINUSE or a syntax error in the pool config tells you whether it will just die again. For PHP-FPM, sudo php-fpm8.2 -t validates the configuration. For Node apps run under a plain node server.js in a terminal or screen, move them to a systemd unit with Restart=on-failure so a crash doesn't become an outage.
Brief 502s during deployments are the same cause on a smaller scale: the app restarts and for a few seconds nothing is listening. Use graceful reloads (systemctl reload php8.2-fpm, kill -HUP for Gunicorn's master process) instead of stop/start.
Cause 2: wrong socket path or permissions
nginx's fastcgi_pass must point at exactly the socket PHP-FPM creates. After a PHP upgrade the socket name changes (php8.1-fpm.sock becomes php8.3-fpm.sock) while the nginx config still references the old one.
# what the pool actually listens on
grep -R '^listen' /etc/php/*/fpm/pool.d/
# what nginx expects
grep -R 'fastcgi_pass' /etc/nginx/
If the path is right but you see Permission denied, the socket's owner or mode doesn't allow the nginx user (www-data on Debian/Ubuntu, nginx on RHEL-family systems). In the pool file:
listen = /run/php/php8.2-fpm.sock
listen.owner = www-data
listen.group = www-data
listen.mode = 0660
Reload PHP-FPM after the change. On RHEL, CentOS, Rocky or Alma Linux, a Permission denied when proxying to a TCP port is often SELinux, not file permissions. Check sudo ausearch -m avc -ts recent; if it confirms the denial, sudo setsebool -P httpd_can_network_connect 1 allows nginx to make outbound connections.
Cause 3: the upstream crashes or gets killed
upstream prematurely closed connection means the worker handling the request vanished. The usual suspects:
- Out-of-memory killer. When the server runs out of RAM, the kernel kills the biggest process, often a PHP-FPM or Node worker. Check with:
Fix it by reducing concurrency (sudo dmesg -T | grep -iE 'out of memory|killed process' sudo journalctl -k --since today | grep -i oompm.max_childrenin PHP-FPM, Gunicorn--workers) so the workers fit in memory, by lowering per-request memory (big exports, image processing), or by adding RAM or swap. A rough sizing for PHP-FPM: available RAM for PHP divided by the typical worker size fromps -o rss -C php-fpm8.2. - Application-level timeouts. Gunicorn kills workers that exceed
--timeout(30 seconds by default) and logsWORKER TIMEOUT; PHP-FPM'srequest_terminate_timeoutdoes the same. nginx sees a closed connection and reports 502, even though the root problem is slowness. Fix the slow request, or raise the timeout deliberately. - Segfaults in PHP extensions or native Node modules. Look for
SIGSEGVin/var/log/php8.2-fpm.logor the service journal. These often follow an extension upgrade.
Cause 4: the upstream is overloaded
When all PHP-FPM workers are busy, new connections queue in the socket backlog. When that fills up, nginx gets Resource temporarily unavailable and returns 502. PHP-FPM logs the warning ahead of time:
sudo grep 'max_children' /var/log/php8.2-fpm.log
# WARNING: [pool www] server reached pm.max_children setting (5), consider raising it
Raising pm.max_children helps only if there is memory for more workers (see the OOM section). Often the real fix is finding what keeps workers busy: slow database queries, calls to an external API without a timeout, or a bot crawling expensive pages. Enabling PHP-FPM's slow log (slowlog plus request_slowlog_timeout = 5s) shows the stack traces of slow requests.
Cause 5: response headers too big for the buffer
upstream sent too big header appears when the application sends headers larger than nginx's buffer, typically big cookies, many Set-Cookie lines or a long Content-Security-Policy. The defaults are one memory page (4k or 8k). Raise them in the relevant location or server block:
# for PHP-FPM (fastcgi_pass)
fastcgi_buffer_size 32k;
fastcgi_buffers 16 16k;
fastcgi_busy_buffers_size 64k;
# for proxy_pass upstreams (Node, Gunicorn, another server)
proxy_buffer_size 16k;
proxy_buffers 8 16k;
proxy_busy_buffers_size 32k;
Run sudo nginx -t before reloading: nginx refuses *_busy_buffers_size values smaller than the largest single buffer or larger than the total buffers minus one buffer. And ask why the headers are so large; a session cookie growing without bound is a bug worth fixing.
Cloudflare 502 vs origin 502
If your site is behind Cloudflare (or another CDN), first establish who generated the error:
- A plain page saying "502 Bad Gateway" with
nginxat the bottom came from your origin, and Cloudflare just passed it through. Everything above applies. - A Cloudflare-branded error page with a Ray ID means Cloudflare itself couldn't get a valid response from your origin. Cloudflare also uses its own 5xx codes for specific problems: 521 (origin refused the connection), 522 (connection timed out), 523 (origin unreachable), 524 (origin took too long), 525 (TLS handshake with origin failed) and 526 (invalid origin certificate).
To bypass the CDN and talk to the origin directly while keeping the right hostname and SNI:
curl -sI --resolve example.com:443:203.0.113.10 https://example.com/
Replace 203.0.113.10 with your origin IP. If this returns 200 while the public URL returns 502, look at the path between the CDN and the origin: a firewall blocking the CDN's IP ranges, an SSL mode mismatch, or the origin rate-limiting the CDN.
Diagnosis cheat sheet
curl -s -o /dev/null -w '%{http_code}\n' https://example.com/to confirm the 502 and whether it is constant or intermittent.sudo tail -n 50 /var/log/nginx/error.logand match the message to the table above.systemctl status <upstream>andjournalctl -u <upstream>.ss -ltnporls -l /run/php/to confirm something is listening where nginx points.dmesg -T | grep -i killedfor OOM kills.- Check the upstream's own log for
max_children,WORKER TIMEOUTor segfaults. - Behind a CDN:
curl --resolveto the origin to split the problem in two.
Key takeaways
- A 502 means the proxy is fine and its upstream failed; the proxy's error log names the exact reason.
- Most 502s are a stopped or crashed upstream service, or a socket path that changed with a PHP upgrade.
- Intermittent 502s under load point to OOM kills, worker timeouts or exhausted worker pools.
- "Too big header" is fixed with buffer sizes, but large headers are worth investigating.
- Behind Cloudflare, check whether the error page is Cloudflare's or your origin's before debugging.
Argos Uptime tags 502s and other server errors with the server_5xx cause and captures a screenshot when the site changes state, so you can see at a glance whether visitors got your origin's error page or your CDN's. Because a 502 is so often "the upstream stopped", it is also a good fit for an automated SSH recovery action: run systemctl restart php8.2-fpm once downtime reaches your threshold, limited to server_5xx failures so it never fires on a DNS or SSL problem. For a broader view of error codes, see HTTP status codes explained, and compare plans for check intervals down to one minute.