502 Bad Gateway & 504 Gateway Timeout: Diagnosing Cloudflare and Host Outages
What Is the Difference Between a 502 and 504 Error?
A 502 Bad Gateway means the proxy or CDN (such as Cloudflare) received an invalid response from the upstream origin server — typically because the origin is down, returning errors, or responding with a malformed HTTP response. A 504 Gateway Timeout means the proxy received no response at all within the timeout window — the origin server accepted the connection but never sent a reply, usually due to overload, a hung process, or a database query that never finished.
Quick Diagnostic Table
| Error Code | What Cloudflare Sees | Likely Origin Cause | First Check |
|---|---|---|---|
| 502 Bad Gateway | Invalid response from origin | Origin down / crashing | Check origin server logs |
| 504 Gateway Timeout | No response within timeout | Origin overloaded / DB hung | Check slow query logs |
| 502 + Cloudflare Ray ID | Cloudflare reached origin | PHP/Node crash | Restart app service |
| 504 + no Ray ID | Cloudflare cannot reach origin | Origin server unreachable | Check firewall/security group |
How to Diagnose and Fix 502/504 Errors
Step 1 — Check Cloudflare Status
Visit cloudflarestatus.com to confirm Cloudflare itself isn't experiencing an outage. Check for incidents affecting your region. Also check your hosting provider's status page simultaneously.
Step 2 — Bypass Cloudflare and Hit Origin Directly
Find your origin server's IP from your DNS panel and access it directly: curl -I http://YOUR_ORIGIN_IP -H "Host: yourdomain.com". If this returns a 500 or hangs, the problem is your origin server. If it returns 200, Cloudflare cannot reach your origin — check firewall rules.
Step 3 — Check Origin Server Logs
- Nginx:
sudo tail -50 /var/log/nginx/error.log - Apache:
sudo tail -50 /var/log/apache2/error.log - Node.js/PM2:
pm2 logs
Look for OOM (out of memory) kills, PHP-FPM pool exhaustion, or DB connection errors — these are the most common 504 causes.
Step 4 — Increase Cloudflare Timeout Settings
In Cloudflare Dashboard → Speed → Optimization → Protocol Optimization, check your proxy timeout settings. For 504 errors caused by slow origin responses, increase the "Proxy Read Timeout" in Cloudflare's Configuration Rules for the affected route (max 600 seconds on Pro plans).
Step 5 — Restart Origin Application Services
SSH into your origin server and restart the application stack:
- PHP-FPM:
sudo systemctl restart php8.1-fpm - Node/PM2:
pm2 restart all - Nginx:
sudo systemctl restart nginx - MySQL:
sudo systemctl restart mysql
Verification
✓ How to Confirm the Fix Worked
Run curl -I https://yourdomain.com and confirm you receive HTTP/2 200 with a CF-Cache-Status header — this confirms Cloudflare is successfully proxying and the origin is responding. Monitor your Cloudflare dashboard's "Overview" tab for error rate — it should drop to near zero within 5 minutes of fixing the origin.