How to Fix HTTP 502 Bad Gateway and 504 Gateway Timeout Errors
A comprehensive, command-by-command troubleshooting guide for sysadmins, DevOps engineers, and webmasters dealing with unresponsive upstream servers and reverse proxy timeouts.
Few things disrupt an online business faster than an abrupt HTTP 502 Bad Gateway or HTTP 504 Gateway Timeout. Because these errors occur at the boundary between edge proxies (such as Cloudflare, AWS ALB, Nginx, or HAProxy) and backend application runtimes (such as PHP-FPM, Node.js, Python Gunicorn, or Go binaries), pinpointing the root cause requires methodical isolation.
01 Understanding the Difference: 502 vs 504
Although both status codes belong to the HTTP 5xx Server Error family, their technical triggers are fundamentally distinct:
HTTP 502 Bad Gateway
The edge proxy reached out to the backend server, but the backend returned an invalid, corrupt, or truncated response, or abruptly terminated the TCP connection (connection refused or TCP RST).
HTTP 504 Gateway Timeout
The edge proxy connected to the origin server, but the origin server took too long to respond, exceeding the proxy's configured read timeout threshold (e.g., 60 or 120 seconds).
02 The 5 Most Frequent Causes in Production
1. Upstream Application Process Crashed (OOM Killer)
When a server runs out of RAM during high traffic or memory-leaking scripts, the Linux Out-Of-Memory (OOM) killer will instantly terminate the heaviest process—usually PHP-FPM, Node.js, or MariaDB/MySQL. When Nginx tries to pass a request via Unix socket or TCP port 9000, it receives a Connection refused error, yielding a 502.
2. PHP-FPM Pool Worker Exhaustion
In WordPress and PHP environments, if your pm.max_children setting is too low (e.g. 10 workers) and 50 visitors submit concurrent requests, incoming requests queue up until the timeout limit is hit, resulting in 504 Gateway Timeouts for all subsequent visitors.
3. Unoptimized Database Queries & Long Transactions
A single unindexed SQL query joining multiple large tables can lock rows for 60+ seconds. Web servers like Apache and Nginx default to a 60-second gateway timeout, returning a 504 to the user while the database continues churning in the background.
4. Firewall Blocking Edge Proxy IP Ranges
If you use Cloudflare or a reverse proxy CDN, all traffic appears to originate from Cloudflare's IP ranges. If an aggressive server-level firewall (UFW, iptables, Fail2ban) rate-limits those IPs, the proxy is blocked from contacting the origin, throwing a 502 Cloudflare Error screen.
5. DNS Record Pointing to a Stale Server IP
During server migrations, if your domain's A or AAAA record still points to an old, decommissioned droplet or VM, the proxy cannot establish an upstream handshake. Use the CheckHostNow DNS Lookup tool to verify global propagation.
03 Step-by-Step Diagnostic Commands (Linux CLI)
Connect to your server via SSH and execute the following commands in sequence to isolate the failure point:
# For PHP-FPM environments:
sudo systemctl status php8.3-fpm || sudo systemctl status php8.2-fpm
# For Node.js / PM2 apps:
pm2 status
pm2 logs --lines 50
# For Python / Gunicorn:
sudo systemctl status gunicorn
# Follow live Nginx error logs:
sudo tail -n 50 -f /var/log/nginx/error.log
# Common patterns to look for:
# "connect() to unix:/var/run/php/php8.2-fpm.sock failed (111: Connection refused)"
# "upstream timed out (110: Connection timed out) while reading response header from upstream"
sudo dmesg -T | grep -i -E "oom|killed process"
04 How to Fix the Configurations
Nginx Proxy Timeout Increase (for Heavy Queries):
If legitimate backend batch jobs take longer than 60 seconds, increase proxy timeouts inside your /etc/nginx/sites-available/your-site.conf:
location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/var/run/php/php8.2-fpm.sock;
fastcgi_read_timeout 300;
fastcgi_connect_timeout 300;
fastcgi_send_timeout 300;
}
Tuning PHP-FPM Pool Limits:
Open /etc/php/8.2/fpm/pool.d/www.conf and adjust your child processes to match your server's RAM:
pm = dynamic
pm.max_children = 50
pm.start_servers = 10
pm.min_spare_servers = 5
pm.max_spare_servers = 20
pm.max_requests = 500
Always restart services after modifying configs: sudo systemctl restart php8.2-fpm && sudo systemctl reload nginx.
Production Supervisor Best Practices
Automated process supervisors (such as systemd or PM2) and container orchestrators automatically restart failed upstream workers when memory limits are exceeded, preventing cascade 502 Bad Gateway failures.