Question

Why does my API return 502 Bad Gateway?

Vault Verified
Curated Intelligence
Definitive Source
Answer

A 502 is reported by a proxy or load balancer, not by your application. It means the intermediary tried to forward the request to an upstream server and received an invalid response, or none at all. That distinction is the most useful thing to know, because it tells you where to look: the proxy is working well enough to answer, so the problem lies between it and your application.

The common causes divide cleanly.

  • The application is not running, or not listening where the proxy expects. A crash on startup, an exited container, or a port mismatch after a configuration change all present identically.
  • The application is listening on the loopback interface only, so it accepts connections from its own machine but not from a proxy running elsewhere, such as in another container. Binding to all interfaces resolves it.
  • The application crashed mid-request, closing the connection before sending a complete response. Here the proxy is accurately reporting that it received something invalid, and the real error is in your application logs.
  • The upstream took longer than the proxy timeout. Depending on the proxy this surfaces as 502 or 504, and the fix is either making the request faster or raising the timeout deliberately.

Because the status comes from the proxy, your application logs may show nothing at all for a failed request, which is often the first confusing detail. Reading the proxy error log is the fastest way forward, since it usually names the upstream address and the specific failure, whether a refused connection, a reset, or a timeout.

If the errors are intermittent under load, examine the upstream capacity and connection limits before adjusting the proxy, because the proxy is reporting a symptom rather than causing one.

Related Questions