Skip to main content
DevOps Guide

What Is 502 Bad Gateway and How to Fix It

A 502 Bad Gateway means a proxy got an invalid response from an upstream. This guide walks through what actually causes it, how to diagnose the real source (not the surface symptom), and the nginx, Cloudflare, AWS, and Vercel specific fixes I reach for when a customer’s site lights up red on the dashboard.

Rai Ansar · Founder of Visual SentinelApril 19, 202614 min read

I have spent the last several years running production infrastructure on bare metal, managing reverse proxies, and more recently building Visual Sentinel (which sits outside people’s infrastructure and watches for this exact class of error). A 502 Bad Gateway is one of the more honest errors HTTP has. Its meaning is precise, the diagnosis path is deterministic, and the fix is almost always upstream of where people first look.

This guide covers seven common failures behind a 502 and how the proxy’s error log and a few quick checks tell them apart, then walks through the fixes for nginx, Cloudflare, AWS ALB and Vercel.

1. What 502 Bad Gateway Actually Means

Per RFC 9110, a 502 response means the server (acting as a gateway) received an invalid response from an upstream server it contacted while trying to fulfill the request. In practice, proxies such as nginx return 502 in three cases:

  • The upstream refused the connection outright (nothing listening).
  • The upstream accepted the connection but closed it before it finished sending the response headers.
  • The upstream sent response headers the gateway could not parse (garbled or oversize headers), or the TLS handshake with it failed.

Whenever you see a 502, there are always at least two servers involved: the “gateway” the browser talks to (nginx, Cloudflare, an AWS ALB, Vercel’s edge, a Kubernetes ingress) and the “upstream” behind it (your application, a microservice, a PHP-FPM pool, a Lambda). The 502 is the gateway’s way of saying “I got your request, I tried to pass it along, and the thing behind me let me down.”

This is why refreshing your browser rarely fixes it. Nothing on the visitor side caused the error; something between the gateway and the origin is broken.

2. The Seven Real Causes of a 502

Every 502 I’ve diagnosed in the last few years has fallen into one of these seven buckets. The order below is roughly how often each one comes up in practice, not alphabetically.

Origin app crashed

The application behind your proxy (Node, PHP-FPM, Gunicorn, Puma) exited and the port stopped listening. Proxy attempts connect, gets refused, returns 502.

Worker pool exhausted

PHP-FPM / Passenger / Unicorn is alive but every worker is busy. New requests wait in the socket’s backlog. Once it is full, nginx cannot connect to a Unix socket and returns 502; a request that waits past the proxy timeout gets a 504 instead.

Firewall or security group

A recently changed iptables rule, UFW rule or AWS security group blocks the proxy from reaching the origin port. A rule that rejects the connection gives a 502 (521 on Cloudflare). One that silently drops it usually ends in a timeout instead (504 on nginx, 522 on Cloudflare).

DNS resolution failed

If the proxy reaches the upstream by hostname, a DNS change can silently break the path: nginx looks the name up when it loads its configuration and keeps the old address until it is reloaded, unless the upstream server has the resolve parameter.

Timeout under load

The origin takes longer than proxy_read_timeout or proxy_connect_timeout. nginx returns 504 for the request that timed out. In an upstream group with more than one server, the timeouts can mark every server unavailable for fail_timeout (10 seconds by default), and requests in that window get a 502 with “no live upstreams” in the error log.

TLS handshake failure

The proxy connects to the origin over TLS and the handshake fails, or the proxy checks the origin certificate and rejects it as expired, self-signed or issued for another name. nginx checks it only when proxy_ssl_verify is on; it is off by default.

Protocol mismatch

The proxy speaks HTTP/2 to an origin that only partly supports it, or the origin sends response headers bigger than the proxy can hold (proxy_buffer_size on nginx, 32 KB in total on an AWS ALB). The proxy rejects the response and returns 502.

3. If You’re a Visitor: What You Can Actually Do

Honest answer: not much. A 502 is a server-side failure and the fix lives on the site owner’s infrastructure. That said, five things are worth trying before you give up or report it:

  1. Hard refresh. Sometimes your browser cached a brief error state. Press Ctrl+Shift+R (Cmd+Shift+R in Chrome on a Mac) to reload the page without your browser’s cached copy.
  2. Wait 30 seconds and try again. Many 502s are short: a service restarting, a brief pause, a deploy in progress.
  3. Try a different network. Switch from WiFi to cellular, or vice versa. If the site loads from mobile data but fails on your home WiFi, your home connection is probably reaching a different CDN edge or server, and that one is failing.
  4. Check if it’s just you. Open our free website status checker (or any “is-it-down” service) to see if the site is returning 502 for everyone or just for your region.
  5. Report it to the site owner. If the site has a status page, check there first. Otherwise an email or a mention on X or Mastodon frequently reaches someone faster than their own monitoring (especially for small sites).

