Understanding 502 Bad Gateway Errors: Causes, Fixes, and Prevention

4 min read

If you've ever encountered a 502 Bad Gateway error, you know the frustration. Your app was working fine, then suddenly — nothing. Let's break down what's actually happening behind the scenes and how to fix it.

What Is a 502 Bad Gateway Error?

A 502 status code means that a server acting as a gateway or proxy received an invalid response from an upstream server. In simpler terms, there's a middleman in your request chain, and that middleman got a bad answer (or no answer at all) from the server it was talking to.

The 502 (Bad Gateway) status code indicates that the server, while acting as a gateway or proxy, received an invalid response from an inbound server it accessed while attempting to fulfill the request. — RFC 9110, Section 15.6.3

Common Causes

Here are the most frequent culprits behind 502 errors:

  1. Upstream server crashes — Your application process died or became unresponsive
  2. Timeouts — The upstream server took too long to respond
  3. Misconfigured reverse proxy — NGINX, Apache, or your load balancer is pointing to the wrong backend
  4. DNS resolution failures — The proxy can't resolve the upstream hostname
  5. Resource exhaustion — The upstream server ran out of memory, file descriptors, or connections

How to Diagnose a 502

Check Your Application Logs

The first place to look is always your application logs. Most 502 errors originate from the upstream server, not the proxy itself.

# Check NGINX error logs
tail -f /var/log/nginx/error.log
 
# Check your application logs (example for a Node.js app)
pm2 logs my-app --lines 100
 
# Check system-level issues
dmesg | tail -20
journalctl -u my-app --since "5 minutes ago"

Inspect the Reverse Proxy Configuration

If you're using NGINX, a common misconfiguration looks like this:

# Bad — upstream timeout is too short
location /api {
    proxy_pass http://backend:3000;
    proxy_read_timeout 5s;
}
 
# Better — give your backend reasonable time to respond
location /api {
    proxy_pass http://backend:3000;
    proxy_read_timeout 60s;
    proxy_connect_timeout 10s;
    proxy_send_timeout 60s;
}

Test the Upstream Directly

Bypass the proxy and hit your backend server directly:

# If your backend runs on port 3000
curl -v http://localhost:3000/health
 
# Check if the process is even running
ss -tlnp | grep 3000

Prevention Strategies

Preventing 502 errors requires a multi-layered approach:

  • Health checks — Configure your load balancer to actively check backend health
  • Graceful shutdowns — Handle SIGTERM properly so in-flight requests complete before the process exits
  • Connection pooling — Reuse connections to avoid exhausting file descriptors
  • Circuit breakers — Use patterns like the circuit breaker pattern to fail fast when backends are unhealthy
  • Auto-scaling — Scale your backend horizontally when traffic increases

Here's a simple health check endpoint in Node.js:

app.get("/health", (req, res) => {
  const health = {
    status: "ok",
    uptime: process.uptime(),
    timestamp: Date.now(),
  };
 
  try {
    // Check critical dependencies
    // e.g., database connectivity
    res.status(200).json(health);
  } catch (error) {
    health.status = "error";
    res.status(503).json(health);
  }
});

502 vs. Other 5xx Errors

It's easy to confuse 502 with related status codes:

StatusNameMeaning
500Internal Server ErrorThe server itself encountered an error
502Bad GatewayThe proxy got a bad response from upstream
503Service UnavailableThe server is overloaded or under maintenance
504Gateway TimeoutThe proxy didn't get a response in time

The key difference: 502 means the proxy got a response, but it was invalid. With a 504, the proxy got no response at all before the timeout.

Wrapping Up

502 errors are almost always an infrastructure issue, not an application bug. Focus your debugging on the communication layer between your proxy and your backend servers. Check logs, verify configurations, and make sure your upstream servers are healthy and responsive.

For more details on related status codes, check out our pages on 500 Internal Server Error, 503 Service Unavailable, and 504 Gateway Timeout.