A 502 Bad Gateway means the upstream PHP-FPM pool never returned a valid FastCGI response. nginx, Apache, or Caddy tried to open a connection to the FPM socket and either the connection never established, was refused by the kernel, or was torn down mid-request.
The fastest triage move is to test both ends of the FastCGI connection: probe the FPM ping endpoint, then read the web server error log for the exact upstream message. Those two signals narrow the cause in seconds.
Note the distinction from 504 Gateway Timeout. A 504 means the web server connected to FPM but the worker never finished before fastcgi_read_timeout. A 502 means the connection itself failed. Worker exhaustion can produce both, but the boundary is which side gave up first. See the companion guide on PHP-FPM 504 Gateway Timeout when the symptom is slow-but-alive rather than unreachable.
One nuance worth setting up front: PHP-FPM’s SIGUSR2 graceful reload creates a brief window with no workers. Old workers drain while the master spawns new ones, and during that gap the web server sees transient 502s. Suppress 502 alerts for roughly 120 seconds after an intentional reload so deploy-time noise does not page anyone.
What this means
A 502 is the web server reporting that the upstream FastCGI peer refused the connection, disappeared mid-request, or returned an invalid response. From PHP-FPM’s perspective the failure happens in one of three places:
- The socket itself. The listen socket does not exist (FPM not started, wrong path), has the wrong ownership or mode (web server cannot open it), or is being denied by SELinux or AppArmor.
- The accept path. The socket is open and listening, but the master and workers cannot accept connections fast enough. The kernel-managed backlog fills, and new connection attempts are refused at the kernel level before FPM ever sees them.
- The worker. A worker accepted the request and then died (segfault, OOM kill, or
request_terminate_timeoutfiring) before sending a complete FastCGI response. The web server sees the socket close unexpectedly and logs “upstream prematurely closed connection”.
The first two are connection failures. The third is a request failure reported as 502 because the response was incomplete. The diagnostic flow for each is different.
Common causes
| Cause | What it looks like | First thing to check |
|---|---|---|
| FPM master is down | Ping endpoint fails, no php-fpm: master process in ps | systemctl status php-fpm and journalctl -u php-fpm -n 50 |
| Listen backlog overflow | Ping succeeds, listen queue near listen queue len, nginx logs connect() failed (11: Resource temporarily unavailable) | nstat -az | grep -iE "ListenOverflows|ListenDrops" and FPM status page |
| Wrong or missing socket path | nginx logs connect() to unix:/run/php/php8.2-fpm.sock failed (2: No such file or directory) | Compare fastcgi_pass in nginx with the socket on disk |
| Socket permissions or ownership | nginx logs connect() to unix:... failed (13: Permission denied) | ls -l /run/php/*.sock against the nginx worker user |
| SELinux or AppArmor denial | Same “Permission denied” log, file mode looks correct, audit log shows AVC | getenforce and ausearch -m avc -ts recent |
| Worker crash mid-request | nginx logs upstream prematurely closed connection; FPM error log shows child N exited on signal 11 | FPM error log and dmesg -T | grep -i php |
| Graceful reload in progress | Brief spike of 502s lasting seconds during deploy | Whether SIGUSR2 was sent recently |
Quick checks
# Is the master process alive?
pgrep -af "php-fpm: master"
# Is the socket listening? (Unix socket)
ss -xlnp | grep php
# Is the socket listening? (TCP, e.g., port 9000)
ss -tlnp | grep 9000
# Does the ping endpoint respond? (through the web server)
curl -sf -o /dev/null -w "%{http_code}\n" http://127.0.0.1/fpm-ping
# Does the ping endpoint respond directly via FastCGI?
# (requires the cgi-fcgi binary, typically in libfcgi-bin / libfcgi-dev)
SCRIPT_NAME=/ping SCRIPT_FILENAME=/ping REQUEST_METHOD=GET \
cgi-fcgi -bind -connect /run/php/php8.2-fpm.sock
# What does the FPM status page say right now?
curl -s http://127.0.0.1/fpm-status
# What is nginx actually complaining about?
tail -100 /var/log/nginx/error.log | grep -E "connect.*failed|no live upstreams|Connection refused|upstream prematurely closed"
# Has the kernel been dropping connections at the listen socket?
nstat -az | grep -iE "ListenOverflows|ListenDrops"
# Any recent OOM kills of php-fpm workers?
dmesg -T | grep -iE "out of memory|oom.*php"
How to diagnose it
flowchart TD
A["nginx returns 502"] --> B{"Ping endpoint?"}
B -->|"fails"| C["FPM down or socket broken"]
B -->|"succeeds"| D{"listen queue near len?"}
D -->|"yes"| E["Backlog overflow"]
D -->|"no"| F{"Reload in progress?"}
F -->|"yes"| G["Expected SIGUSR2 window"]
F -->|"no"| H["Check worker exits and socket path"]
C --> C1["systemctl status; journalctl"]
C --> C2["ls -l socket; check perms"]
E --> E1["Raise max_children or fix slow dependency"]
H --> H1["FPM log: child exited on signal?"]- Pull the exact upstream error from the web server log. nginx emits distinct messages for each failure mode.
connect() failed (111: Connection refused)means nothing is accepting on the socket.(2: No such file or directory)means the socket path is wrong or FPM is not running.(13: Permission denied)means the web server cannot open the socket.upstream prematurely closed connection while reading response headermeans a worker died mid-response. - Probe the FPM ping endpoint. If ping succeeds, the master is alive and dispatching, so the 502 is on the saturation side (backlog overflow) or the worker-crash side. If ping fails, the master is down, the socket is missing, or permissions are broken.
- Read the FPM status page. Compare
listen queueagainstlisten queue len. A queue at or near its configured length combined withactive processesequal topm.max_childrenconfirms worker exhaustion pushing into backlog overflow. - Check kernel drop counters. FPM cannot see connections that the kernel refused before they reached the accept path.
TcpExtListenOverflowsandTcpExtListenDropsin/proc/net/netstatincrement when this happens. A non-zero rate here while the FPM queue shows zero means drops are happening faster than your poll interval can capture. - Verify socket existence and ownership. Compare the path nginx is configured to connect to (
fastcgi_pass unix:/run/php/php8.2-fpm.sock) with what is on disk. Confirm the nginx worker user can read and write the socket. - If the failure is mid-request, look at worker exits. The FPM error log line
child N exited on signal 11 (SIGSEGV)indicates a worker segfaulted. Cross-reference withdmesgfor OOM kills, which arrive as signal 9 from the kernel rather than as segfaults in the FPM log. - Rule out an in-flight reload. If SIGUSR2 was sent recently, the master drains old workers and spawns new ones. During that window the ping may briefly fail and 502s are expected. Suppress alerts for roughly 120 seconds after an intentional reload.
Metrics and signals to monitor
| Signal | Why it matters | Warning sign |
|---|---|---|
| Ping endpoint success or failure | Tests whether the master is alive and dispatching | Failure with live traffic means FPM down or socket broken |
listen queue vs listen queue len | Distance to kernel-level connection drops | Queue at the configured length means the next connection is refused |
active processes vs pm.max_children | Pool utilization, the precondition for queue growth | Sustained at max_children means zero burst headroom |
Kernel TcpExtListenOverflows | Counts drops that are invisible to FPM | Any non-zero rate alongside web server 502s confirms overflow |
FPM error log child N exited on signal | Worker crashes produce mid-request 502s | Repeated signal 11 entries indicate an extension or memory bug |
systemctl status php-fpm | Whether systemd considers the unit failed | Failed state with no restart in progress means a master crash |
nginx error.log upstream messages | The failure mode from the connector side | Distinct log strings map to distinct root causes |
Fixes
FPM master is down or failing to start
Start with journalctl -u php-fpm -n 50 for the startup error. Common causes are config syntax errors, missing extensions, or a socket path that cannot be created. php-fpm -tt tests the config without starting the daemon.
If the master was OOM-killed, dmesg shows the kill event. The long-term fix is reducing pm.max_children, adding memory, or setting pm.max_requests to a finite value so per-worker memory cannot grow without bound.
systemctl restart php-fpm brings the service back. This is disruptive: all in-flight requests are killed. Verify the start actually succeeds afterward. A restart that fails to come up needs the underlying config or extension problem fixed first.
Listen backlog overflow
The fix is more workers or faster requests, not a bigger backlog. Increasing listen.backlog alone just makes the queue longer; connections still get refused when it fills.
If memory allows, raise pm.max_children and reload. Before doing this, confirm avg_worker_RSS x new_max_children + OS_overhead fits in available RAM. Blindly raising the ceiling is the classic path into the OOM death spiral.
If the cause is a slow dependency, address the dependency. Set request_slowlog_timeout so the slow log names the call that is blocking workers. Adding workers without fixing the slowness just creates more stuck workers.
Verify the kernel somaxconn is at least as high as your intended listen.backlog. Linux silently clamps the backlog to net.core.somaxconn, so your effective backlog is min(listen.backlog, somaxconn). Set an explicit value rather than relying on the default if the queue length matters to your capacity model.
Wrong socket path
Compare the fastcgi_pass directive in nginx with the actual socket path. Distro conventions differ: Debian and Ubuntu use /run/php/phpX.Y-fpm.sock; RHEL-family tends to use /run/php-fpm/www.sock. After a PHP upgrade the versioned path changes, and a site still pointing at the old /run/php/php8.1-fpm.sock will 502 the moment the package upgrades.
In container images derived from docker-library/php, the entrypoint can override the listen directive in the pool config. Verify the live value with php-fpm -tt rather than trusting the file on disk.
Socket permissions or ownership
Default `listen.mode` in most distro-supplied configs is 0660, with `listen.owner` and `listen.group` defaulting to the running user. The nginx worker user needs read and write permission on the socket file.Set listen.owner, listen.group, and listen.mode explicitly in the pool config so the values survive restarts and package upgrades. After a unit file change or distro upgrade, ownership can drift. Re-check with ls -l /run/php/*.sock.
SELinux or AppArmor
The nginx error looks identical to a permission problem because the kernel returns EACCES either way: file mode looks correct, but the web server still cannot open the socket.
On SELinux systems, check the audit log with ausearch -m avc -ts recent. The boolean httpd_can_network_connect covers TCP FastCGI connections (e.g., port 9000). For Unix socket access, the relevant factor is the socket file’s SELinux context and the directory it lives in, not a network boolean. Confirm against your distribution’s documentation before changing policy. Enforcing mode recovers the denial only after the fix is applied and nginx re-attempts the connection.
Worker crashes mid-request
A 502 from nginx with upstream prematurely closed connection while reading response header points here. The FPM error log will show child N exited on signal 11 (SIGSEGV) or signal 7 (SIGBUS). Signal 9 means an OOM kill and comes from the kernel, not from PHP. See the companion guide on PHP-FPM worker segfaults for the deeper diagnosis path.
Expected reload window
During SIGUSR2, the master drains old workers before spawning new ones. There is no overlap window like nginx has, so brief 502s during this gap are expected. Suppress alerts for roughly 120 seconds after intentional reloads. See the companion guide on the graceful reload window for the mechanics.
Prevention
- Monitor both sides of the connection. FPM’s status page shows internal state. The web server error log and kernel counters show what happens at the socket boundary. A backlog overflow is invisible to FPM by design.
- Set
pm.max_requests. A finite value (500 to 1000) prevents unbounded per-worker memory growth that eventually attracts the OOM killer. The default in many distros is 0. - Set
request_slowlog_timeout. Without it, you see that workers are busy but not why. A 5-second threshold catches the calls that drain the pool. - Watch kernel
ListenOverflows. This is the only signal that catches drops the FPM status page cannot see. Poll/proc/net/netstatornstatat a short interval. - Pin the socket path. Distro upgrades change versioned paths. Either pin the listen directive explicitly or run integration checks after package upgrades.
- Suppress alerts around intentional reloads. The SIGUSR2 gap is real. A 120-second silence window after a documented deploy prevents noise.
- Keep nginx and FPM timeouts coherent. When FPM’s
request_terminate_timeoutfires first, the worker is killed, the connection drops, and nginx returns 502. When nginx’sfastcgi_read_timeoutfires first, you get 504. Typically you wantrequest_terminate_timeoutslightly higher thanfastcgi_read_timeoutso timeouts surface as 504 on the web server side rather than as a worker kill.
How Netdata helps
- The PHP-FPM collector pulls
active processes,idle processes,listen queue, andlisten queue lenper second, so the saturation curve that precedes a backlog overflow is visible before the web server starts returning 502. - Correlating the FPM ping probe with the web server 5xx rate separates “FPM down” from “FPM overloaded” in one view, which is the first branch of the triage.
- Per-process CPU and memory charts catch the OOM-kill path early: rising worker RSS combined with cgroup memory pressure predicts the master crash before it happens.
- Kernel socket counters from
/proc/net/netstatappear alongside the FPM status fields, so drops invisible to FPM show up next to the queue depth that predicts them. - For containerized FPM, cgroup-level memory metrics are collected independently of the host, so the limit that actually triggers the OOM kill is the one being watched.
Related guides
- PHP-FPM 504 Gateway Timeout: requests accepted but never finishing in time
- PHP-FPM active processes near max_children: reading pool utilization
- PHP-FPM in containers: cgroup limits and the silent OOM kill
- PHP-FPM “child N exited on signal 11 (SIGSEGV)”: worker segfaults
- PHP-FPM crash loop and fork storm: workers dying faster than they serve
- PHP-FPM dynamic mode scaling lag: why the pool cannot keep up with bursts
- PHP-FPM emergency restart: “failed processes threshold reached, initiating reload”
- PHP-FPM graceful reload: the brief no-worker window on SIGUSR2
- How PHP-FPM actually works in production: a mental model for operators
- PHP-FPM idle processes at zero: no burst headroom left
- PHP-FPM listen queue growing: the earliest signal of saturation
- PHP-FPM “server reached pm.max_children setting (N), consider raising it”