What won’t help: reinstalling your browser, switching DNS servers, or running a virus scan. None of those touch the gateway-to-origin path that broke.

4. If You Run the Site: Diagnose From Upstream Outward

Diagnose 502s from the application outward, not from the edge inward. The cause is usually on the origin host, and every layer above it (proxy, CDN, DNS) is only reporting “I couldn’t get an answer.”

Step 1: Is the origin even running?

SSH into the origin. Does the application process exist? Is the port listening?

# On the origin host
ss -tlnp | grep :3000       # replace 3000 with your app's port
ps aux | grep -i node       # or php-fpm / gunicorn / puma
curl -v http://127.0.0.1:3000/health

If curl localhost fails, the app itself is down or stuck. Start it (or your process manager will) and watch for it to crash again. A crash-loop usually shows in the app’s own logs, not nginx’s.

Step 2: Read the reverse-proxy error log

The access log will tell you a request returned 502, which you already knew. The error log will tell you why. For nginx:

tail -f /var/log/nginx/error.log
# while you reproduce the request in another terminal

curl -v https://yoursite.com/the-failing-path

Look for the word upstream. The line that mentions it also names the failure mode: connection refused, timed out, prematurely closed connection, SSL_do_handshake() failed. That phrase narrows the root cause down to a few of the seven buckets in section 2.

Step 3: Can the proxy actually reach the origin?

From the proxy host (not from your laptop), curl the origin exactly the way nginx would:

# From the proxy host, with the same target nginx uses
curl -v http://<upstream-host>:<port>/
curl -v --resolve app.internal:443:10.0.0.42 https://app.internal/

If this fails, you have a network-level problem between proxy and origin. Iptables, UFW, Docker bridge network, a cloud security group, or a DNS change. On a bare-metal server that runs Docker, I removed UFW on purpose, because UFW and Docker’s own iptables rules conflict in ways that surface as 502s nobody can reproduce.

Step 4: Timeouts and buffers

If the origin is slow but working, nginx returns 504 for the requests that time out, and in an upstream group with several servers the timeouts can turn later requests into 502s (“no live upstreams”). A response header bigger than proxy_buffer_size is a 502 of its own (“upstream sent too big header”). The directives that matter:

# in your nginx server{} or location{} block
proxy_connect_timeout 10s;
proxy_send_timeout    60s;
proxy_read_timeout    60s;
proxy_buffer_size     16k;
proxy_buffers         8 16k;
proxy_busy_buffers_size 32k;

Raising these is a diagnostic tool, not a fix. If your 502 disappears when you bump proxy_read_timeout from 10s to 60s, your real problem is a slow endpoint. Find and fix the slow endpoint, then put the timeout back.

Step 5: Restart the upstream only, not the proxy

If a worker process is stuck, bounce just the origin app. Restarting nginx in front of a broken backend fixes nothing, drops in-flight connections for healthy endpoints, and teaches you the wrong lesson. systemctl restart php-fpm, pm2 restart <app>, docker compose restart app, whichever applies.

Rather have it fixed for you? Acefina, the team behind Visual Sentinel, repairs broken and hacked sites for a fixed price.

5. Platform-Specific 502s

Each proxy, CDN, and PaaS generates 502s with its own phrasing. The error message is a strong hint at the real cause if you know how to read it.

PlatformError MessageReal Cause & Fix
nginxupstream prematurely closed connection while reading response headerThe upstream closed the connection mid-response. Usually a crashed worker, or the upstream’s own time limit killing a slow request (PHP-FPM request_terminate_timeout, Gunicorn --timeout). Check that the upstream process is alive and read its log for the same time.
nginxconnect() failed (111: Connection refused) while connecting to upstreamNothing is listening on the upstream port. The backend process is not running, crashed, or is bound to a different interface. Restart the upstream and confirm the bind address.
nginxupstream timed out (110: Connection timed out) while connectingThe connection to the upstream was not set up within proxy_connect_timeout: a firewall dropping packets, a network problem, or an origin too busy to accept. nginx returns 504 for this request; you see a 502 only once every server in the group is marked unavailable (“no live upstreams”).
CloudflareError 502: Bad gateway (Ray ID shown)Cloudflare shows its branded 502 page when your origin answered with a 502. Check your origin proxy error log for the same time. Blocked Cloudflare IPs show as 521 or 522, not 502.
AWS ALBHTTP 502 with target health failingALB could not reach the target, target returned malformed response, or target closed the connection. Check target health in the ALB console and the target’s keep-alive timeout (must be > ALB’s idle timeout, default 60s).
VercelNO_RESPONSE_FROM_FUNCTION (502)A function finished without returning a response, for example after an error it did not handle. Check the Vercel function logs and fix the function; the edge is fine. FUNCTION_INVOCATION_FAILED, when the function itself fails, is a 500.

