Developer Toolbox
5xx server errorOften retryableComes from the proxy

502 Bad Gateway

A gateway or proxy (nginx, a load balancer, a CDN) passed the request on and got an invalid response back, or none at all. The application behind it may never have seen the request.

Open cURL Builder Build the health check request, with verbose output.

Common causes

  • The application crashed, is restarting or isn't running, so the proxy's connection is refused.
  • The proxy points at the wrong host or port, or the app listens on 127.0.0.1 inside a container, where the proxy can't reach it.
  • The app closed the connection halfway through the response, for example because the kernel's OOM killer stopped it.
  • The response headers are larger than the proxy's buffer (nginx logs upstream sent too big header).
  • TLS between the proxy and the origin fails: an expired or self-signed certificate on the origin, with the proxy set to verify it.

How to fix it

  • Read the proxy's error log first. nginx writes the exact reason, such as connect() failed (111: Connection refused) or upstream prematurely closed connection.
  • Call the app directly from the proxy's host (curl -v http://127.0.0.1:3000/health). If that fails too, the problem is the app, not the proxy.
  • In a container, make the app listen on 0.0.0.0, not localhost.
  • For large headers (big cookies, long JWTs), raise proxy_buffer_size in nginx.
  • During deploys, drain connections before stopping the old instance, so requests in flight don't end as 502s.

502 or 504?

Both come from the proxy. 502 means the answer it got was broken or the connection was refused; 504 means no answer came in time. A 502 points to a crash or a misconfiguration, a 504 to something slow.

502 or 500?

A 500 is written by your application; a 502 by the proxy in front of it. If the error page looks like nginx's or your CDN's, not your app's, the proxy sent it.

Example

HTTP/1.1 502 Bad Gateway
Server: nginx
Content-Type: text/html

<html>
<head><title>502 Bad Gateway</title></head>
<body>
<center><h1>502 Bad Gateway</h1></center>
<hr><center>nginx</center>
</body>
</html>

Defined in RFC 9110, section 15.6.3.