devkult_
tools29converters34

502 Bad Gateway

5xx server error

A proxy or gateway got an invalid response — or none at all — from the upstream server.

502 comes from a middleman. nginx, a load balancer, a CDN or an API gateway forwarded your request to an upstream server, and what came back was broken: a crash mid-response, a closed connection, or bytes that weren't valid HTTP. The proxy is fine; the application behind it isn't.

Class5xx Server Error
Retry?With backoff (idempotent requests only)
Cacheable by defaultNo — only with explicit Cache-Control
Response bodyAllowed
Defined inRFC 9110 §15.6.3 — 502 Bad Gateway
Example response
HTTP/1.1 502 Bad Gateway
Content-Type: application/json
Content-Length: 23

{"error":"Bad Gateway"}

Common causes

  • The application crashed or isn't running — nginx logs connect() failed (111: Connection refused) while connecting to upstream.
  • The app listens on a different port or socket than the proxy expects.
  • The upstream closed the connection early, often an out-of-memory kill or a crash on one particular request.
  • Response headers too large for the proxy's buffers (nginx: upstream sent too big header).
  • Keep-alive races behind load balancers: the app closes idle connections before the balancer does.

How to fix it

  1. Check the app is running and listening where the proxy points (systemctl status, docker ps, ss -ltnp).
  2. Read the proxy's error log — nginx's error.log states the exact upstream failure.
  3. Restart the app and watch its logs for a crash on the failing request.
  4. For 'too big header', raise proxy_buffer_size and proxy_buffers.
  5. Make the app's keep-alive timeout longer than the load balancer's idle timeout (in Node, raise server.keepAliveTimeout above the ALB's 60 s).

Useful here: How to fix 502 Bad Gateway in nginx · 502 vs 503 vs 504 · HTTP Status Checker

Send a 502 from your server

Express
res.status(502).json({ error: "Bad Gateway" });
Next.js route handler
return Response.json({ error: "Bad Gateway" }, { status: 502 });
Flask
return {"error": "Bad Gateway"}, 502
Go net/http
http.Error(w, "Bad Gateway", http.StatusBadGateway)
nginx
return 502;

Check what a URL returns

Print just the status line from the command line, or check a whole list of URLs at once, with their response headers, in the HTTP Status Checker.

curl -sI https://example.com/your-path | head -n 1

Frequently asked questions

Is a 502 a problem with my internet?

No — your request reached the site's proxy. The failure is between that proxy and the site's application. Retry in a minute; if it persists, the site is down.

502 vs 504?

502: the upstream answered badly, or hung up. 504: the upstream didn't answer in time.

Why do I get intermittent 502s behind an AWS load balancer?

Often a keep-alive race: the app closes an idle connection just as the load balancer reuses it. Make the app's keep-alive timeout longer than the balancer's idle timeout.

Related status codes