502 Bad Gateway Error | Causes and Solutions

A 502 Bad Gateway error occurs when a proxy or gateway receives an invalid response from an upstream server. Learn the common causes, troubleshooting steps, and how to fix 502 errors in your infrastructure.

A 502 Bad Gateway error occurs when a server acting as a gateway or proxy receives an invalid response from an upstream server. This typically happens in distributed architectures where a load balancer, CDN, or API gateway sits between clients and application servers. Among all HTTP status codes, 502 is one of the most disruptive because it points to a failure between layers—not at the client or the final origin alone.

502 Bad Gateway Error

What 502 Bad Gateway Means

The HTTP Definition

Per RFC 9110, 502 indicates “the server, while acting as a gateway or proxy, received an invalid response from an upstream server it accessed while attempting to fulfill the request.”

Key characteristics:

  • The server you reached is a proxy, not the origin
  • The proxy tried to reach upstream but got a bad response
  • “Invalid response” includes malformed HTTP, empty response, or connection reset

502 vs 503 vs 504

CodeMeaningRoot Cause
502 Bad GatewayInvalid response from upstreamApplication crash, malformed response, protocol mismatch
503 Service UnavailableServer cannot handle requestOverload, maintenance, resource exhaustion
504 Gateway TimeoutNo response from upstreamUpstream too slow, timeout exceeded

Common Causes of 502 Bad Gateway

1. Application Server Not Running

The upstream server isn’t accepting connections:

Terminal window
# Check if application is running
systemctl status your-app
netstat -tlnp | grep :3000

2. Application Server Crashed

The process crashed while handling the request:

# Check application logs
journalctl -u your-app -f
# Or application-specific logs
tail -f /var/log/app/error.log

3. Protocol Mismatch

The proxy expects HTTP but the upstream sends something else:

  • HTTP/1.1 vs HTTP/2 mismatch
  • SSL/TLS configuration mismatch
  • WebSocket upgrade failures

4. Response Too Large

The upstream response exceeds buffer limits:

Nginx:

# Fix: Increase buffer sizes
proxy_buffer_size 128k;
proxy_buffers 4 256k;
proxy_busy_buffers_size 256k;

5. Connection Reset

The upstream closed the connection unexpectedly:

  • Application timeout before proxy timeout
  • Memory exhaustion causing process kill
  • Network issues between proxy and upstream

6. Wrong Port or Address

The proxy connects to the wrong upstream:

# Verify upstream configuration
upstream backend {
server 127.0.0.1:3000; # Correct address?
}

Troubleshooting 502 Errors

Step 1: Identify Which Layer Generated the 502

Client → [CDN](/en/learning/cdn/what-is-a-cdn/) → [Load Balancer](/en/learning/performance/what-is-load-balancing/) → API Gateway → Application
↑ ↑ ↑ ↑
502 502 502 (origin of problem)

Check response headers:

  • Server: Identifies which server responded
  • X-Cache-Status: CDN information
  • Via: Proxy chain information

Step 2: Check Upstream Server Health

Terminal window
# Test direct connection to upstream
curl http://localhost:3000/health
# Check if port is listening
netstat -tlnp | grep :3000
# Check process status
ps aux | grep node
systemctl status your-app

Step 3: Check Proxy/Gateway Logs

Nginx:

Terminal window
tail -f /var/log/nginx/error.log
# Look for: "upstream sent an invalid response"
# Look for: "connect() failed"
# Look for: "Connection refused"

HAProxy:

Terminal window
tail -f /var/log/haproxy.log
# Look for: "sH" (502 status)

Azion:

Real-Time Events → filter by status 502
# Check upstream_cache_status and upstream_response_time fields

Cloud Load Balancer: Check the cloud provider’s logs and metrics dashboards.

Step 4: Check Network Connectivity

Terminal window
# Test from proxy server to upstream
curl -v http://upstream-server:port/
# Check firewall rules
iptables -L -n
# Check DNS resolution
nslookup upstream-server

