SYSTEMS ACTIVE // Avg Triage: 14m
| By NexivaGen
DevOps & Infrastructure 6 min read 1,435 reads Oct 15, 2026

How to Diagnose and Resolve 502 Bad Gateway Errors in Production Nginx & PHP-FPM

A step-by-step triage guide for senior web engineers facing sudden 502 Bad Gateway outages, upstream socket starvation, and PHP-FPM pool exhaustion.

Nexiva Core Systems Team
Nexiva Senior Engineering Unit

Understanding the 502 Bad Gateway Architecture

In high-throughput web applications, a 502 Bad Gateway error indicates that your edge reverse proxy (such as Nginx, Cloudflare, or Traefik) received an invalid response or no response from the upstream application server (such as PHP-FPM, Gunicorn, or Node.js runtime).

Primary Culprits in Production

  • PHP-FPM Worker Starvation: The pm.max_children threshold was exceeded due to slow queries or synchronous external HTTP calls.
  • Upstream Socket Timeout: The fastcgi_read_timeout in Nginx terminated the connection before the worker completed execution.
  • Memory Exhaustion (OOM Killer): The Linux kernel terminated PHP-FPM master or child processes because the machine ran out of physical memory.

Step 1: Inspect Upstream Error Logs

tail -n 100 /var/log/nginx/error.log
# Look for: "connect() to unix:/var/run/php/php8.1-fpm.sock failed (111: Connection refused)"

Step 2: Tune PHP-FPM Process Pool

Review your pool configuration at /etc/php/8.1/fpm/pool.d/www.conf:

pm = dynamic
pm.max_children = 50
pm.start_servers = 10
pm.min_spare_servers = 5
pm.max_spare_servers = 20
pm.max_requests = 500

Step 3: Enable KeepAlive and Buffer Sizing

Prevent packet fragmentation and buffer overflow by tuning your FastCGI buffers in Nginx configuration:

fastcgi_buffers 16 16k;
fastcgi_buffer_size 32k;
fastcgi_read_timeout 120s;

Conclusion

By implementing proactive telemetry, configuring PM pool ceilings relative to real RAM limits, and catching runaway database locks, you eliminate unannounced 502 outages permanently.

Filed Under Topics

Need Expert Triage for Your Own Web Infrastructure?

From fixing critical database deadlocks to resolving slow response times, our on-call senior engineers are ready to dispatch.