To fix an NGINX 502 Bad Gateway, run sudo tail -n 100 /var/log/nginx/error.log and find the line containing upstream. A 502 means NGINX itself is working, but the backend it proxies to (PHP-FPM, Node.js, a backend API, a Docker container) refused the connection, died mid-reply, or sent a response NGINX couldn't use. The error log line tells you which, and the fix follows from it:
| Error log says | Most likely cause | Jump to |
|---|---|---|
connect() failed (111: Connection refused) |
Backend is down, or NGINX points at the wrong address/port | Cause 1, Cause 4 |
upstream prematurely closed connection |
Backend crashed or killed the request mid-response | Cause 2 |
upstream sent too big header |
Response headers exceed NGINX's buffer | Cause 3 |
unix:/...php-fpm.sock failed (13: Permission denied) or (2: No such file or directory) |
PHP-FPM socket permissions or path | Cause 5 |
connect() failed (13: Permission denied) on a TCP upstream |
SELinux blocking the connection | Cause 6 |
SSL_do_handshake() failed ... while SSL handshaking to upstream |
TLS mismatch with an HTTPS backend | Cause 7 |
If the error page footer says something like nginx/1.24.0 (Ubuntu), that's just NGINX's version string (shown because server_tokens defaults to on) — it tells you which server answered, not what broke.
This post covers the seven causes that cover the large majority of 502s, in roughly the order of how often they show up, with the exact diagnostic commands and configuration fixes for each.
Always start with the error log
Before reading any further, run this:
sudo tail -n 100 /var/log/nginx/error.log
NGINX writes the actual cause of every 502 to the error log with a clear upstream line. A typical entry:
2026/05/23 14:23:01 [error] 1812#0: *5234 connect() failed (111: Connection refused)
while connecting to upstream, client: 203.0.113.45, server: example.com,
request: "GET /api/users HTTP/1.1", upstream: "http://127.0.0.1:3000/api/users",
host: "example.com"
The bracketed error code (111: Connection refused, 104: Connection reset by peer, 13: Permission denied) plus the upstream: URL tell you everything you need to start. The rest of this post is essentially a translation table for those error codes — keep the log open in another terminal while you work through the causes below.
If /var/log/nginx/error.log is empty or doesn't exist, your NGINX may be writing to journald instead — try sudo journalctl -u nginx -n 100. The Linux server commands guide covers the wider set of log-reading commands.
Cause 1: The upstream process isn't running
The most common 502 cause is your backend application crashed or never started.
The error log line reads:
connect() failed (111: Connection refused) while connecting to upstream
Connection refused is the kernel saying nothing is listening on that port.
NGINX did its job; there's just no application to forward to.
Confirm whether the upstream is up:
sudo ss -tlnp | grep :3000 # replace with whatever port NGINX is forwarding to
If you see nothing, the upstream is down. Start it (or check why it crashed) — for a systemd-managed service:
sudo systemctl status myapp
sudo systemctl start myapp
sudo journalctl -u myapp -n 200
For a Docker container:
docker ps -a | grep myapp # is it running, or exited?
docker logs myapp --tail 200 # what did it say before dying?
docker start myapp # bring it back
A surprising number of 502s in production are this — a deploy crashed silently, OOMKiller reaped the process, a startup error wasn't caught. Fix the upstream and the 502 goes away.
If the 502 started with a release, the fastest way to stop the bleeding is usually to put the previous version back and debug from there. DeployHQ's one-click rollback redeploys the last working release in a single step, so you can investigate the crash without users staring at a 502.
Cause 2: The upstream is slow, and something gives up waiting
The error log line for a 502:
upstream prematurely closed connection while reading response header from upstream
This means the backend closed the connection before sending a complete response. With slow requests, the usual culprit is the application server's own timeout, which can be shorter than NGINX's (Gunicorn's timeout defaults to 30 seconds; PHP-FPM's request_terminate_timeout is off by default but often set): when either expires, the worker handling the request is killed, the connection drops, and NGINX reports a 502. Check the app server's log for a worker timeout or kill message at the same timestamp, and raise that limit — or fix the slow request — first.
502 vs 504: if NGINX's own timeout expires, you get a different status. A line like upstream timed out (110: Connection timed out) while reading response header from upstream produces a 504 Gateway Timeout, not a 502 — NGINX's upstream code maps timeouts to 504 and connection errors or invalid responses to 502. If your users see 504s, the NGINX settings below are the ones to tune.
NGINX has built-in timeouts for connecting to the upstream, sending the request, and reading the response. The relevant settings live in the http, server, or location block:
http {
proxy_connect_timeout 60s; # default; the OS usually caps connects at ~75s, so raising it rarely helps
proxy_send_timeout 60s; # how long to wait between two writes of the request
proxy_read_timeout 60s; # time between two reads of the response, not the whole response (the big one)
}
Defaults are 60 seconds. For an API call that does a slow database query, an LLM request, or anything that legitimately takes a while, bump proxy_read_timeout to whatever your real upper-bound is:
location /api/slow-report {
proxy_pass http://backend;
proxy_read_timeout 300s;
}
Apply the change and reload (not restart — reload picks up config without dropping in-flight connections):
sudo nginx -t # test the config first
sudo systemctl reload nginx
Watch out for the flip side: raising the timeout doesn't fix a slow query; it just hides the symptom. If you're hitting a 60-second timeout on what should be a 2-second endpoint, the upstream has a real performance problem to investigate — adding 4 minutes of patience won't make it faster.
Cause 3: Buffer issues on large response headers
The error log line:
upstream sent too big header while reading response header from upstream
NGINX has fixed-size buffers for the upstream's response headers. Some applications (Laravel with verbose session cookies, some SSO implementations, anything that returns a lot of Set-Cookie headers) exceed the default and trigger a 502.
Bump the buffer sizes:
location / {
proxy_pass http://backend;
proxy_buffer_size 128k;
proxy_buffers 4 256k;
proxy_busy_buffers_size 256k;
}
proxy_buffer_size is the buffer for the response header line; proxy_buffers is the number and size of buffers for the response body. The default proxy_buffer_size is 4k or 8k depending on platform, which is often too small for modern apps.
This is the 502 that's hardest to diagnose without reading the log carefully — the upstream is healthy, response times are normal, but the response itself is malformed-looking to NGINX. The fix is purely configuration.
Cause 4: The upstream address in nginx.conf is wrong
The error log line:
connect() failed (111: Connection refused) while connecting to upstream, upstream: "http://10.0.0.5:8080/..."
If the upstream IP or port is wrong — typo, a container that was renamed, a service that moved to a different port after a refactor — you get the same connection refused as Cause 1, but the actual upstream is fine. Compare the upstream: URL in the error log to what's actually listening:
sudo ss -tlnp # what's actually listening locally
docker ps # what containers are running and on what ports
For dynamic backends (upstream backend { server backend.example.com:8080; }), confirm DNS resolves correctly from the NGINX host:
dig backend.example.com
curl -v http://backend.example.com:8080/health
A common variant: NGINX caches DNS resolution at config-load time. If your backend's IP changed (autoscaling, a container restart in Docker Compose), NGINX keeps using the old address until you reload it. Adding a resolver directive and a variable in proxy_pass forces per-request resolution:
location / {
resolver 1.1.1.1 valid=30s;
set $backend "backend.example.com";
proxy_pass http://$backend:8080;
}
On NGINX 1.27.3 and newer you can keep a normal upstream block instead: the resolve parameter on server, which used to be commercial-only, is now in open-source NGINX. It needs a shared-memory zone and a resolver:
upstream backend {
zone backend 64k;
resolver 127.0.0.53 valid=30s; # or your internal DNS server
server backend.example.com:8080 resolve;
}
Check your version with nginx -v first: Ubuntu 26.04 ships NGINX 1.28, which supports this, while Ubuntu 24.04's packaged 1.24 does not.
Cause 5: PHP-FPM specific — socket permissions and pool config
When NGINX is fronting PHP-FPM, the 502 patterns get specific. The examples below use php8.3, the default on Ubuntu 24.04. On Ubuntu 26.04 the packaged default is PHP 8.5, so substitute php8.5 in socket paths, service names and log files. The error log line is one of these:
connect() to unix:/var/run/php/php8.3-fpm.sock failed (13: Permission denied)
connect() to unix:/var/run/php/php8.3-fpm.sock failed (2: No such file or directory)
recv() failed (104: Connection reset by peer) while reading response header from upstream
Permission denied means NGINX (running as www-data on Debian/Ubuntu, nginx on RHEL/AlmaLinux) can't read the FPM socket. Check the socket's permissions:
ls -la /var/run/php/php8.3-fpm.sock
The user/group on the socket should match the user NGINX runs as. The fix is in the FPM pool config (/etc/php/8.3/fpm/pool.d/www.conf or equivalent):
listen.owner = www-data
listen.group = www-data
listen.mode = 0660
Reload PHP-FPM (sudo systemctl reload php8.3-fpm) after changing.
No such file or directory means FPM isn't running, or it's using a different socket path than what NGINX expects. Check FPM status and confirm the socket path matches:
sudo systemctl status php8.3-fpm
sudo find /var/run /run -name "php*-fpm.sock" 2>/dev/null
Connection reset by peer usually means an FPM worker died mid-request — most often from a PHP fatal error, a memory limit being hit, or pm.max_children being exhausted. Check the FPM error log:
sudo tail -n 100 /var/log/php8.3-fpm.log
If pm.max_children is exhausted (server reached pm.max_children setting), raise it in the pool config — but understand why traffic exceeded the previous limit before adding capacity blindly.
Cause 6: SELinux or AppArmor blocking the upstream connection
On AlmaLinux, Rocky, and RHEL, SELinux is enforcing by default. (Amazon Linux 2023 enables SELinux in permissive mode by default, so denials are logged but not enforced unless you've switched it to enforcing — check with getenforce.) A 502 with this exact signature usually means SELinux is the culprit:
connect() failed (13: Permission denied) while connecting to upstream
NGINX-to-upstream connections are governed by the httpd_can_network_connect boolean. By default, NGINX (which runs under the httpd_t context on RHEL-family systems) can only connect to a specific allowlist of ports — port 3000 for a Node.js backend is not on that list.
Confirm SELinux is the cause:
sudo ausearch -m AVC -ts recent | tail -20 # recent AVC denials
A line like denied { name_connect } for pid=1812 comm="nginx" dest=3000 confirms it. The fix:
sudo setsebool -P httpd_can_network_connect 1
-P makes the change persistent across reboots. There's no NGINX reload needed — the boolean takes effect immediately.
On Ubuntu, AppArmor is the equivalent system, but the packaged nginx doesn't ship an AppArmor profile, so it only matters if you or your hosting provider added one. If you did, denials show up in:
sudo dmesg | grep -i denied
sudo aa-status # which AppArmor profiles are loaded
The Linux distros for deployment guide covers which distros ship SELinux enforcing by default — this is one of the cases where the distro choice has real operational consequences.
Cause 7: TLS handshake failures to an HTTPS upstream
When NGINX proxies to an upstream over https://, it makes its own TLS connection to that backend. If the handshake fails, the client gets a 502. The error log line:
SSL_do_handshake() failed (SSL: error:...) while SSL handshaking to upstream
A frequent cause is missing SNI. NGINX does not send the server name to HTTPS upstreams by default (proxy_ssl_server_name defaults to off), so any backend that hosts several sites on one IP — a CDN, a load balancer, a shared host, most managed platforms — can't pick a certificate and rejects the handshake. Turn SNI on:
location / {
proxy_pass https://upstream.example.com;
proxy_ssl_server_name on; # send SNI to the upstream
proxy_ssl_name upstream.example.com; # only needed if it differs from the proxy_pass host
}
The other usual cause is a protocol or cipher mismatch, for example an old backend that only speaks TLS 1.0/1.1, because proxy_ssl_protocols defaults to TLSv1.2 TLSv1.3. Set proxy_ssl_protocols to match what the backend supports, or better, upgrade the backend.
Certificate verification is a separate setting. proxy_ssl_verify is off by default, so an expired or self-signed upstream certificate does not cause a 502 out of the box. It only matters once you turn verification on (proxy_ssl_verify on plus proxy_ssl_trusted_certificate), which you should do for any upstream reached over an untrusted network. Both defaults are documented in the ngx_http_proxy_module reference.
Diagnostic checklist
When a 502 appears in production, run through this in order:
- Read the error log.
sudo tail -n 100 /var/log/nginx/error.log. Theupstream:URL and the bracketed error code (111,104,13,SSL_do_handshake) tell you which cause above applies. A110: Connection timed outline means you're looking at a 504, not a 502 (see Cause 2). - Confirm the upstream is running.
sudo ss -tlnp | grep :PORT. If nothing is listening, the upstream is down (Cause 1). - Check the upstream's logs.
sudo journalctl -u myapp -n 200ordocker logs myapp --tail 200. The real cause of the crash is usually here. - Test the upstream directly from the NGINX host.
curl -v http://127.0.0.1:3000/health. If this works, the problem is between NGINX and the upstream (config, SELinux, buffers). If it fails, the problem is the upstream itself. - Test the NGINX config.
sudo nginx -t. Reload withsudo systemctl reload nginxif you've changed anything. - Check system resources.
df -h,free -h,dmesg | tail -50. A 502 right after a deploy can be OOMKiller, full disk, or open-file-descriptor limits — these tools are covered above and in the Related guides.
If your 502s only show up for a few seconds during each release, the backend is being restarted while NGINX is still sending it traffic. That's a deploy-process problem, not an NGINX one, and zero downtime deployments (preparing the new release alongside the old one and switching over when it's ready) are the structural fix.
If you've done all six and still have 502s, the problem is almost always in the application — not NGINX itself.
Related guides
- NGINX cheatsheet — quick reference for the config-test, reload and log commands used throughout this post.
- Nginx vs Apache vs Caddy — comparison of the three popular reverse-proxy options, with deploy-side tradeoffs.
- Deploying .NET applications with DeployHQ on DigitalOcean — a worked example of an NGINX reverse-proxy setup in production.
- Run DeepSeek on a VPS with Ollama — another reverse-proxy example, this time fronting an LLM backend (where
proxy_read_timeoutmatters a lot). - Deploy OpenClaw on a VPS — Ubuntu + Nginx reverse proxy + systemd setup walkthrough.
For the deploy itself, DeployHQ's build pipelines can include a post-deploy nginx -t && systemctl reload nginx step so config drift is caught at release time, not at first 502 in production. Start a free trial to wire NGINX reloads into a Git-driven deploy workflow.
Need help? Email support@deployhq.com or follow @deployhq on X.