On this pageWhat each code tells you
A 502 or a 504 is the reverse proxy reporting on someone else. Nginx received the request, handed it to an upstream such as PHP-FPM, a Node or Python app server, or a container, and that conversation failed. Restarting Nginx almost never helps, because Nginx is the messenger. The fix lives in the upstream or in the link between the two, and the error log tells you which. A 505 is a different and much rarer animal, covered at the end.
What each code tells you
| Code | Generated by | What happened | Look first at |
|---|---|---|---|
| 502 Bad Gateway | The proxy | The upstream refused the connection, crashed, closed it early or answered with garbage | Nginx error log, upstream service status |
| 503 Service Unavailable | The proxy or the app, on purpose | Maintenance mode, rate limiting or overload protection | Your own limits and maintenance switches |
| 504 Gateway Timeout | The proxy | The upstream accepted the request but did not answer in time | Slow requests, timeouts along the chain |
| 505 HTTP Version Not Supported | Whatever parses the request | The request named an HTTP version the server will not speak | The client or the device in front of the server |
If a CDN or a hosted proxy sits in front of your server, check whose error page you are looking at. Cloudflare, for example, documents that a Cloudflare-branded 502 or 504 page means the error came from your origin server, and it uses its own 52x codes when it cannot get a proper answer from you: 521 when the server refuses the connection, 522 when the connection times out, and 524 when the server takes longer than the proxy's read timeout, 125 seconds by default.
Start with the error log
sudo tail -n 50 /var/log/nginx/error.log
sudo journalctl -u php8.3-fpm --since "15 min ago" --no-pager
The message on the line that matches the failed request names the cause more often than not:
Message in error.log |
Meaning |
|---|---|
connect() failed (111: Connection refused) while connecting to upstream |
Nothing listens on that address and port |
connect() to unix:/run/php/php8.3-fpm.sock failed (2: No such file or directory) |
Wrong socket path, or PHP-FPM is not running |
connect() to unix:... failed (11: Resource temporarily unavailable) |
PHP-FPM's queue is full: every worker is busy |
... failed (13: Permission denied) while connecting to upstream |
Socket permissions, or SELinux blocking the connection |
upstream prematurely closed connection while reading response header from upstream |
The upstream died or was killed mid-request |
upstream sent too big header while reading response header from upstream |
Response headers, usually cookies, exceed Nginx's buffer |
no live upstreams while connecting to upstream |
Every server in an upstream group is marked as failed |
upstream timed out (110: Connection timed out) while reading response header from upstream |
A 504: the upstream was too slow |
Fix a 502: the upstream is down or unreachable
PHP-FPM
Check that the service runs and that Nginx points at a socket that exists:
systemctl status php8.3-fpm --no-pager
ls -l /run/php/
grep -rn "fastcgi_pass" /etc/nginx/sites-enabled/
The classic 502 after a PHP upgrade is a socket name that changed, from php8.3-fpm.sock to a newer version's, while the server block still names the old one. Fix fastcgi_pass, then sudo nginx -t && sudo systemctl reload nginx.
Resource temporarily unavailable means all workers were busy and the backlog overflowed. The PHP-FPM log will also say server reached pm.max_children setting. Raising pm.max_children in the pool file helps only if memory allows it, so measure first:
ps -C php-fpm8.3 -o rss= | awk '{ s += $1; n++ } END { printf "%d workers, %.0f MB average\n", n, s / n / 1024 }'
Divide the memory you can spare for PHP by that average. More children than memory can hold turns a 502 into swapping, which is worse.
App servers and containers
For Node, Gunicorn, Uvicorn or a container, first talk to the upstream directly from the server, bypassing Nginx:
ss -ltnp | grep 3000
curl -sv http://127.0.0.1:3000/ -o /dev/null
No listener means the app crashed or listens somewhere else. A container may publish a different port than the one in proxy_pass, or the app inside it may bind to 127.0.0.1 in the container, which is unreachable from the host. Prefer an explicit 127.0.0.1 over localhost in proxy_pass, so Nginx does not try an IPv6 address the app never listens on.
Crashes and the OOM killer
upstream prematurely closed connection means the process died while working. Check whether the kernel killed it for memory:
sudo journalctl -k --since "1 hour ago" | grep -i -E "out of memory|killed process"
If it did, reduce the number of workers, fix the leak, or add memory. A CloudSat server can be resized to a bigger plan from the console when the workload has simply outgrown it.
SELinux on AlmaLinux and Rocky Linux
Permission denied on a TCP upstream, with everything else correct, is often SELinux refusing to let Nginx open network connections:
getsebool httpd_can_network_connect
sudo setsebool -P httpd_can_network_connect 1
Oversized headers
Applications that set many or large cookies trip Nginx's response header buffer. Raise it for that site only:
proxy_buffer_size 16k;
proxy_buffers 8 16k;
# for PHP-FPM, the FastCGI equivalents:
fastcgi_buffer_size 32k;
fastcgi_buffers 16 16k;
Fix a 504: the upstream is too slow
A 504 means the upstream is alive and slow. Raising timeouts hides that; find the slow request first. Log how long the upstream took, in the http block:
log_format timing '$remote_addr "$request" $status rt=$request_time urt=$upstream_response_time';
access_log /var/log/nginx/timing.log timing;
Requests whose urt sits near 60 seconds are the ones hitting Nginx's default read timeout. The usual causes are a slow database query, an external API that hangs, or a report or export that should run as a background job instead of inside a web request. Fix those, and the 504s go away without touching a timeout.
When a long request is legitimate, raise the limit for that location only, and keep the inner layers shorter than the outer ones:
location /admin/export {
proxy_read_timeout 300s;
proxy_pass http://127.0.0.1:8000;
}
| Layer | Setting | Default |
|---|---|---|
| Nginx to HTTP upstream | proxy_read_timeout |
60 s |
| Nginx to PHP-FPM | fastcgi_read_timeout |
60 s |
| PHP | max_execution_time |
30 s |
| PHP-FPM pool | request_terminate_timeout |
0 (off) |
| Gunicorn | --timeout |
30 s |
The order matters. If the app server kills a worker at 30 seconds, Nginx sees a closed connection and reports a 502, not a 504. When every inner timeout is shorter than the one outside it, the application fails first, logs its own error, and the proxy never has to guess.
The rare 505
RFC 9110 defines 505 as the server refusing the major version of HTTP used in the request. Browsers do not trigger it. Nginx returns it when the request line names a major version above 1, such as HTTP/2.0 written as plain text on a connection that only speaks HTTP/1.x. It logs the reason at the info level, which the default error_log level hides.
The usual sources are scripts or devices, not people:
- A hand-written client that builds request lines itself and sends the wrong version string.
- A load balancer or tunnel forwarding HTTP/2 traffic to a backend port that only speaks HTTP/1.1.
You can reproduce it to compare behaviors:
printf 'GET / HTTP/2.0\r\nHost: example.com\r\n\r\n' | nc 127.0.0.1 80
curl -sv --http1.1 http://example.com/ -o /dev/null
If the first command returns a 505 and the second works, the server is fine and the client or the device in front of it needs fixing.
Prevent the next one
- Monitor a page that touches the database, not just the home page from a cache, so an outage shows up before your visitors report it.
- Restart crashed upstreams automatically:
Restart=on-failurein the systemd unit, orrestart: unless-stoppedin Docker Compose. - Keep the timing log from the 504 section. A slow endpoint usually creeps up for weeks before it times out.
- Test configuration before every reload with
sudo nginx -t. A failed reload keeps the old configuration running, which hides the mistake until the next restart.
FAQ
Is a 502 the hosting provider's fault?
On a server you run, both Nginx and the upstream are yours, so start with your own logs. If the error page comes from a CDN or proxy in front of you, that layer is telling you it could not get a good answer from your server, which still points back to the server's logs.
Why do I get a 502 for a slow request instead of a 504?
Because an inner timeout fired first. An app server or PHP-FPM killed the request, the connection closed, and Nginx reported a bad gateway. Compare the timeouts in the table above.
Should I raise every timeout to five minutes?
No. Long timeouts tie up workers and connections while users wait, so one slow endpoint can exhaust the pool for everyone. Raise them only for the locations that need it, and move long jobs out of the request path.
Run it on CloudSat. Cloud VPS on AMD EPYC and NVMe from $1.98/mo in 13 regions, delivered in under 5 minutes and paid in crypto. See plans or deploy a server.




