HTTPfy

502 Bad Gateway

A gateway or proxy got an invalid response, or no response, from the upstream server.

502 at a glance

Code
502
Name
Bad Gateway
Class
5xx Server error
Status
IANA-registered standard code
Defined in
RFC 9110, Section 15.6.3
Cacheable by default
No by default. Caches store it only when the response carries explicit freshness (Cache-Control max-age, s-maxage or Expires).

What 502 means

502 Bad Gateway is generated by something in the middle, such as nginx, a load balancer or a CDN, when the server behind it failed: the connection was refused or reset, or the reply was not valid HTTP. The application itself usually never logged the request, so look at the proxy's error log first.

What typically causes a 502

  • nginx: connect() failed (111: Connection refused) while connecting to upstream, meaning the app server (Gunicorn, PHP-FPM, Node) is down or on a different port or socket.
  • nginx: upstream prematurely closed connection, meaning the app crashed or was OOM-killed mid-request.
  • PHP-FPM socket permission errors, or upstream sent too big header (raise fastcgi_buffer_size / proxy_buffer_size).
  • AWS ALB: the target closed the connection, sent a malformed response, or its keep-alive timeout is shorter than the ALB idle timeout (60 s).
  • Kubernetes: pods restarting or failing readiness while ingress still routes to them.
  • Cloudflare shows its own 502/504 page for problems inside Cloudflare; origin problems appear as 520-526 instead.

Fix it on the server

  • Check that the upstream process is running and listening where the proxy expects (ss -ltnp).
  • Set the app server's keep-alive timeout longer than the load balancer's idle timeout (e.g. Node server.keepAliveTimeout = 65000 behind ALB).
  • Look for OOM kills (dmesg, kubectl describe pod) and crash loops.
  • Use graceful shutdown and readiness probes so deploys do not drop in-flight requests.

Fix it as a client or visitor

  • Wait and retry: 502s during deploys or restarts are usually short.
  • If only one URL fails, it may crash the backend; report it with the time.

Headers that go with 502

HeaderRole
ServerTells you which proxy generated it (nginx, awselb/2.0, cloudflare).

Example response

HTTP/1.1 502 Bad Gateway
Server: awselb/2.0
Content-Type: text/html
Content-Length: 122

Opens the HTTP headers tool with your URL filled in; it shows the status line and headers of every redirect hop.