Skip to content

502 Bad Gateway

A server acting as a gateway or proxy got an invalid response, or no usable response, from the upstream server behind it.

What 502 Bad Gateway means

Most sites have a reverse proxy, load balancer or CDN (nginx, Cloudflare, a cloud load balancer) in front of the app server. A 502 means that front layer contacted the app and got back garbage, a reset connection or nothing at all.

With 504 the upstream was reachable but too slow, and with 503 the server reports itself unavailable. With 502 the upstream is usually down, crashed or misconfigured.

Common causes

  • The app server (Node.js, PHP-FPM, Gunicorn) has crashed, is restarting or is not running.
  • The proxy points at the wrong host, port or socket, or a firewall blocks the connection.
  • The upstream sent a malformed response, or headers bigger than the proxy's buffer.
  • DNS or SSL problems between a CDN and the origin server.

How to fix 502 Bad Gateway

  1. As a visitor, wait a moment and reload. Short 502s often happen during deploys.
  2. Check the app process is running and listening where the proxy expects; curl it directly from the proxy host.
  3. Read the proxy error log. nginx logs lines such as connect() failed (111: Connection refused) or upstream sent too big header.
  4. Check app logs for crashes or out-of-memory kills, and raise proxy_buffer_size if upstream headers are too large.

Example response

HTTP/1.1 502 Bad Gateway
Content-Type: text/plain; charset=utf-8

502 Bad Gateway

How to check for a 502 response

cURL

# Print only the status code
curl -s -o /dev/null -w "%{http_code}\n" https://example.com/

JavaScript (Node.js)

const res = await fetch("https://example.com/");
if (res.status === 502) {
  console.log(res.status, res.statusText);
}

Python

import requests

res = requests.get("https://example.com/")
if res.status_code == 502:
    print(res.status_code, res.reason)

Go

res, err := http.Get("https://example.com/")
if err != nil {
	log.Fatal(err)
}
defer res.Body.Close()
if res.StatusCode == 502 {
	fmt.Println(res.Status)
}

Specification

502 Bad Gateway is defined in RFC 9110, section 15.6.3.

  • 504

    Gateway Timeout

    A gateway or proxy waited too long for a response from the upstream server and gave up before the page was ready.

  • 503

    Service Unavailable

    The server cannot handle the request right now, usually because it is overloaded or down for maintenance. Try again later.

  • 500

    Internal Server Error

    Something went wrong on the server and it could not complete the request. It is a generic error and not your fault.

← all 63 HTTP status codes

Type to search posts, tools and projects.

Keyboard shortcuts

Search+Kor/
Go to homegthenh
Go to bloggthenb
Go to projectsgthenp
Go to timelinegthent
Show this help?
Close search or helpesc