An nginx 502 Bad Gateway means nginx accepted the client's request but got no usable response from the upstream it proxies to: the backend refused the connection, closed it mid-response, sent headers nginx could not parse, or nginx was not allowed to connect at all. The fastest fix is to stop guessing and read the matching line in the nginx error log, because each cause leaves a distinct message. This guide maps every common message to its fix, then covers timeouts, buffers, Docker networking and how to prove the fix worked.

Everything below was checked against the nginx.org documentation as of December 2026, when the download page lists mainline 1.31.10 and stable 1.30.8. One change matters more than any other if you upgraded this year, and it gets its own section further down: since 1.29.7, nginx keeps upstream connections alive by default.

Step One: Find the Error Log Line Behind the Nginx 502 Bad Gateway

The 502 page your browser shows is generic on purpose. The reason lives in the error log, written at the error level for every failed upstream attempt. Find the log path first, then filter for upstream messages:

# Where does this nginx write its error log?
sudo nginx -T 2>/dev/null | grep -E '^\s*error_log'

# Default package locations
sudo tail -n 50 /var/log/nginx/error.log

# Only the upstream-related lines, newest last
sudo grep -E 'upstream|connect\(\)|no live' /var/log/nginx/error.log | tail -n 20

# Official Docker image: logs go to stderr
docker logs --tail 50 my-nginx 2>&1 | grep -i upstream

A typical line looks like this, and every part of it is useful:

2026/12/02 09:14:07 [error] 2817#2817: *4410 connect() failed (111: Connection refused) while connecting to upstream, client: 203.0.113.9, server: app.example.com, request: "GET /api/orders HTTP/2.0", upstream: "http://127.0.0.1:3000/api/orders", host: "app.example.com"

The upstream: field tells you exactly which address nginx tried. Half of all 502 investigations end right there, when that address is not the one you thought (a stale IP, the wrong port, localhost inside a container).

If the log shows nothing, check that the request reaches this nginx at all (a CDN or load balancer in front can return its own 502), and that error_log is not set to crit or higher somewhere in an included file.

502 versus 504 versus 503

Before chasing a cause, confirm the status code. nginx returns 504 Gateway Timeout when the upstream accepted the connection but did not answer within proxy_read_timeout, logged as upstream timed out (110: Connection timed out) while reading response header from upstream. A 503 usually comes from your own limit_req/limit_conn rules or from the application. A 502 is about the connection or the response being broken, not slow. Mixing these up leads people to raise timeouts for a problem that timeouts cannot fix.

Error Message to Fix: The Lookup Table

Error log fragment What it means First thing to check
connect() failed (111: Connection refused) Nothing is listening on that IP:port Is the app running, on that port, on that interface?
connect() to unix:... failed (2: No such file or directory) The socket path does not exist PHP-FPM/Gunicorn socket path and service status
connect() to unix:... failed (13: Permission denied) nginx's user cannot open the socket Socket owner/mode, or SELinux
connect() to 127.0.0.1:8080 failed (13: Permission denied) on a TCP address SELinux is blocking the outbound connect httpd_can_network_connect boolean
upstream prematurely closed connection while reading response header Backend accepted, then closed without a full response App crash, worker killed, keepalive race
recv() failed (104: Connection reset by peer) Backend reset the connection Same as above, plus TLS/protocol mismatch
upstream sent too big header while reading response header from upstream Response headers exceed the header buffer proxy_buffer_size / fastcgi_buffer_size
no live upstreams while connecting to upstream Every server in the group is marked failed Earlier errors that triggered max_fails
SSL_do_handshake() failed TLS to the backend failed SNI (proxy_ssl_server_name), protocol, certs
upstream sent invalid header Backend spoke something other than valid HTTP Wrong port (e.g. HTTP to an HTTPS or gRPC port)

The sections below take these one at a time.

Connection Refused (111): Nothing Listening on the Upstream

111: Connection refused is the kernel telling nginx that no process is accepting connections on that address. nginx is working correctly; the backend is not where nginx expects it. Check from the nginx host itself, using the exact address from the log line:

