HTTP

Status Code

HTTP 502 Bad Gateway: Server Communication Error

Learn what 502 Bad Gateway means, why it happens, and how to fix it. Guide covering proxy errors, upstream failures, and troubleshooting.

3 min read intermediate Try in Playground

TL;DR: 502 Bad Gateway means a proxy got an invalid response from upstream. Usually a temporary server issue.

What is 502 Bad Gateway?

A 502 occurs when a gateway/proxy receives an invalid response from an upstream server.

Client → Proxy → Upstream Server (broken)

       502 Bad Gateway

The proxy works fine—the problem is behind it.

Common Causes

LevelCause
AppCrashed, overloaded, OOM killed, wrong port
InfrastructureServer down, network partition, firewall
ConfigWrong upstream address, timeout too short

How to Fix

For Users

  1. Refresh the page
  2. Wait and retry (server might be restarting)
  3. Clear browser cache

For Admins

# Check if upstream is running
systemctl status your-app
curl -v http://localhost:3000/health

# Check proxy logs
tail -f /var/log/nginx/error.log
```nginx

Common log messages:

- `upstream prematurely closed connection`
- `connect() failed (111: Connection refused)`
- `upstream timed out`

### Nginx Configuration

```nginx
upstream backend {
    server 127.0.0.1:3000;
    server 127.0.0.1:3001 backup;
}

server {
    location / {
        proxy_pass http://backend;
        proxy_connect_timeout 60s;
        proxy_read_timeout 60s;
        proxy_next_upstream error timeout http_502;
    }
}

502 vs 503 vs 504

CodeMeaning
502Invalid response from upstream
503Server overloaded/maintenance
504No response from upstream (timeout)

Client Retry Logic

async function fetchWithRetry(url, retries = 3) {
  for (let i = 0; i < retries; i++) {
    const response = await fetch(url)
    if (response.status === 502) {
      await new Promise((r) => setTimeout(r, Math.pow(2, i) * 1000))
      continue
    }
    return response
  }
  throw new Error('Max retries exceeded')
}

Diagnosing 502 Errors in Production

When a 502 appears in production, the first step is to determine whether the problem is in the upstream application or in the network path between the proxy and the upstream. Check the proxy error log first — nginx logs the specific reason for each 502, such as upstream prematurely closed connection, connect() failed (111: Connection refused), or upstream sent invalid header.

A Connection refused error means the upstream process is not listening on the expected port. This usually means the application crashed, was never started, or is listening on a different port than the proxy expects. Check systemctl status, pm2 list, or your container orchestration platform to verify the process is running.

A prematurely closed connection error means the upstream accepted the connection but closed it before sending a complete HTTP response. This often happens when the application runs out of memory and is killed by the OS, when an unhandled exception causes the process to exit mid-response, or when a database connection pool is exhausted and the application gives up.

For intermittent 502 errors under load, the cause is often a mismatch between the proxy’s keep-alive timeout and the upstream’s keep-alive timeout. If the upstream closes an idle connection just as the proxy tries to reuse it, the proxy gets a connection reset and returns 502. The fix is to set the upstream’s keep-alive timeout slightly longer than the proxy’s, so the proxy always closes idle connections before the upstream does.

Frequently Asked Questions

What does 502 Bad Gateway mean?

A 502 error means a proxy/gateway received an invalid response from an upstream server. The proxy works, but the backend isn't responding correctly.

What causes 502 Bad Gateway?

Common causes: upstream server crashed, network issues between proxy and upstream, timeout, misconfigured proxy, or firewall blocking communication.

How do I fix a 502 error?

Users: refresh, clear cache, wait and retry. Admins: check upstream server health, review proxy logs, verify network connectivity.

What is the difference between 502 and 504?

502 means invalid response from upstream. 504 means no response (timeout). Both indicate upstream problems.

Keep Learning