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:

  1. 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.
  2. 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.
  3. The worker. A worker accepted the request and then died (segfault, OOM kill, or request_terminate_timeout firing) 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

CauseWhat it looks likeFirst thing to check
FPM master is downPing endpoint fails, no php-fpm: master process in pssystemctl status php-fpm and journalctl -u php-fpm -n 50
Listen backlog overflowPing 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 pathnginx 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 ownershipnginx logs connect() to unix:... failed (13: Permission denied)ls -l /run/php/*.sock against the nginx worker user
SELinux or AppArmor denialSame “Permission denied” log, file mode looks correct, audit log shows AVCgetenforce and ausearch -m avc -ts recent
Worker crash mid-requestnginx logs upstream prematurely closed connection; FPM error log shows child N exited on signal 11FPM error log and dmesg -T | grep -i php
Graceful reload in progressBrief spike of 502s lasting seconds during deployWhether 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?"]
  1. 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 header means a worker died mid-response.
  2. 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.
  3. Read the FPM status page. Compare listen queue against listen queue len. A queue at or near its configured length combined with active processes equal to pm.max_children confirms worker exhaustion pushing into backlog overflow.
  4. Check kernel drop counters. FPM cannot see connections that the kernel refused before they reached the accept path. TcpExtListenOverflows and TcpExtListenDrops in /proc/net/netstat increment 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.
  5. 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.
  6. 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 with dmesg for OOM kills, which arrive as signal 9 from the kernel rather than as segfaults in the FPM log.
  7. 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

SignalWhy it mattersWarning sign
Ping endpoint success or failureTests whether the master is alive and dispatchingFailure with live traffic means FPM down or socket broken
listen queue vs listen queue lenDistance to kernel-level connection dropsQueue at the configured length means the next connection is refused
active processes vs pm.max_childrenPool utilization, the precondition for queue growthSustained at max_children means zero burst headroom
Kernel TcpExtListenOverflowsCounts drops that are invisible to FPMAny non-zero rate alongside web server 502s confirms overflow
FPM error log child N exited on signalWorker crashes produce mid-request 502sRepeated signal 11 entries indicate an extension or memory bug
systemctl status php-fpmWhether systemd considers the unit failedFailed state with no restart in progress means a master crash
nginx error.log upstream messagesThe failure mode from the connector sideDistinct 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/netstat or nstat at 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_timeout fires first, the worker is killed, the connection drops, and nginx returns 502. When nginx’s fastcgi_read_timeout fires first, you get 504. Typically you want request_terminate_timeout slightly higher than fastcgi_read_timeout so 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, and listen queue len per 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/netstat appear 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.