Skip to content

Troubleshooting guide

502 Bad Gateway: causes and how to fix it

A 502 means a proxy in front of your app received an invalid response, or none at all, from the server behind it. The fix depends on which hop failed.

4 min read10 sectionsUpdated

On this page

Key points

  • 502 comes from a proxy: Nginx, a load balancer, an API gateway or a CDN, never from the browser.
  • The upstream is the problem: crashed, not listening, closing connections early or sending a malformed response.
  • Check the proxy’s error log first; it usually names the upstream and the reason.
  • A 502 on a monitor is an outage: alert on it from several regions.

What 502 actually means

HTTP 502 Bad Gateway is returned by a server acting as a gateway or proxy when the upstream server it forwarded the request to gave an invalid response. In a typical stack the request goes browser → CDN → load balancer → Nginx → application. Any proxy along that chain can return the 502, and the problem is in the hop behind it.

CodeMeaningTypical cause
502 Bad GatewayUpstream gave an invalid response or closed the connectionApp crashed, wrong port, connection reset
503 Service UnavailableServer cannot handle the request right nowOverloaded, maintenance, no healthy backends
504 Gateway TimeoutUpstream did not answer in timeSlow query, hung request, timeout too short

Common causes, most likely first

  1. The application is down or restarting. A crash, an out-of-memory kill or a deploy in progress leaves nothing listening.
  2. Wrong upstream address or port. The proxy points at 127.0.0.1:3000 but the app now listens on 8080, or on a Unix socket with the wrong permissions.
  3. The app closes connections early. Keep-alive timeouts on the app shorter than the proxy's, so the proxy reuses a connection the app already closed.
  4. Response headers too large. Big cookies or many Set-Cookie headers exceed the proxy's buffer (upstream sent too big header in Nginx).
  5. PHP-FPM or worker pool exhausted or crashed.
  6. TLS problems between proxy and upstream, such as a wrong SNI or an expired internal certificate.
  7. CDN cannot reach your origin: firewall rules, an origin IP change or an expired origin certificate.

Find the failing hop

Start where the 502 is generated and work backwards:

bash
# 1. Which layer answered? Look at the Server header and the body
curl -sv https://example.com/ -o /dev/null 2>&1 | grep -iE '^< (HTTP|server|via|cf-ray)'

# 2. Nginx: the error log names the upstream and the reason
sudo tail -n 50 /var/log/nginx/error.log
#   connect() failed (111: Connection refused) while connecting to upstream   -> app not listening
#   upstream prematurely closed connection                                   -> app crashed or closed early
#   upstream sent too big header                                             -> raise proxy_buffer_size

# 3. Is the app listening where Nginx expects?
sudo ss -ltnp | grep -E ':3000|:8080'

# 4. Call the app directly, bypassing the proxy
curl -sv http://127.0.0.1:3000/health

# 5. Did it crash or get OOM-killed?
journalctl -u myapp --since "30 min ago" | tail -n 50
dmesg -T | grep -i -E 'killed process|out of memory'

Fixes by cause

CauseFix
App not runningRestart it, then find out why it stopped (logs, OOM, crash on boot)
Wrong port or socketAlign the proxy upstream with the app’s listen address; check socket permissions
Keep-alive mismatchMake the app’s keep-alive timeout longer than the proxy’s idle timeout
Headers too bigIn Nginx raise proxy_buffer_size and proxy_buffers, or shrink cookies
Worker pool exhaustedIncrease workers, fix slow requests holding them, add instances
CDN cannot reach originAllow the CDN’s IP ranges, fix the origin certificate, check DNS
nginx.confplaintext
upstream app {
    server 127.0.0.1:3000;
    keepalive 32;
}
server {
    location / {
        proxy_pass http://app;
        proxy_http_version 1.1;
        proxy_set_header Connection "";
        proxy_buffer_size 16k;
        proxy_buffers 8 16k;
    }
}

Catching it next time

  • Uptime checks from several regions on your main pages and API, alerting on any 5xx after two consecutive failures. See how to monitor website uptime.
  • A health endpoint that the load balancer uses, so broken instances are taken out of rotation before users hit them.
  • Memory alerts on the app process, since OOM kills are a frequent root cause.
  • Deploy markers on your charts, because 502s often start with a release.

VitalRix uptime monitoring checks HTTP status and content every minute, and an incident links to the traces and logs from the same minutes, so you can see whether the app crashed or never received the request. An Nginx check also watches active and dropped connections.

Frequently asked questions

Is a 502 error my fault or the website’s?

As a visitor, it is almost never your fault. It is a server-side problem between the site’s proxy and its application. Reloading after a minute often works if the app was restarting.

Can a 502 be caused by the CDN?

Yes. If the CDN cannot connect to your origin, or the origin returns something invalid, the CDN shows its own 502 page. Its error page or response headers usually say so.

Why do I get 502 only sometimes?

Intermittent 502s usually mean one unhealthy instance behind a load balancer, keep-alive timeout mismatches, or workers being recycled. Look for a pattern by instance and time.

Check it now, free

Watch your own site and services with VitalRix

Uptime checks, APM, logs, real-user monitoring, alerts and status pages in one place. Every product has a free tier and no credit card is needed.