You hit a 502 Bad Gateway error. The page won’t load, your visitors are bouncing, and you have no idea what’s actually broken. The good news: this error almost always has a fixable cause, and most of the time you can resolve it in under 15 minutes.
This guide walks you through exactly what a 502 error is, why it happens, and how to fix it on any setup, whether you’re a site owner, developer, or just someone trying to load a webpage.
What Is a 502 Bad Gateway Error?
A 502 Bad Gateway error is an HTTP status code that means one server received an invalid response from another server it was talking to upstream. In plain terms: your web server asked a backend server for something, got back garbage (or nothing), and doesn’t know what to do with it.
It’s different from a 503 (service unavailable) or a 504 (gateway timeout). A 502 specifically points to a bad or corrupt response, not just a slow one or an overloaded one.
You’ll see it show up in different ways depending on the server or CDN:
- “502 Bad Gateway”
- “502 Proxy Error”
- “Error 502”
- “HTTP 502”
- “502 Service Temporarily Overloaded”
- Cloudflare’s custom “Error 502: Bad Gateway” page
All of these mean the same thing underneath.

What Actually Causes a 502 Error?
Before you start clicking around and restarting things randomly, it helps to understand the real causes. A 502 typically comes from one of these:
Server-side causes (most common):
- A PHP-FPM or FastCGI process crashed or ran out of workers
- Nginx or Apache trying to talk to a backend app (Node.js, Python, Ruby) that’s down
- A WordPress site where a plugin crashed the PHP process
- Memory limits on the server being hit, killing processes mid-request
- A misconfigured upstream proxy or load balancer
Network and infrastructure causes:
- Firewall blocking traffic between the proxy and backend
- DNS pointing to the wrong server
- SSL certificate mismatch between the proxy and origin
- A CDN (like Cloudflare) failing to reach the origin server
Temporary/overload causes:
- A traffic spike overwhelming backend workers
- A deployment that briefly took the app offline
- A cron job or database query hogging all the resources
Knowing which category your 502 falls into saves a lot of time.
Quick Fixes to Try First
Before you dig deep, do these first. They solve the problem more often than you’d think.
1. Reload the Page
Hit F5 or Ctrl+R. Sometimes a 502 is a blip, a momentary hiccup between servers that resolves in seconds. If it was temporary, it’ll be gone.
2. Try a Different Browser or Incognito Mode
Rules out a browser cache issue. If it loads in incognito, clear your browser cache and cookies.
3. Check if the Site Is Down for Everyone
Use Down For Everyone Or Just Me or Is It Down Right Now. If others see it too, the problem is on the server side. If only you see it, it might be DNS or your ISP.
4. Flush Your DNS Cache
On Windows:
ipconfig /flushdns
On Mac:
sudo dscacheutil -flushcache; sudo killall -HUP mDNSResponder
On Linux:
sudo systemd-resolve --flush-caches
5. Try a Different Network
Switch from WiFi to mobile data or vice versa. This can reveal if the issue is specific to your connection or ISP.
How to Fix 502 Bad Gateway on Your Own Server
If you run the server, here’s where to actually look.
Check Your Server Error Logs First
This is the single most useful step. The logs will almost always tell you what’s wrong.
For Nginx:
tail -f /var/log/nginx/error.log
For Apache:
tail -f /var/log/apache2/error.log
# or
tail -f /var/log/httpd/error_log
For PHP-FPM:
tail -f /var/log/php-fpm/error.log
# or check your pool config for the log path
Look for lines showing “upstream” errors, connection refused messages, or process crashes. These tell you exactly what’s breaking.
Restart Backend Services
If PHP-FPM is the backend process (common with WordPress and other PHP sites), restart it:
sudo systemctl restart php8.1-fpm
# or whichever version you're running
sudo systemctl restart php-fpm
Then restart Nginx or Apache:
sudo systemctl restart nginx
sudo systemctl restart apache2
Check the status after restarting:
sudo systemctl status php8.1-fpm
sudo systemctl status nginx
If a service fails to start, the status output will show you why.
Check PHP-FPM Pool Configuration
A very common cause of 502 errors under load is running out of PHP-FPM worker processes. When all workers are busy, new requests get a 502.
Find your pool config (usually at /etc/php/8.1/fpm/pool.d/www.conf) and look at these settings:
| Setting | Default | Better for Busy Sites |
|---|---|---|
| pm | dynamic | ondemand or static |
| pm.max_children | 5 | 20-50 (based on RAM) |
| pm.start_servers | 2 | 5 |
| pm.min_spare_servers | 1 | 5 |
| pm.max_spare_servers | 3 | 10 |
| pm.max_requests | 500 | 200 |
A rough formula: pm.max_children = Available RAM / Average PHP process size. If your average PHP process uses 50MB and you have 2GB free for PHP, set max_children to around 40.
After editing, restart PHP-FPM.
Check Nginx Upstream Configuration
If you’re proxying to a Node.js, Python, or other app, check your Nginx config for the upstream block:
upstream myapp {
server 127.0.0.1:3000;
keepalive 32;
}
server {
location / {
proxy_pass http://myapp;
proxy_connect_timeout 60s;
proxy_read_timeout 60s;
proxy_send_timeout 60s;
}
}
If the app on port 3000 is down, you’ll get a 502. Check if it’s actually running:
ss -tlnp | grep 3000
# or
netstat -tlnp | grep 3000
If nothing shows up, your app is down. Start it back up.
Check Resource Usage
A server that’s out of memory will start killing processes, causing 502s:
free -h # memory usage
top # live CPU and process view
df -h # disk space (yes, full disk causes 502s too)
If RAM is exhausted, you need to either add more, reduce worker counts, or optimize your app’s memory usage. A full disk can cause database crashes and file write failures that trigger 502s.
Fixing 502 Errors with Cloudflare
Cloudflare sits in front of millions of sites. When you see a Cloudflare-branded 502 page, it means Cloudflare itself couldn’t reach your origin server.
What the Error Screen Tells You
Cloudflare shows different error codes that give you a hint:
| Cloudflare Code | Meaning |
|---|---|
| 502 / 504 | Origin server returned an error or timed out |
| 521 | Origin server refused the connection |
| 522 | Connection timed out |
| 523 | Origin is unreachable |
| 525 | SSL handshake failed |
For a true 502 from Cloudflare, the origin server responded but with something invalid.
Steps to Fix It
Step 1: Log into Cloudflare dashboard and check the “Health Checks” section for your domain to confirm what Cloudflare is seeing.
Step 2: Check if your origin IP is correct in Cloudflare DNS settings. If you recently migrated servers or changed IPs, update the A record.
Step 3: Verify your SSL mode. Go to SSL/TLS in your Cloudflare dashboard. If you set it to “Full (Strict)” but your origin doesn’t have a valid SSL certificate, you’ll get a 502. Try switching to “Full” temporarily to diagnose.
Step 4: Temporarily disable Cloudflare by clicking the cloud icon on your DNS record to make it grey (DNS only). Then access your site directly. If it loads, the origin is fine and the issue is between Cloudflare and your origin. If it still breaks, the origin server itself is the problem.
Step 5: Check Cloudflare’s status page at cloudflarestatus.com to rule out an issue on Cloudflare’s end.
Fixing 502 Errors in WordPress
WordPress gets its own section because it’s where most people encounter this error in the wild.
Common WordPress-Specific Causes
- A plugin running a long-running process that kills the PHP worker
- WP-Cron firing at a bad moment
- Autosave or update process conflicting with a slow database query
- A caching plugin that’s misconfigured and passing bad responses
How to Diagnose
Step 1: Deactivate all plugins
If you can access wp-admin, go to Plugins > Installed Plugins, select all, and bulk deactivate. If the 502 clears, reactivate them one by one to find the culprit.
If you can’t access wp-admin (the 502 blocks everything), connect via FTP or SSH and rename the plugins folder:
mv wp-content/plugins wp-content/plugins_backup
WordPress will disable all plugins. Test the site. Then rename it back and reactivate one at a time.
Step 2: Switch to a default theme
A poorly coded theme can also cause this. Via FTP/SSH:
mv wp-content/themes/your-theme wp-content/themes/your-theme-backup
WordPress falls back to a default theme.
Step 3: Increase PHP memory limit
In your wp-config.php:
define('WP_MEMORY_LIMIT', '256M');
define('WP_MAX_MEMORY_LIMIT', '512M');
Also update php.ini or .htaccess if your host allows it:
php_value memory_limit 256M
Step 4: Check the WP debug log
Add these lines to wp-config.php:
define('WP_DEBUG', true);
define('WP_DEBUG_LOG', true);
define('WP_DEBUG_DISPLAY', false);
Then check wp-content/debug.log for error messages.
Fixing 502 in Node.js / Python / Ruby Apps
If you’re running a custom app behind Nginx or Apache, the problem is almost always that the app process died.
Check if the App Is Running
# For a Node.js app on port 3000
ps aux | grep node
ss -tlnp | grep 3000
# For a Python/Gunicorn app
ps aux | grep gunicorn
ss -tlnp | grep 8000
Common Fixes
Restart the process manager:
If you’re using PM2 for Node.js:
pm2 list
pm2 restart all
pm2 logs # to see what crashed it
If you’re using Supervisor:
sudo supervisorctl status
sudo supervisorctl restart your_app
If you’re using systemd:
sudo systemctl restart your-app.service
sudo journalctl -u your-app.service -n 50
Check for port conflicts:
Sometimes a previous crashed process is still holding the port:
sudo lsof -i :3000
sudo kill -9 <PID>
Then restart your app.
Look at the app’s own logs:
Your app likely writes its own logs. Python/Django/Flask logs, Node.js console output captured by PM2, etc. The crash reason is almost always in there.
502 Errors on Load Balancers (AWS, GCP, nginx upstream)
If you’re running multiple servers behind a load balancer, a 502 can mean one or more backend instances failed their health check or crashed.
AWS Application Load Balancer
In the AWS console:
- Go to EC2 > Load Balancers > your ALB
- Click on Target Groups
- Check the “Targets” tab for any instances showing “unhealthy”
- SSH into the unhealthy instance and check the app and server logs
An unhealthy instance usually means the health check endpoint returned a non-200 code, or the app on that server isn’t responding on the expected port.
Nginx Upstream 502 Fixes
If all upstream servers are down, Nginx returns 502. You can configure Nginx to retry other servers in the upstream block:
upstream backend {
server 192.168.1.10:8080 max_fails=3 fail_timeout=30s;
server 192.168.1.11:8080 max_fails=3 fail_timeout=30s;
server 192.168.1.12:8080 backup;
}
The max_fails and fail_timeout settings tell Nginx to mark a server as failed after 3 errors within 30 seconds and try another one.
Preventing 502 Errors Going Forward
Fixing the immediate problem is important, but stopping it from happening again matters more.
Monitoring and Alerts
Set up uptime monitoring so you know about 502s before your users do. Tools like UptimeRobot (free tier available), Better Uptime, or Datadog can alert you via email, SMS, or Slack within seconds of a 502 occurring. According to Cloudflare’s documentation on HTTP errors, proactive monitoring of 5xx errors is one of the most effective ways to reduce mean time to recovery.
Rate Limiting and Queueing
If spikes in traffic trigger your 502s, implement rate limiting at the Nginx level to protect your backend:
limit_req_zone $binary_remote_addr zone=api:10m rate=10r/s;
location /api/ {
limit_req zone=api burst=20 nodelay;
proxy_pass http://backend;
}
This limits each IP to 10 requests per second with a burst allowance of 20, preventing a single client or bot from flooding your backend workers.
Auto-Restart Configuration
Make sure your app processes automatically restart on failure. With systemd:
[Service]
Restart=always
RestartSec=5s
With PM2:
pm2 startup # configure PM2 to survive reboots
pm2 save
Regular Resource Auditing
Check your server’s memory and CPU usage trends weekly. A server that creeps toward its resource limits will eventually start throwing 502s under load. Tools like Netdata or Grafana with Prometheus give you visibility before it becomes a crisis.
502 Error Troubleshooting Table
| Situation | Most Likely Cause | First Fix |
|---|---|---|
| 502 on all pages | PHP-FPM or app process down | Restart PHP-FPM / app service |
| 502 only under traffic | Not enough PHP/app workers | Increase pm.max_children |
| 502 after deploy | New code broke the app | Check app logs, rollback if needed |
| 502 with Cloudflare | Origin unreachable or SSL issue | Check origin server, verify SSL mode |
| 502 on WordPress | Plugin or memory issue | Deactivate plugins, raise memory limit |
| 502 on load balancer | One or more backends unhealthy | Check target group health in AWS/GCP console |
| 502 intermittently | Overloaded workers or slow DB queries | Add workers, optimize slow queries |
| 502 after server move | DNS still pointing to old server | Update DNS or Cloudflare A record |
Summary
A 502 Bad Gateway error is one of the more solvable server errors once you know where to look. It means a server in your chain received an invalid response from another server, and it almost always boils down to a crashed process, misconfigured proxy, insufficient resources, or a network/DNS issue.
The fastest path to resolution:
- Check your error logs first, always
- Restart your backend services (PHP-FPM, your app process, Nginx)
- Confirm the app is actually running on the expected port
- Check memory and disk space
- If using Cloudflare, verify DNS and SSL mode
- For WordPress, isolate plugins and raise the memory limit
Once it’s fixed, put monitoring in place and configure auto-restart so the next crash gets handled faster. The MDN documentation on HTTP response status codes is also a useful reference if you want to understand the full HTTP spec around gateway errors.
- How to Fix “File Is Open in Another Program” Error in Windows (2026 Guide) - February 19, 2026
- Speed Up Your Mac With These Top 10 Mac Troubleshooting Tips (2026 Guide) - February 19, 2026
- Fixed “Unknown USB Device (Device Descriptor Request Failed)”: 2026 Guide - February 19, 2026