# Is anything listening on port 3000, and on which interface?
sudo ss -ltnp | grep ':3000'

# Talk to the upstream directly, bypassing nginx
curl -sv http://127.0.0.1:3000/health -o /dev/null

# Is the service up?
systemctl status myapp --no-pager
journalctl -u myapp -n 50 --no-pager

Three causes cover nearly every case:

  1. The app is down or crash-looping. The journal or container logs show why. If it restarts every few seconds you will see 502s interleaved with successes. On Kubernetes this looks like the pattern in our CrashLoopBackOff guide.
  2. Port mismatch. The app moved from 3000 to 8080 in a config change and proxy_pass still says 3000.
  3. Wrong interface. ss shows the app on 127.0.0.1:3000 but nginx connects to the host's private IP, or the app listens on IPv6 [::1] only while proxy_pass http://localhost:3000 resolves to 127.0.0.1 first. Use an explicit IP in proxy_pass and make the app bind to the same one.

PHP-FPM Socket Errors: Missing Socket and Permission Denied

PHP sites usually talk to PHP-FPM over a Unix socket, which adds two failure modes.

(2: No such file or directory) means the path in fastcgi_pass does not exist. The socket name includes the PHP version on Debian and Ubuntu packages, so an upgrade that installs a new php8.x-fpm service quietly breaks a hard-coded path. Compare the two:

