Skip to content

Fix nginx 502 Bad Gateway: diagnosing the upstream

A troubleshooting guide for the nginx 502 bad gateway error from a proxied upstream — read the error log, confirm the backend is listening, and fix connect failures, timeouts, buffers, and SELinux.

A 502 Bad Gateway from nginx means nginx acted as a proxy, reached out to your upstream — an app server, PHP-FPM, or another proxied service — and got back nothing it could use as an HTTP response. The status has almost nothing to do with nginx itself and almost everything to do with the backend behind it. The good news: nginx writes the real cause into its error log every single time. connect() failed, upstream prematurely closed connection, no live upstreams, Permission denied, upstream sent too big header — each phrase points at a different fix. This guide reads that log line, confirms the backend with a direct request, and walks the fixes for each cause.

What you’ll accomplish

  • Read the nginx error log and translate its 502 phrase into a root cause.
  • Confirm whether the backend is actually listening, over TCP or a Unix socket.
  • Fix the four common causes: a dead backend, timeouts, oversized headers, and SELinux blocking the connection.
  • Tell a 502 (bad/empty response) apart from a 504 (backend too slow) so you fix the right thing.

Prerequisites

  • An nginx server that proxies to an upstream via proxy_pass or fastcgi_pass.
  • Shell access to the nginx host with permission to read /var/log/nginx/error.log.
  • The ability to restart the backend (systemd unit, container, or process manager) and to reload nginx.

How it works

When you use proxy_pass http://127.0.0.1:3000 or fastcgi_pass unix:/run/php/php8.3-fpm.sock, nginx opens a fresh connection to that address for the request, forwards it, and waits for a response header. Three things can go wrong on that leg, and each maps to a 502: nginx cannot open the connection at all, the connection opens but the backend closes it before sending a complete header, or the backend sends a header nginx refuses to accept. A slow-but-alive backend is a different failure — that is a 504, covered at the end.

Request path from client to nginx to the app server, with the error.log phrase for each 502 failure point and its root cause

The single most useful habit: never guess. Tail the error log, read the phrase, and let it route you to the fix.

Step-by-step

  1. Tail the error log and read the phrase. Every 502 leaves a line naming the upstream address and the reason.

    sudo tail -n 20 /var/log/nginx/error.log

    A dead backend looks like this:

    2026/07/14 09:12:41 [error] 812#812: *4 connect() failed (111: Connection refused) while connecting to upstream, client: 203.0.113.7, server: app.example.com, request: "GET / HTTP/1.1", upstream: "http://127.0.0.1:3000/", host: "app.example.com"

    Note the upstream: field — http://127.0.0.1:3000/ — that is exactly where nginx tried to connect. That address is what you verify next.

  2. Confirm the backend is listening. Check that something owns the port or socket from the upstream: line.

    ss -ltnp | grep ':3000'

    Healthy output names the process and PID:

    LISTEN 0      511    127.0.0.1:3000    0.0.0.0:*    users:(("node",pid=2210,fd=18))

    If this returns nothing, the backend is down — that alone explains Connection refused. For PHP-FPM on a Unix socket, check the socket exists and its permissions instead:

    ls -l /run/php/php8.3-fpm.sock
    srw-rw---- 1 www-data www-data 0 Jul 14 08:55 /run/php/php8.3-fpm.sock
  3. Curl the backend directly, bypassing nginx. This is the fastest way to prove whether the problem is nginx or the app. For a TCP upstream:

    curl -sS -o /dev/null -w '%{http_code}\n' http://127.0.0.1:3000/

    A working backend prints 200. A dead one prints the same error nginx sees:

    curl: (7) Failed to connect to 127.0.0.1 port 3000 after 0 ms: Connection refused

    For a PHP-FPM socket, HTTP curl does not apply — speak FastCGI to it with cgi-fcgi:

    SCRIPT_NAME=/ping SCRIPT_FILENAME=/ping REQUEST_METHOD=GET \
      cgi-fcgi -bind -connect /run/php/php8.3-fpm.sock

    With pm.status_path / ping.path enabled in the pool, a live FPM replies pong.

  4. If the backend is down, start it and read its own logs. A backend that will not stay up is the real bug; nginx is only the messenger.

    sudo systemctl restart php8.3-fpm
    sudo systemctl status php8.3-fpm --no-pager
    ● php8.3-fpm.service - The PHP 8.3 FastCGI Process Manager
         Active: active (running) since Tue 2026-07-14 09:15:02 UTC

    If it crashes again within seconds, journalctl -u php8.3-fpm -n 50 (or your app’s log) has the stack trace. Fix that before touching nginx.

  5. Match proxy_pass to how the backend actually listens. A socket-versus-TCP mismatch produces Connection refused even when the backend is healthy. If FPM listens on a socket, nginx must use fastcgi_pass unix:/run/php/php8.3-fpm.sock;; if it listens on 127.0.0.1:9000, nginx must use fastcgi_pass 127.0.0.1:9000;. Confirm the FPM side:

    grep -E '^listen' /etc/php/8.3/fpm/pool.d/www.conf
    listen = /run/php/php8.3-fpm.sock

    Whatever this prints must be byte-for-byte what nginx passes to.

  6. Set sane timeouts for a slow header. If the log says upstream prematurely closed connection while reading response header, the backend accepted the request but died or was cut off before finishing the header. Raise the read window so a merely-slow response is not severed:

    location / {
        proxy_pass http://127.0.0.1:3000;
        proxy_connect_timeout 5s;
        proxy_read_timeout 60s;
        proxy_send_timeout 60s;
    }

    proxy_connect_timeout caps how long nginx waits to open the socket; proxy_read_timeout caps the gap between successful reads once connected. Note that raising these turns a 502 into a 504 if the backend is simply slow — the point is to stop severing responses that would have completed.

  7. Give nginx room for large upstream headers. upstream sent too big header while reading response header from upstream means the backend’s response header (often a fat Set-Cookie or a long auth token) overflowed nginx’s buffer. Enlarge it:

    http {
        proxy_buffer_size          16k;
        proxy_buffers              8 16k;
        proxy_busy_buffers_size    32k;
        large_client_header_buffers 4 16k;
    }

    proxy_buffer_size holds the first chunk (the response header). large_client_header_buffers covers the request side when the client sends big cookies of its own.

  8. Test and reload — never restart blindly. Validate the config before applying it so a typo does not take the site fully offline.

    sudo nginx -t && sudo systemctl reload nginx
    nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
    nginx: configuration file /etc/nginx/nginx.conf test is successful

