502 Bad Gateway: what it means, why it happens and how to fix it

, Founder · Updated

A 502 Bad Gateway error means a server acting as a gateway or proxy got an invalid response from the server behind it. The page you asked for exists, but the hop between the proxy (nginx, a load balancer, a CDN such as Cloudflare) and the application failed. To fix it, find which hop broke, then restart, reconfigure or resize the upstream.

The HTTP specification defines it this way: 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). "Inbound server" is the application server, PHP-FPM pool, Node process or origin that sits behind the proxy.

502 vs 503 vs 504

Three 5xx codes look alike in a browser and mean different things:

CodeWho sends itWhat went wrong
502 Bad GatewayA proxy or gatewayThe upstream server replied, but the reply was invalid, or the connection failed
503 Service UnavailableThe server handling the requestIt is temporarily unable to handle the request, from overload or maintenance
504 Gateway TimeoutA proxy or gatewayThe upstream server did not reply in time

RFC 9110 defines 504 as a gateway or proxy that "did not receive a timely response from an upstream server". A 503 comes from a server "currently unable to handle the request due to a temporary overload or scheduled maintenance" (RFC 9110, section 15.6). In practice the line between 502 and 504 is blurry, because each proxy decides which code to send when a connection drops. If you see both, treat them as the same incident.

Common causes

  • The application is down. The Node, Python or PHP-FPM process crashed, was killed for using too much memory, or is still restarting after a deploy. The proxy connects to a port where nothing is listening.
  • Wrong upstream address. The proxy points at the wrong port, socket path or container name, often after a config change.
  • The upstream closes the connection early. The app throws an unhandled error and ends the request without sending a response.
  • Oversized response headers. Large cookies or many Set-Cookie headers overflow the proxy's header buffer.
  • DNS or network between the CDN and the origin. The CDN cannot reach the origin, or the origin firewall blocks the CDN's IP ranges.
  • Overload. Every worker is busy, so new connections are refused or reset.

How to diagnose a 502, step by step

  1. Confirm it from outside. Run curl -I https://example.com/page and note the status and the server header. A header such as server: cloudflare tells you which layer answered.

  2. Request the origin directly. Bypass the CDN or load balancer and call the application server by its IP or internal hostname:

    curl -I http://127.0.0.1:3000/page
    curl -I --resolve example.com:443:203.0.113.10 https://example.com/page
    

    If the origin answers 200 directly, the problem is in the proxy layer. If the origin fails too, the problem is the application.

  3. Read the proxy's error log. nginx logs the reason for every 502, such as connect() failed (111: Connection refused) or upstream sent too big header.

  4. Read the application's log for the same timestamp. Look for crashes, out-of-memory kills, restarts and unhandled exceptions.

  5. Check whether it follows load. If 502s appear only at peak traffic, the cause is capacity, not configuration.

Fixes by platform

nginx as a reverse proxy

Match the error log message to the fix:

nginx error logLikely causeFix
connect() failed (111: Connection refused)Nothing listening on the upstream addressStart the app, or correct proxy_pass / fastcgi_pass
upstream prematurely closed connectionThe app crashed mid-requestFix the exception in the app log
upstream sent too big headerHeaders larger than the bufferRaise proxy_buffer_size (or fastcgi_buffer_size)
upstream timed outSlow upstreamSpeed up the handler, or raise proxy_read_timeout

nginx's defaults are a 60-second proxy_connect_timeout and proxy_read_timeout, and a proxy_buffer_size of one memory page, "either 4K or 8K, depending on a platform" (nginx proxy module docs). Raise a timeout only after you know why the upstream is slow. A longer timeout keeps workers busy and can turn a few 502s into an outage.

Cloudflare

Cloudflare's guidance is counterintuitive. If the error page carries Cloudflare's branding, the 502 or 504 came from your origin server. If the page is plain and unbranded, Cloudflare generated it (Cloudflare docs).

  • Branded page: check that the origin answers for the hostname in the failing URL, and look for overload, crashes or network failures on the origin.
  • Unbranded page: Cloudflare points to compression problems, such as gzip content sent with a wrong content-length. Try disabling compression at the origin. For errors that persist, contact Cloudflare Support with the failing URL, the timestamp and the output of /cdn-cgi/trace on your domain.

Cloudflare also notes that a 5xx cause "is not always found in the origin server's error logs", so check any load balancers, caches or firewalls between Cloudflare and the origin (Cloudflare 5xx errors).

Vercel and other serverless hosts

On Vercel, a 502 with the code NO_RESPONSE_FROM_FUNCTION means a function finished without returning a response. Vercel lists a global uncaught exception, an unhandled promise rejection, or a deployment with a syntax error as causes (Vercel docs). Make sure every code path returns a response, including error paths, and reproduce the request while the runtime logs are open. A function that runs too long returns 504 FUNCTION_INVOCATION_TIMEOUT instead (Vercel docs).

What visitors can do

A 502 is a server problem, so a visitor can only work around it. Reload after a minute, because many 502s come from restarts that finish quickly. If one page fails and others load, the site's owner needs to know the exact URL. Clearing cookies helps in one case: when oversized cookies are what overflow the proxy's header buffer.

How 502 errors affect Google Search

Google treats 502 like any other server error. Its documentation says "5xx and 429 server errors prompt Google's crawlers to temporarily slow down with crawling". Content from 5xx responses is ignored, and indexed URLs are kept at first but "eventually dropped" (Google Search Central). Google also states that its indexing pipeline removes URLs that persistently return a server error, and that crawling speeds back up gradually once the server returns 2xx again.

So a 502 that lasts minutes costs little. One that lasts days on important pages can remove them from search. After a fix, confirm that every version of your homepage resolves cleanly to a 200 with the redirect checker, which follows each hop and shows the status code at the end.

Questions

Is a 502 Bad Gateway my fault or the website's?
Almost always the website's. A 502 is sent by a proxy, load balancer or CDN that could not get a valid response from the server behind it. As a visitor you can reload after a minute or try another network, but the fix is on the server side.
What is the difference between 502, 503 and 504?
502 means the proxy got an invalid response from the upstream server. 504 means the proxy got no response in time. 503 means the server answering you is temporarily unable to handle the request, usually because of overload or maintenance.
Does a 502 error hurt SEO?
A short one does not. Google's crawlers slow down when they see 5xx errors and ignore the content of those responses. Indexed URLs are kept at first, but URLs that keep returning a server error are eventually removed from the index.
Why does a 502 come and go?
Intermittent 502s usually mean the upstream process is restarting, running out of memory, or hitting a timeout under load. Compare the times of the errors with your application restarts and traffic peaks in the logs.
How do I fix a 502 on nginx?
Read the nginx error log first. 'Connection refused' means nothing is listening on the upstream address, so start the app or fix the port. 'Upstream sent too big header' means the response headers did not fit in proxy_buffer_size, so raise it.

Related

See where you stand in Google and AI answers

Starter is $19 a month for one site, with a 14-day free trial and no card to start.