grep -R "fastcgi_pass" /etc/nginx/
grep -R "^listen" /etc/php/*/fpm/pool.d/ 2>/dev/null || grep -R "^listen" /etc/php-fpm.d/
ls -l /run/php/ /run/php-fpm/ 2>/dev/null

(13: Permission denied) on a unix: path means the socket exists but the nginx worker user cannot read and write it. The PHP-FPM configuration reference is explicit: on Linux the web server needs read/write permission on the socket, and by default the socket is owned by the user running FPM with mode 0660. If FPM runs as www-data and nginx runs as nginx, nginx is locked out. Fix it in the pool file rather than with a one-off chmod, because the socket is recreated on every restart:

; /etc/php/8.4/fpm/pool.d/www.conf (path varies by distro and version)
listen = /run/php/php8.4-fpm.sock
listen.owner = www-data
listen.group = nginx
listen.mode = 0660
; Alternative where POSIX ACLs are supported; owner/group are then ignored
; listen.acl_users = nginx

Then restart FPM and confirm the socket's group with ls -l. If you are mid-upgrade, our PHP 8.6 upgrade guide covers the version-specific pool paths you will need to update.

When FPM is up but every request still returns 502 with upstream prematurely closed connection or recv() failed (104), look at the FPM log for server reached pm.max_children setting or children exiting on a signal. A PHP fatal error that kills the worker, or request_terminate_timeout killing a long request, both surface to nginx as a closed connection.

SELinux Permission Denied on a TCP Upstream

On RHEL, Rocky, Alma and Fedora, a reverse proxy that works perfectly in testing can fail in production with this:

[crit] 1532#1532: *1 connect() to 127.0.0.1:8080 failed (13: Permission denied) while connecting to upstream

A TCP connect cannot hit a filesystem permission, so 13 here is SELinux denying the httpd_t domain (which nginx runs in) an outbound connection. The fix is a boolean, not disabling SELinux. F5's guide to running NGINX with SELinux gives both relevant booleans:

# Confirm it is SELinux
getenforce
sudo ausearch -m AVC -c nginx --start recent | audit2why

# Allow nginx to relay to backends (reverse proxy)
sudo setsebool -P httpd_can_network_relay 1
# Broader: allow connections to any port type
sudo setsebool -P httpd_can_network_connect 1

-P makes the change persistent across reboots. httpd_can_network_relay is the boolean aimed at proxying; httpd_can_network_connect lets the httpd_t domain connect to any port type, which is wider than most setups need. Try the narrower one first and re-test before reaching for the broad one. If the backend listens on an unusual port and the denial persists, the AVC record from audit2why names the port type involved. A Unix socket in a non-standard directory can produce the same 13 on a unix: path; in that case the socket's file context is wrong, and ls -Z will show it.

Upstream Prematurely Closed Connection

This message means the TCP connection was established and nginx sent the request, but the backend hung up before sending complete response headers. Look at the backend, not nginx:

  • The worker was killed. Gunicorn's default timeout is 30 seconds: "workers silent for more than this many seconds are killed and restarted." A request that takes 45 seconds becomes a 502 even though nginx's own proxy_read_timeout is 60 seconds. Raise the app server timeout, or better, move the slow work to a background job.
  • Out of memory. dmesg -T | grep -i oom or the container's OOMKilled status. Each kill shows up as a burst of 502s.
  • The app crashed on that specific request. Correlate the timestamp in nginx's log with the application log.
  • A keepalive race, which got more common this year. See the next section.

The Nginx 1.29.7 Keepalive Change and Intermittent 502s

According to the nginx CHANGES file, version 1.29.7 (24 March 2026) made two defaults change: the keepalive directive in upstream blocks is enabled by default, and the proxy module now speaks HTTP/1.1 to backends and no longer sends Connection: close. The upstream module docs now list the default as keepalive 32 local; with an idle keepalive_timeout of 60 seconds. Every stable branch from 1.30 onward inherits this.

That is a performance win, but it creates a classic race. nginx holds an idle connection open for up to 60 seconds; many app servers close idle connections much sooner. Gunicorn's documented keepalive default is 2 seconds, and Node.js documents its own server.keepAliveTimeout in the http module reference. If the backend closes a connection at the moment nginx reuses it, nginx logs upstream prematurely closed connection or recv() failed (104: Connection reset by peer). nginx will retry idempotent requests on another connection, but per the proxy_next_upstream docs it does not resend a POST, LOCK or PATCH that was already sent unless you add non_idempotent. The symptom: rare, random 502s, mostly on writes, after an nginx upgrade with no app change.

The rule is simple: nginx's idle timeout must be shorter than the backend's. Either shorten nginx's or lengthen the backend's:

upstream app_backend {
    server 127.0.0.1:3000;
    keepalive 32;
    keepalive_timeout 4s;   # below the backend's idle timeout
}
// Node.js: make the server's idle timeout longer than nginx's
const server = app.listen(3000, "127.0.0.1");
server.keepAliveTimeout = 65_000; // ms, longer than nginx's 60s default
server.headersTimeout = 66_000;   // keep this above keepAliveTimeout

If you cannot change either side right away, keepalive 0; inside the upstream block restores the old one-connection-per-request behaviour while you work it out.

Upstream Sent Too Big Header: Buffers

upstream sent too big header while reading response header from upstream

nginx reads the backend's response headers into a single buffer. The proxy module docs set proxy_buffer_size to one memory page by default, 4K or 8K depending on the platform, and if the headers do not fit, the response is treated as invalid and the client gets a 502. The usual culprits are large Set-Cookie headers (session data stuffed into cookies, several auth cookies from an SSO flow), long Link or CSP headers, and frameworks that echo debug data into headers.

Measure the actual header size before changing anything:

curl -s -o /dev/null -D - http://127.0.0.1:3000/login | wc -c

Then size the buffers to fit with headroom:

location / {
    proxy_pass http://app_backend;
    proxy_buffer_size       16k;   # must hold the full response header
    proxy_buffers           8 16k;
    proxy_busy_buffers_size 32k;   # must be >= proxy_buffer_size, < total proxy_buffers minus one
}

location ~ \.php$ {
    include fastcgi_params;
    fastcgi_pass unix:/run/php/php8.4-fpm.sock;
    fastcgi_buffer_size 32k;       # same problem, FastCGI variant
    fastcgi_buffers     16 16k;
}

Run sudo nginx -t after editing; nginx refuses some inconsistent combinations of busy and total buffer sizes at config test time. Note that since 1.31.3, the CHANGES file says header and trailer size from HTTP/2 backends (the newer proxy-to-HTTP/2 path) is also limited by proxy_buffer_size, so this fix applies there too. If headers are routinely above 16K, fix the application: an oversized cookie is shipped on every request a browser makes.

No Live Upstreams

no live upstreams while connecting to upstream is a consequence, not a cause. In an upstream block, each server has max_fails=1 and fail_timeout=10s by default, per the upstream docs: one failed attempt marks the server unavailable for 10 seconds. With a single server, any blip (one connection refused during a deploy) makes nginx skip the backend entirely for 10 seconds, and every request in that window gets an instant 502 with this message.

Scroll up in the log to the first error before the no live upstreams burst; that is the real problem. For single-server upstreams, consider disabling failure accounting so nginx always tries:

upstream app_backend {
    server 127.0.0.1:3000 max_fails=0;
}

With several servers, keep the defaults but tune them, and pair them with health-checked, rolling deploys so you never take every server down at once.

Timeouts: When They Matter for a 502

Timeouts produce 504s far more often than 502s, but they interact with the causes above. The defaults from the proxy module docs:

Directive Default Notes
proxy_connect_timeout 60s "cannot usually exceed 75 seconds"
proxy_send_timeout 60s Between two write operations, not the whole request
proxy_read_timeout 60s Between two reads, not the whole response
fastcgi_read_timeout 60s Same semantics for PHP-FPM

Two practical points. First, align the chain: client-side load balancer idle timeout, then nginx proxy_read_timeout, then the app server's worker timeout. If the app server kills the worker first (Gunicorn at 30 seconds, PHP-FPM's request_terminate_timeout), you get a 502, not the 504 you would expect. Second, lower proxy_connect_timeout to a few seconds when you have multiple upstreams, so a dead server fails fast and nginx moves on.

Docker Networking: Localhost Is Not Your Host

The most common 502 in containerised setups:

# Inside the nginx container, this points at the nginx container itself
proxy_pass http://localhost:3000;

Each container has its own network namespace, so localhost inside the nginx container is that container. The log shows connect() failed (111: Connection refused) ... upstream: "http://127.0.0.1:3000/". Fixes, in order of preference:

  1. Put both containers on the same user-defined network and use the service name. Docker Compose does this for you.
  2. Make the app listen on 0.0.0.0 inside its container. An app bound to 127.0.0.1 in its own container is unreachable from any other container, even with the right hostname.
  3. For a service on the host itself, use the host-gateway mapping that the docker run reference documents: --add-host=host.docker.internal:host-gateway. Docker Desktop resolves that name automatically; on Linux you need the flag (or extra_hosts in Compose).
services:
  nginx:
    image: nginx:1.30
    ports:
      - "80:80"
    volumes:
      - ./default.conf:/etc/nginx/conf.d/default.conf:ro
    depends_on:
      - app
    extra_hosts:
      - "host.docker.internal:host-gateway"   # only needed to reach the host
  app:
    build: .
    command: ["node", "server.js"]
    environment:
      HOST: 0.0.0.0
      PORT: "3000"

The second Docker trap is stale DNS. nginx resolves hostnames in proxy_pass and upstream blocks once, at startup, and keeps the IP. Recreate the app container, it gets a new IP, and nginx keeps connecting to the old one until reloaded. Either reload nginx after redeploys, or make it re-resolve through Docker's embedded DNS server, which the Docker networking docs put at 127.0.0.11 on user-defined networks:

resolver 127.0.0.11 valid=10s ipv6=off;

upstream app_backend {
    zone app_backend 64k;              # 'resolve' needs shared memory
    server app:3000 resolve;           # open source nginx 1.27.3+
}

server {
    listen 80;
    location / {
        proxy_pass http://app_backend;
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}

The resolve parameter on upstream servers was commercial-only until 1.27.3, per the upstream module docs, so every current open source release supports it. On older builds, the fallback is set $backend http://app:3000; proxy_pass $backend;, which forces a lookup through resolver at request time. If your host's disk fills up and Docker can no longer recreate containers, the 502 is a symptom of Docker's "no space left on device" problem.

HTTPS Upstreams and SSL Handshake Failures

When proxy_pass points at https://, nginx is a TLS client. Two defaults from the proxy module docs surprise people: proxy_ssl_server_name is off, so nginx sends no SNI, and proxy_ssl_verify is off. Backends behind a CDN or a shared TLS terminator often reject handshakes without SNI, logging SSL_do_handshake() failed and returning a 502.

location / {
    proxy_pass https://api.internal.example.com;
    proxy_ssl_server_name on;
    proxy_ssl_name api.internal.example.com;
    proxy_ssl_verify on;
    proxy_ssl_trusted_certificate /etc/ssl/certs/ca-certificates.crt;
}

Turning verification on is not required to fix the 502, but it is the right setting. If you are changing TLS settings anyway, our guide to post-quantum TLS on nginx with OpenSSL covers the client and server side of key-exchange negotiation.

How to Verify the Fix

Do not stop at "the page loaded once". Intermittent 502s need evidence over time. Add upstream timing to your access log:

log_format upstream_debug '$remote_addr [$time_local] "$request" $status '
                          'upstream=$upstream_addr ustatus=$upstream_status '
                          'connect=$upstream_connect_time header=$upstream_header_time '
                          'total=$upstream_response_time';
access_log /var/log/nginx/upstream.log upstream_debug;

$upstream_status shows what the backend actually returned (or 502 when nginx synthesised it), and multiple comma-separated values reveal retries to the next server. Then validate, reload and measure:

sudo nginx -t && sudo systemctl reload nginx

# 500 requests, count status codes
for i in $(seq 1 500); do
  curl -s -o /dev/null -w '%{http_code}\n' https://app.example.com/health
done | sort | uniq -c

# Any 502s in the last hour, with the upstream status attached
sudo awk '$7 == 502' /var/log/nginx/upstream.log | tail

For keepalive races, test with writes, not just GET /health: send POST requests at intervals just longer than the backend's idle timeout, which is exactly when the race window opens.

Frequently Asked Questions

Is a 502 Bad Gateway an nginx problem or a backend problem?

Almost always the backend, or the path between nginx and the backend. nginx generates the 502 because the upstream refused, reset or mangled the connection. The exceptions are nginx-side configuration: a wrong proxy_pass address, undersized header buffers, missing SNI, or a stale resolved IP.

Why do I get 502 only on some requests?

Intermittent 502s usually mean a crash-looping or memory-killed backend, workers being killed by an app-server timeout, or a keepalive race where the backend closes idle connections before nginx does. The last one became more common after nginx 1.29.7 enabled upstream keepalive by default.

Should I just increase proxy_read_timeout?

Only if the log says upstream timed out, and that is a 504, not a 502. Raising nginx timeouts does nothing for connection refused, permission denied or oversized headers, and it does not help if the app server kills the worker first.

How do I fix 502 Bad Gateway with nginx in Docker?

Replace localhost with the target service name on a shared user-defined network, make the app listen on 0.0.0.0, and make nginx re-resolve container names (resolver 127.0.0.11 plus resolve on the upstream server) or reload nginx after redeploys.

What does "no live upstreams" mean?

Every server in the upstream group has been marked unavailable after reaching max_fails within fail_timeout (1 failure in 10 seconds by default). Find the earlier error that caused the failures; for a single-server upstream, max_fails=0 stops nginx from skipping it.

Bottom Line

Treat the nginx 502 bad gateway as a symptom with a label attached. Read the upstream line in the error log, match the message to its cause (refused, socket permissions, SELinux, premature close, header size, no live upstreams, TLS), fix that specific thing, and then verify with upstream timing in the access log over a few hundred requests. If you upgraded to nginx 1.30 or a 1.29.7+ mainline this year and started seeing rare 502s on writes, check upstream keepalive timeouts before anything else.