Cloudflare specifically: when your origin answers with a 502, Cloudflare shows its own branded error page with the Ray ID. A 502 that Cloudflare itself generates is a plain page without Cloudflare branding. Every response through Cloudflare carries a CF-Ray header, so look at the page instead: a branded page means start at your origin.

6. Diagnosing a 502 with curl

The single most useful command I run when something 502s in production:

curl -v -o /dev/null -w "%{http_code} %{time_total}s %{remote_ip}\n" https://yoursite.com/

Output tells you the HTTP status, total time, and the resolved IP. Compare that IP across runs: if it changes, you’re hitting different CDN edges, and one of them might be misrouting.

To bypass the CDN and hit origin directly (useful for isolating where the 502 really comes from):

# Bypass the CDN, hit origin IP with the correct SNI
curl -v --resolve yoursite.com:443:<ORIGIN_IP> https://yoursite.com/

If the origin answers normally but the CDN returns 502, the CDN-to-origin link is the problem. If both return 502, the origin is the problem and the CDN is innocent. Diagnosis settled in two curl calls.

7. 502 vs 504: Stop Confusing Them

These two are not the same, and telling them apart short-circuits half the diagnosis.

StatusMeaningWhat Happened
502 Bad GatewayInvalid response from upstreamUpstream crashed, refused the connection, or sent a broken response. The gateway got no usable answer.
504 Gateway TimeoutUpstream too slowProxy gave up waiting within the configured timeout, either to connect or for a response.
503 Service UnavailableServer refused on purposeOrigin is up but refusing requests (maintenance mode, rate limited, overloaded with an explicit backoff).

Under sustained load, timeouts can still end in a 502: in an nginx upstream group with several servers, timeouts mark the servers unavailable, and the next requests get a 502 with “no live upstreams” in the error log. If raising proxy_read_timeout makes those 502s stop, the underlying failure was a timeout.

8. How to See 502s Before Your Users Do

Your own origin health check can miss a 502. A curl localhost/health on the origin host can pass while every outside visitor gets a 502, because it skips the proxy-to-origin path, and that path is the part that broke.

The practical way to catch externally visible 502s is to monitor the public user-facing URL from outside your own infrastructure. Visual Sentinel requests your public URL on a schedule from Europe, the US and Asia Pacific (Asia Pacific on paid plans), through the same public path your visitors use. Detection time depends on the plan interval and your alert settings, and when a check fails, we check the site again before an outage alert goes out.

Catching 502s externally

Configured uptime checks from Europe, the US and Asia Pacific request your public URL on the interval included with your plan and identify as VisualSentinelBot/2.0 (to let them through a firewall, allow the check addresses on that page). They record status and timing evidence. A confirmed 502 can then follow the alert routes available on your plan. A failure shorter than the check interval can be missed, which is why the schedule matters.

Start a 10-day free trial of 502 monitoring (no card with a work email)

Beyond monitoring, the big structural fixes that cut 502 rates over time: process managers that restart crashed workers automatically (pm2, systemd with Restart=always, Kubernetes restartPolicy: Always), generous but finite proxy timeouts, keep-alive tuned on both sides of the proxy-origin hop, and an origin SSL certificate that you actually monitor for expiry.

Catch the next 502 before your visitors do
Visual Sentinel Solo at $15 a month checks every 5 minutes, alerts on SSL expiry, and adds visual regression so you also catch pages that load but look broken. Your first site is monitored free for 3 days, screenshot check included, then try Solo free for 10 days (no card with a work email).

9. Frequently Asked Questions

A

Rai Ansar

Founder of Visual Sentinel

Rai Ansar is the founder of Visual Sentinel. He writes about website monitoring, reliability, and catching the failures that uptime checks miss. More from Rai Ansar.

Run a website of your own? Read about keeping watch over your own website, so an alert tells you when something on it breaks.

See your site checked

Add your site and we check its uptime, SSL certificate and screenshots free for 3 days. Then try a paid plan free for 10 days (no card with a work email) or subscribe, from $15 USD a month.

Check my site free