Step 5: Compare Timeout Settings

The proxy timeout should be longer than the upstream application timeout:

# Nginx proxy timeouts
proxy_connect_timeout 60s;
proxy_send_timeout 60s;
proxy_read_timeout 60s;

How to Fix 502 Errors

Fix Application Server Issues

Terminal window
# Restart the application
systemctl restart your-app
# Check for crashes
journalctl -u your-app -n 100
# Monitor resources
top -p $(pgrep -f "node.*app")

Fix Nginx Configuration

upstream backend {
server 127.0.0.1:3000 max_fails=3 fail_timeout=30s;
keepalive 32;
}
server {
location / {
proxy_pass http://backend;
proxy_http_version 1.1;
proxy_set_header Connection "";
# Increase timeouts
proxy_connect_timeout 60s;
proxy_send_timeout 60s;
proxy_read_timeout 60s;
# Increase buffers for large responses
proxy_buffer_size 128k;
proxy_buffers 4 256k;
}
}

Fix Health Checks

Ensure the proxy has accurate health checks:

# Nginx passive health checks
upstream backend {
server 127.0.0.1:3000 max_fails=3 fail_timeout=30s;
}
# Nginx active health checks (requires Plus or third-party module)
# HAProxy
backend app_servers
balance roundrobin
option httpchk GET /health
server app1 127.0.0.1:3000 check inter 5s fall 3 rise 2
# Azion: configure health checks via Origins settings in the Console
# Set health check path, interval, and failure threshold per origin

Implement Circuit Breakers

Prevent cascading failures:

const circuitBreaker = new CircuitBreaker(fetchFromUpstream, {
timeout: 5000,
errorThresholdPercentage: 50,
resetTimeout: 30000
});
circuitBreaker.fire()
.catch(err => {
// Return fallback or 503
});

Prevention Strategies

1. Proper Resource Sizing

Monitor and size for peak load:

  • Memory per process
  • CPU limits
  • Connection pool size
  • File descriptor limits

2. Graceful Restarts

Use graceful restart to avoid dropped connections:

Terminal window
# Nginx
nginx -s reload
# Node.js with PM2
pm2 reload app --update-env

3. Health Endpoints

Implement proper health checks:

app.get('/health', (req, res) => {
const healthy = checkDatabase() && checkMemory();
res.status(healthy ? 200 : 503).json({ status: healthy ? 'ok' : 'unhealthy' });
});

4. Rate Limiting

Prevent overload from traffic spikes:

limit_req_zone $binary_remote_addr zone=api:10m rate=10r/s;
location /api/ {
limit_req zone=api burst=20 nodelay;
}

Monitoring 502 Errors

Track these metrics:

  • 502 rate: Percentage of requests returning 502
  • Upstream response time: Time to get response from backend
  • Connection errors: Failed connections to upstream
  • Process health: Application server availability

Alert thresholds:

  • 502 rate > 0.1%: Investigate
  • 502 rate > 1%: Critical incident
  • Any 502 spike after deployment: Rollback and investigate

Frequently Asked Questions

What’s the difference between 502 and 504? 502 means the upstream sent an invalid response. 504 means the upstream didn’t respond at all (timeout).

Why does 502 happen after deployment? Common causes: application not starting, wrong port, missing environment variables, database migration issues.

How do I fix 502 in Kubernetes? Check pod status, logs, readiness probes, and service selectors.

Can a CDN cause 502 errors? Yes. If the origin returns an invalid response, the CDN will return 502 to the client.

Should clients retry on 502? Only for idempotent methods (GET, PUT, DELETE). Use exponential backoff.

What does Nginx “upstream prematurely closed connection” mean? The application closed the connection before sending a complete response. Check application logs for crashes or timeouts.

stay up to date

Subscribe to our Newsletter

Get the latest product updates, event highlights, and tech industry insights delivered to your inbox.