502 Bad Gateway Error: Causes & Solutions
A 502 Bad Gateway error means a server acting as a gateway or proxy received an invalid response from an upstream server. This is a server-side issue, not something wrong with your request. This guide explains why 502 errors happen and how to fix them from both client and server perspectives.
What Does 502 Bad Gateway Mean?
When you see a 502 error, there are at least two servers involved:
- The gateway/proxy server (e.g., Nginx, Cloudflare, a load balancer) that you are connecting to
- The upstream/origin server (e.g., your application server, API backend) that processes the request
The gateway server successfully received your request but got a bad, incomplete, or no response from the upstream server.
Common Causes
| Cause | Description |
|---|---|
| Upstream server crashed | The application server is down or unresponsive |
| Upstream server overloaded | Too many requests overwhelmed the backend |
| Timeout between servers | The upstream server took too long to respond |
| Incorrect proxy configuration | Nginx/Apache misconfigured reverse proxy settings |
| Firewall blocking | Firewall between gateway and upstream blocking traffic |
| DNS resolution failure | Gateway cannot resolve the upstream server hostname |
| SSL/TLS mismatch | Certificate issues between gateway and upstream |
How to Diagnose 502 Errors
Check with cURL
# Check response headers for clues
curl -I https://example.com
Verbose output to see the full exchange
curl -v https://example.com 2>&1
Check with timing information
curl -w "DNS: %{time_namelookup}s\nConnect: %{time_connect}s\nTLS: %{time_appconnect}s\nTotal: %{time_total}s\n" \
-o /dev/null -s https://example.com
Check with Python
import requests
try:
response = requests.get("https://example.com", timeout=30)
print(f"Status: {response.status_code}")
print(f"Server: {response.headers.get('Server')}")
except requests.exceptions.ConnectionError as e:
print(f"Connection error: {e}")
Fixes for Website Visitors
If you encounter a 502 error while browsing:
- Refresh the page — The issue may be temporary
- Wait and retry — Server may be restarting or under maintenance
- Clear browser cache — Cached DNS or stale data may cause issues
- Try a different browser or device — Rule out client-side problems
- Check the site’s status page — Many services have status.example.com
- Use a proxy — If the issue is geographic or ISP-related, a proxy may help
# Test from a different IP via proxy
curl -x http://user:pass@proxy.example.com:8080 https://example.com
Fixes for Server Administrators
Check Upstream Server Status
# Check if the application server is running
systemctl status your-app-server
pm2 status # For Node.js apps
Check if the port is listening
ss -tlnp | grep 8080
netstat -tlnp | grep 8080
Test upstream directly (bypassing the gateway)
curl http://localhost:8080/health
Check Nginx Configuration
# Common Nginx reverse proxy config that can cause 502
upstream backend {
server 127.0.0.1:8080;
}
server {
listen 80;
location / {
proxy_pass http://backend;
# Increase timeouts to prevent 502 on slow responses
proxy_connect_timeout 60s;
proxy_send_timeout 60s;
proxy_read_timeout 60s;
# Increase buffer sizes
proxy_buffer_size 128k;
proxy_buffers 4 256k;
proxy_busy_buffers_size 256k;
}
}
# Test Nginx configuration
nginx -t
Reload Nginx
systemctl reload nginx
Check Nginx error logs
tail -f /var/log/nginx/error.log
Check Apache Configuration
# Check Apache error log
tail -f /var/log/apache2/error.log
Increase proxy timeout
In apache config:
ProxyTimeout 60
ProxyPass / http://localhost:8080/
ProxyPassReverse / http://localhost:8080/
Restart Apache
systemctl restart apache2
Check Application Logs
# Node.js / PM2
pm2 logs your-app
Python / Gunicorn
tail -f /var/log/gunicorn/error.log
PHP-FPM
tail -f /var/log/php-fpm/error.log
Docker
docker logs your-container
Handling 502 Errors in Code
When building scrapers or API clients, implement retry logic for 502 errors since they are usually temporary.
import requests
import time
def robust_request(url, max_retries=3):
for attempt in range(max_retries):
try:
response = requests.get(url, timeout=30)
if response.status_code == 502:
wait = 2 ** attempt
print(f"502 Bad Gateway. Retrying in {wait}s...")
time.sleep(wait)
continue
return response
except requests.exceptions.ConnectionError:
wait = 2 ** attempt
print(f"Connection failed. Retrying in {wait}s...")
time.sleep(wait)
raise Exception("Failed after retries")
# Retry with cURL
curl --retry 3 --retry-delay 5 --retry-all-errors https://example.com
502 vs Other 5xx Errors
| Code | Meaning | Cause |
|---|---|---|
| 500 | Internal Server Error | Bug in application code |
| 502 | Bad Gateway | Upstream server sent invalid response |
| 503 | Service Unavailable | Server overloaded or in maintenance |
| 504 | Gateway Timeout | Upstream server did not respond in time |
FAQ
Is a 502 error my fault?
No. A 502 error is a server-side issue. The problem is between the gateway and the upstream server, not with your request.
How long does a 502 error last?
It depends on the cause. Server restarts take seconds to minutes. Traffic overload may last until the spike subsides. Configuration issues persist until an administrator fixes them.
Can a CDN cause 502 errors?
Yes. If a CDN like Cloudflare cannot reach your origin server, it will return a 502 error. Check your origin server’s health and ensure the CDN can connect to it.
Should I retry requests that get 502?
Yes. Since 502 errors are typically temporary, retrying with exponential backoff is appropriate. Most HTTP client libraries support automatic retries for 5xx errors.