# How to Fix 502 Bad Gateway and 504 Timeout on Nginx and Cloudflare

> Step-by-step commands to fix 502 Bad Gateway and 504 Gateway Time-out on Nginx, PHP-FPM, Node.js, and Cloudflare with fastcgi_read_timeout and pool tuning.

- **Publisher**: Egy Monitor (https://egymonitor.com/en)
- **Original URL**: [https://egymonitor.com/en/posts/how-to-fix-502-bad-gateway-504-timeout-nginx-cloudflare-2026](https://egymonitor.com/en/posts/how-to-fix-502-bad-gateway-504-timeout-nginx-cloudflare-2026)
- **Category**: [Web Hosting & Dev](https://egymonitor.com/en/categories/web-hosting-dev)
- **Author**: Abdelrahman Shawqi
- **Published Date**: 2026-11-25 19:56
- **Keywords**: nginx 502 bad gateway, 504 gateway timeout, cloudflare 502 fix, php-fpm tuning, web hosting troubleshooting

---

A **502 Bad Gateway** error means Nginx or Cloudflare connected to your upstream backend (PHP-FPM, Node.js, or Gunicorn) and received a refused connection, crashed process, or invalid response, whereas a **504 Gateway Time-out** means the upstream server accepted the request but failed to finish responding before the timeout window expired. You can pinpoint the exact root cause in under 30 seconds by inspecting `/var/log/nginx/error.log` and checking whether the error screen comes from Nginx or Cloudflare's edge.

When your production site sits behind Cloudflare and Nginx, double-proxy timeouts and socket mismatches are the most frequent culprits behind sudden downtime. Walking through the diagnostic matrix below lets you fix the issue permanently instead of blindly restarting services.

## 502 Bad Gateway vs 504 Timeout Diagnostic Matrix

Match the exact error line from your Nginx error log to the corresponding upstream failure and immediate fix.

HTTP Code
Nginx Error Log Signature
Root Cause
Immediate Fix

502 Bad Gateway
`connect() to unix:/run/php/php8.3-fpm.sock failed (111: Connection refused)`
PHP-FPM or Node.js process crashed or stopped
Restart service and inspect OOM killer via `dmesg`

502 Bad Gateway
`failed (13: Permission denied) while connecting to upstream`
Socket user/group mismatch between Nginx and PHP-FPM
Align `listen.owner` and `listen.group` to `www-data`

502 Bad Gateway
`upstream sent too big header while reading response header`
Large cookies or JWT tokens overflow proxy buffers
Increase `fastcgi_buffer_size` and `proxy_buffer_size`

504 Timeout
`upstream timed out (110: Connection timed out)`
Slow SQL query, external API call, or low Nginx timeout
Raise `fastcgi_read_timeout` or `proxy_read_timeout`

504 Timeout
`server reached pm.max_children setting` (in PHP-FPM log)
Traffic spike exhausted all available PHP worker processes
Tune `pm.max_children` based on available RAM

524 / 504 Edge
Cloudflare branded 502/504/524 page (no local Nginx error)
Origin took >100s or firewall blocked Cloudflare IPs
Whitelist Cloudflare IP ranges; offload jobs to queues

## Step 1 Inspect Nginx and Upstream Logs Immediately

Never guess whether PHP-FPM, Node.js, or Cloudflare dropped the connection. Run these three diagnostic commands over SSH first:

```
sudo tail -n 50 /var/log/nginx/error.log
sudo systemctl status php8.3-fpm nginx
sudo dmesg -T | grep -iE 'killed process|oom'
```

If `dmesg` shows an Out-Of-Memory (OOM) kill, your server ran out of RAM during a traffic spike and Linux terminated PHP-FPM or Node.js—causing an instant 502 Bad Gateway.

## Step 2 Fix PHP-FPM Socket Permission and Pool Exhaustion

Permission mismatches occur frequently after OS upgrades or switching Nginx users. Open your PHP-FPM pool configuration (typically `/etc/php/8.3/fpm/pool.d/www.conf`) and confirm the Unix socket ownership matches the `user` directive inside `/etc/nginx/nginx.conf`:

```
user = www-data
group = www-data
listen = /run/php/php8.3-fpm.sock
listen.owner = www-data
listen.group = www-data
listen.mode = 0660
```

Next, check `/var/log/php8.3-fpm.log` for `pm.max_children` warnings. When every PHP worker is busy, incoming requests queue until Nginx triggers a 504 timeout. Calculate your safe child limit using this formula: divide RAM allocated to PHP (for example, 2048 MB) by average process size (check with `ps --no-headers -o "rss,cmd" -C php-fpm8.3`, typically 50–80 MB):

```
pm = dynamic
pm.max_children = 30
pm.start_servers = 6
pm.min_spare_servers = 4
pm.max_spare_servers = 12
pm.max_requests = 500
```

## Step 3 Tune Nginx FastCGI and Reverse Proxy Timeouts

By default, Nginx waits only 60 seconds for an upstream server to return headers or body data, as documented in standard [Nginx 504 troubleshooting guides](https://linuxize.com/post/fix-504-gateway-timeout-error-in-nginx/). For heavy report exports, WooCommerce checkouts, or AI API calls, extend timeouts and header buffers inside your server block:

```
# Inside location ~ \.php$ for PHP-FPM
fastcgi_read_timeout 180s;
fastcgi_send_timeout 180s;
fastcgi_buffers 16 16k;
fastcgi_buffer_size 32k;

# Inside location / for Node.js, Python, or Go reverse proxies
proxy_connect_timeout 60s;
proxy_send_timeout 180s;
proxy_read_timeout 180s;
proxy_buffer_size 128k;
proxy_buffers 4 256k;
proxy_busy_buffers_size 256k;
```

Always validate syntax before reloading so you never take down other virtual hosts:

```
sudo nginx -t && sudo systemctl reload nginx && sudo systemctl restart php8.3-fpm
```

## Step 4 Resolve Cloudflare Proxy 502 and 504 Origin Errors

According to the official [Cloudflare Error 502 and 504 Support documentation](https://developers.cloudflare.com/support/troubleshooting/http-status-codes/cloudflare-5xx-errors/error-502-504/), Cloudflare displays a branded 502 or 504 page when its edge cannot establish a valid TCP/TLS handshake with your origin server, or when your origin returns an invalid HTTP response. Meanwhile, Cloudflare enforces a strict **100-second origin read timeout** on Free, Pro, and Business plans (documented on the [Cloudflare Developers portal](https://developers.cloudflare.com/)).

> 
**Critical Cloudflare Rule:** Raising Nginx's `fastcgi_read_timeout` to 300 seconds will still fail behind Cloudflare Free or Pro plans at the 100-second mark unless you move long-running tasks to background queues (such as Laravel Horizon, Redis queues, or BullMQ) or switch that specific endpoint to a DNS-only subdomain.

## Complete Verification Checklist Before Closing the Incident

- **Verify Local Origin Bypass:** Run `curl -I --resolve yourdomain.com:443:127.0.0.1 https://yourdomain.com` to confirm whether the 502/504 happens locally or only through Cloudflare.

- **Check Firewall Whitelisting:** Ensure UFW, CSF, or Fail2Ban is not rate-limiting or dropping official Cloudflare IPv4/IPv6 edge ranges.

- **Align Keepalive Timeouts:** Set Nginx `keepalive_timeout 65;` higher than Node.js's default 5-second idle timeout (or bump Node's `server.keepAliveTimeout = 65000`) to eliminate random 502 race conditions.

- **Confirm SSL Mode Alignment:** Use Cloudflare SSL mode **Full (Strict)** with a valid Origin CA or Let's Encrypt certificate instead of Flexible SSL to prevent redirect loops and handshake drops.

- **PHP-FPM Best Practice:** Pair `pm.max_requests = 500` with OPcache to stop memory leaks before OOM kills occur.

- **Node.js Best Practice:** Run processes under PM2 or systemd with automatic restart limits and explicit `headersTimeout` greater than `keepAliveTimeout`.

### Frequently Asked Questions

#### Why does my site throw 502 Bad Gateway randomly under Node.js and Nginx?

Random 502 errors with Node.js behind Nginx almost always stem from a keep-alive race condition. Node.js closes idle connections after 5 seconds by default while Nginx tries to reuse them. Setting `server.keepAliveTimeout = 65000` and `server.headersTimeout = 66000` in Node.js fixes it immediately.

#### How do I tell if a 502 error is from Cloudflare or my own Nginx server?

Look at the error page design. A plain white screen displaying `502 Bad Gateway / nginx` comes directly from your origin server, meaning Cloudflare reached Nginx fine, but Nginx failed to reach PHP-FPM or Node.js. A styled Cloudflare status diagram indicates Cloudflare could not communicate with Nginx at all.

#### Can I extend Cloudflare's 100-second timeout on the Free plan?

No. Cloudflare limits proxied HTTP origin responses to 100 seconds on Free, Pro, and Business plans. For long exports or heavy webhook jobs, process the work asynchronously in a background queue and poll a status endpoint instead.