Validate it works

Make a real end-to-end request through nginx and confirm both the status and a clean log. The time_total also tells you the backend is responding promptly, not just eventually.

curl -sS -o /dev/null -w '%{http_code} %{time_total}s\n' https://app.example.com/
200 0.184s

Then confirm no new 502 lines are being written:

sudo tail -n 5 /var/log/nginx/error.log

A quiet tail with a 200 from curl means the upstream leg is healthy. If you run a pool of backends, this is also the moment to confirm your passive checks are tuned — our companion guide on nginx upstream health checks covers max_fails and fail_timeout so one flaky node does not eject the whole pool.

Troubleshooting

Use the decision tree below to jump from the exact phrase in your log to its fix.

Decision tree mapping each nginx 502 error.log phrase to the command that fixes it

  • connect() failed (111: Connection refused) — Nothing is listening at the upstream: address. Either the backend is down (start it, then re-check with ss -ltnp) or proxy_pass points at the wrong port/socket. This is the most common 502 and almost always a backend problem, not an nginx one.
  • upstream prematurely closed connection while reading response header — The backend accepted the connection but died mid-request or was killed by its own timeout. Read the app or FPM log for a crash, a fatal PHP error, or an OOM kill (dmesg | grep -i oom). If the process is fine but slow, raise proxy_read_timeout as in step 6. For PHP-FPM specifically, a pm.max_children ceiling that is too low also shows here — the pool runs out of workers and drops connections.
  • no live upstreams while connecting to upstream — Every server in the upstream block is currently marked down by passive checks. One backend flapping can cascade if max_fails is too aggressive. Fix the backends first, then review the block’s max_fails / fail_timeout; keepalive settings matter here too, covered in tuning the nginx keepalive upstream pool.
  • (13: Permission denied) while connecting to upstream — On RHEL/Rocky/AlmaLinux with SELinux enforcing, nginx is blocked from opening the connection. Confirm the denial, then allow it:
    sudo ausearch -m avc -ts recent | grep nginx
    sudo setsebool -P httpd_can_network_connect 1
    For a Unix socket, also confirm the socket’s group/owner lets the nginx user (www-data or nginx) read and write it — that was step 2.
  • upstream sent too big header — The header overflowed the proxy buffer. Apply the buffer sizes from step 7 and reload. This one is easy to misread as a random intermittent 502 because it only fires when the header happens to be large.

When this is the wrong approach

A 502 is not a 504. If the log says upstream timed out (110: Connection timed out) while reading response header, nginx connected fine and the backend is simply too slow — that returns 504, and raising proxy_read_timeout is the correct move, not the fixes above. Likewise, if curl straight to the backend already returns a 500 or a broken response, nginx is faithfully reporting a bug in your application; the fix lives in the app’s code or database, and no amount of nginx tuning will help. Nginx buffers, timeouts, and SELinux booleans only address the transport between nginx and a backend that is itself healthy — when the backend is the problem, fix the backend.

For the full contract of proxy_pass, buffering, and timeout directives, the nginx proxy module documentation is the authoritative reference; PHP-FPM setups also lean on the fastcgi module docs.

If this is the kind of work you’d rather never own again, it’s the daily job of Managed Cloud Ops — book an infrastructure review.