Seeing 502 Bad Gateway on an Nginx + PHP-FPM stack means Nginx accepted the browser’s request normally, tried to forward it to your upstream php-fpm socket or port, and received either a refused connection, a crashed child worker (SIGSEGV), or a truncated FastCGI stream.

Instead of restarting services blindly, checking one line in Nginx’s error log tells you within 10 seconds whether the root cause is a wrong socket path, an exhausted pm.max_children pool, a PHP fatal OOM crash, or a proxy buffer overflow.

Fast Diagnosis: Match Your Nginx Error Log Line to the Exact Fix

/var/log/nginx/error.log Message Root Cause Immediate Fix
connect() to unix:/run/php/php8.3-fpm.sock failed (2: No such file) Nginx points to old PHP version socket (e.g. `8.1` vs `8.3`) or `php-fpm` is stopped Match `fastcgi_pass` path to `listen =` in `www.conf` and start `php8.3-fpm`
connect() ... failed (13: Permission denied) Nginx worker user (`www-data` or `nginx`) lacks rw permission on `.sock` Set `listen.owner`, `listen.group`, and `listen.mode = 0660` in `www.conf`
recv() failed (104: Connection reset by peer) while reading response header PHP worker crashed (`SIGSEGV` / `memory_limit`), or `pm.max_children` backlog overflowed Inspect `/var/log/php8.3-fpm.log` for OOM/fatal errors & size `pm.max_children`
upstream sent too big header while reading response header Large `Set-Cookie`, JWT, or CSP response headers exceeded Nginx’s 4 KB/8 KB buffer Increase `fastcgi_buffers 16 16k;` and `fastcgi_buffer_size 32k;`

Step 1: Verify the Exact PHP-FPM Socket & User Permissions

After upgrading PHP (for example, PHP 8.2 -> PHP 8.3/8.4 on Ubuntu), `apt` creates a new socket path while your Nginx site block still references the old one. Check the live socket path and match both files:

# Confirm active PHP-FPM service and socket path
sudo systemctl status php8.3-fpm
ls -la /run/php/
; /etc/php/8.3/fpm/pool.d/www.conf
listen = /run/php/php8.3-fpm.sock
listen.owner = www-data
listen.group = www-data
listen.mode = 0660
listen.backlog = 1024

On very high-traffic single servers (> 1,500 req/s), switching from Unix domain sockets to loopback TCP (`127.0.0.1:9000`) or raising `net.core.somaxconn` avoids socket-queue drops when bursts arrive faster than FPM accepts them.

Step 2: Calculate Safe pm.max_children Without Swapping RAM

Setting `pm.max_children = 5` on an 8 GB server causes `502`/`504` queues under minor traffic spikes—while setting `pm.max_children = 200` on a 2 GB VPS invokes the Linux OOM Killer (`Killed process php-fpm`), producing immediate `502 Connection reset by peer` crashes! Measure your real average PHP worker RSS footprint first:

# Measure average RSS memory per PHP-FPM worker in MB
ps --no-headers -o "rss,cmd" -C php-fpm8.3 | awk '{ sum+=$1; n++ } END { printf "Workers: %d | Avg RSS: %.1f MB\n", n, sum/n/1024 }'

Apply this production capacity formula:

pm.max_children = floor((Total_Server_RAM_MB - OS_and_MySQL_Reserved_MB) / Avg_PHP_Worker_RSS_MB)

Example (4 GB VPS running Nginx + PHP-FPM, external DB):
  Available for PHP = 4096 - 1024 (OS/Nginx/Redis) = 3072 MB
  Avg Worker RSS    = 48 MB
  Safe max_children = floor(3072 / 48) = 64
; Balanced dynamic pool config in /etc/php/8.3/fpm/pool.d/www.conf
pm = dynamic
pm.max_children = 64
pm.start_servers = 12
pm.min_spare_servers = 8
pm.max_spare_servers = 24
pm.max_requests = 1000        ; Recycles workers cleanly to prevent extension memory leaks
request_terminate_timeout = 35s

Step 3: Fix “Upstream Sent Too Big Header” & Timeout Mismatches

Apps returning large session cookies, debug headers, or serialized OAuth JWTs frequently exceed Nginx’s default `4 KB`/`8 KB` FastCGI buffer size—triggering an instant `502` on valid `200 OK` responses! Also align `fastcgi_read_timeout` slightly *above* PHP’s `max_execution_time`:

location ~ \.php$ {
    include snippets/fastcgi-php.conf;
    fastcgi_pass unix:/run/php/php8.3-fpm.sock;

    # Prevent 502 on large JWT / Cookie / CSP headers
    fastcgi_buffer_size 32k;
    fastcgi_buffers 16 16k;
    fastcgi_busy_buffers_size 64k;

    # Keep Nginx read timeout slightly above PHP request_terminate_timeout
    fastcgi_connect_timeout 10s;
    fastcgi_send_timeout 45s;
    fastcgi_read_timeout 45s;
}

Reload safely after checking syntax: sudo nginx -t && sudo systemctl reload nginx.

Step 4: Pair With Page Caching So Bursts Never Reach PHP-FPM

The fastest PHP request is the one PHP-FPM never has to execute. Adding public `Cache-Control: public, s-maxage=3600` headers on anonymous GET articles and tools lets Nginx microcaching or your CDN absorb crawler bursts in `< 10 ms`—eliminating concurrency `502`/`500` spikes altogether. Comparing container or serverless migration costs? Estimate options in our Cloud Cost Calculator and PHP-FPM vs FrankenPHP Architecture Guide.

Frequently Asked Questions

What is the difference between Nginx 502 Bad Gateway and 504 Gateway Timeout?

502 Bad Gateway happens when PHP-FPM is unreachable, crashes mid-request, or sends an invalid/oversized FastCGI header. 504 Gateway Timeout means Nginx connected to PHP-FPM cleanly, but PHP took longer than fastcgi_read_timeout (commonly 60s) to finish—usually due to an unindexed SQL query or stalled external API call.