A gateway or proxy got an invalid response from an upstream server.
What 502 Bad Gateway means
502 Bad Gateway means the proxy or load balancer sitting in front of the actual server received a malformed or unexpected response from upstream. Classic causes: upstream crashed mid-response, upstream returned protocol garbage, connection was reset before the response completed. 502 is one of the most common error codes from CDNs (Cloudflare, AWS CloudFront, Fastly) and reverse proxies (Nginx, HAProxy).
When servers should return it: A proxy or CDN returns 502 when it cannot get a valid response from the origin. Origin operators see this as "the proxy is reporting we returned garbage".
Common causes
Origin server crashed mid-request
Origin returned non-HTTP response (raw error text, wrong port)
Connection reset by origin
Origin SSL certificate invalid or expired
Origin closed the connection before sending the full response
Upstream timeout (sometimes manifests as 502 instead of 504)
How to fix 502 Bad Gateway
Check origin server logs for crashes or errors
Verify origin is actually running and reachable on the right port
Check origin certificate validity
For Cloudflare 502s, check the Cloudflare event log and origin response
Retry the request, often transient
Example response
HTTP/2 502
server: cloudflare
content-type: text/html
<html><body>502 Bad Gateway</body></html>
502 = the upstream returned bad data (wrong format, garbled). 504 = the upstream did not respond at all within the timeout.
Why am I getting 502 from Cloudflare?
Cloudflare 502 means Cloudflare reached your origin but the response was invalid. Check origin logs first; the origin is the source of the problem.
Defined in: RFC 9110 · Class:5xx Server Error
More references
For a one-page reference of all HTTP status codes, see the HTTP cheat sheet. For testing API responses, try the API Tester tool. For inspecting responses on the command line, the curl cheat sheet covers the most common flags.