502 Bad Gateway: what it means and how to fix it
By the ProxyOnly team · 16 Nov 2026 · 6 min read
A 502 means a server in the middle could not use the reply it got from the server behind it. What causes it, how to fix it, and a demo you can run.
A 502 Bad Gateway means that a server in the middle of a request, acting as a gateway or proxy, received an invalid response from the server behind it. Your browser reached the first server without trouble. The failure is further along the chain, and the first server is the one reporting it. RFC 9110 defines the status code in these terms.
The error is usually temporary, and it is usually not caused by anything on your side. This article explains where a 502 comes from, what to try as a visitor, how to find the cause if you run the site, and how scripts should react.
Where a 502 comes from
Most websites do not answer a request with one server. The request passes through several, and each can fail on its own:
- Your browser or script sends the request.
- A CDN, load balancer or reverse proxy receives it. Cloudflare, nginx and a cloud load balancer are common examples.
- The application server, such as a PHP, Node.js or Python process, builds the page.
The server in the middle returns the 502 when what comes back from the application is not something it can pass on. That is different from the application returning an error itself. A 500 means the application ran and failed. A 502 means the middle server could not get a usable answer from it. Forward proxy vs reverse proxy explains how these middle servers work.
Three 5xx codes involve the middle server, and they are easy to mix up:
502 Bad Gateway: the reply from behind was invalid. In practice gateways also use it when they cannot connect at all.503 Service Unavailable: a server is overloaded or down for maintenance. See 503 Service Unavailable.504 Gateway Timeout: the reply from behind took too long. See 504 Gateway Timeout.
What causes a 502
- The application is down, crashed or restarting. This is the most common cause, and a deployment produces a short burst of 502s.
- The gateway is set up with the wrong address, port or socket for the application.
- A firewall or security group blocks the gateway from reaching the application.
- The application accepts the connection and then closes or resets it, for example because it ran out of memory halfway through a request.
- The application sends something that is not valid HTTP, or response headers larger than the gateway's buffer.
- The gateway speaks HTTPS to a port that serves plain HTTP, or the other way round.
- The gateway cannot look up the application's host name.
See it happen
To see these failures side by side we wrote a gateway in 25 lines of Python and ran it in front of a second small server that we made misbehave in different ways. The gateway waits up to two seconds for the application and picks a status for each failure.
import http.client, http.server, socket
UPSTREAM = ("127.0.0.1", 9001)
TIMEOUT = 2
class Gateway(http.server.BaseHTTPRequestHandler):
def do_GET(self):
try:
conn = http.client.HTTPConnection(*UPSTREAM, timeout=TIMEOUT)
conn.request("GET", self.path)
resp = conn.getresponse()
body = resp.read()
except socket.timeout:
return self.fail(504, "Gateway Timeout")
except (OSError, http.client.HTTPException):
return self.fail(502, "Bad Gateway")
self.send_response(resp.status)
for name, value in resp.getheaders():
if name.lower() not in ("transfer-encoding", "connection", "date", "server"):
self.send_header(name, value)
self.end_headers()
self.wfile.write(body)
def fail(self, code, text):
self.send_response(code, text)
self.end_headers()
self.wfile.write(text.encode())
http.server.ThreadingHTTPServer(("127.0.0.1", 9000), Gateway).serve_forever()The application behind it answers /ok immediately. Its /garbage path writes bytes that are not HTTP and hangs up, /hangup closes the connection without writing anything, /slow waits five seconds, and /maintenance returns a 503 with a Retry-After header. We requested each path through the gateway with curl -s -o /dev/null -w "/$path -> %{http_code} in %{time_total}s\n", first with the application stopped and then with it running. This is what we saw:
--- upstream not running
/ok -> 502 in 0.001964s
--- upstream running
/ok -> 200 in 0.008060s
/garbage -> 502 in 0.004094s
/hangup -> 502 in 0.001693s
/slow -> 504 in 2.006378s
/maintenance -> 503 in 0.007838sThree different failures, a stopped application, a reply that is not HTTP and a dropped connection, all came out as the same 502. From the outside they cannot be told apart, which is why the gateway's log matters more than the status code. The slow application produced a 504 after exactly the two seconds the gateway was willing to wait. The 503 was the application's own answer, passed through unchanged.
If you are a visitor
- Reload after a minute. Many 502s last only seconds, for example while a site restarts after an update.
- Try another device on another network, such as a phone with Wi-Fi turned off, to check that the problem is not on your side. How to check if a website is down shows how.
- If you use a VPN or proxy, turn it off and try again. The gateway that failed may be the proxy's. See 502 Bad Gateway through a proxy.
- Clearing cookies and cache rarely helps, because the failure happens on the server side.
- If the error lasts, tell the site's owner. Include the time, the page and any request or Ray ID printed on the error page.
If you run the site
Work from the gateway towards the application. Start with the gateway's error log, because the line it wrote says which failure happened. nginx writes lines like these:
connect() failed (111: Connection refused) while connecting to upstream: nothing is listening at that address, so the application is down or the address is wrong.upstream prematurely closed connection while reading response header from upstream: the application took the request and dropped it, often by crashing.upstream sent too big header while reading response header from upstream: the response headers did not fit the buffer. Raiseproxy_buffer_size, or send fewer and smaller cookies.no live upstreams while connecting to upstream: every server in the group is currently marked as failed.
Then work through the rest:
- Ask the application directly from the gateway's own host, skipping the gateway, for example
curl -i http://127.0.0.1:3000/with your own port. If that fails too, the problem is the application. - Check that the application process is running and listening on the port or socket the gateway uses.
- Look for memory kills. On Linux the kernel log shows lines such as "Out of memory: Killed process" when a process is stopped for using too much memory.
- Compare the address, port and protocol in the gateway configuration with what the application really uses.
- Check the firewalls and security groups between the two servers.
- If 502s appear in short bursts after each deployment, restart application instances one at a time, or use health checks so the gateway stops sending requests to an instance that is still starting.
Behind Cloudflare
Cloudflare's documentation on 502 and 504 errors says that a Cloudflare-branded 502 or 504 most often comes from the origin web server, and sometimes from Cloudflare itself. Check your origin first. The 520 to 526 errors are Cloudflare's more specific reports about its connection to your origin. See Cloudflare error 520 for what each one means.
If a script gets a 502
Treat it as temporary. For requests that are safe to repeat, such as plain page fetches, retry a few times with growing waits, and give up after a fixed number of attempts. Do not retry in a tight loop, and do not resend a request that changes data, such as a payment, before checking whether the first attempt went through. The article on 503 Service Unavailable includes a retry setup that also respects Retry-After.
If the 502 only appears when your traffic goes through a proxy, the failing gateway may be the proxy or the route behind it. Our page on 502 Bad Gateway through a proxy and the guide to fixing common proxy errors cover that case. For the other two errors that scripts meet most often, see 403 Forbidden and 429 Too Many Requests.
Try it yourself
Create an account, add funds from US$1 and order a proxy in the country you need.
Keep reading
25 Nov 2026 · Troubleshooting
409 Conflict explained
A 409 means your request conflicts with the resource's current state. The duplicate case, the lost update case, and how ETag and If-Match prevent both.
25 Nov 2026 · Troubleshooting
405 Method Not Allowed explained
A 405 means the URL exists but rejects your HTTP method. The Allow header says which methods work, and most 405s come from one of five causes.