Bad Gateway
Server Error (5xx)The 502 Bad Gateway status code indicates that the server, while acting as a gateway or proxy, received an invalid response from an upstream server. This commonly occurs when a reverse proxy (nginx, Apache) cannot communicate with the application server behind it. The issue is between the proxy and the upstream server, not with the client.
What is HTTP 502 Bad Gateway?
HTTP 502 Bad Gateway is a server error (5xx) status code. The 502 Bad Gateway status code indicates that the server, while acting as a gateway or proxy, received an invalid response from an upstream server. This commonly occurs when a reverse proxy (nginx, Apache) cannot communicate with the application server behind it. The issue is between the proxy and the upstream server, not with the client. Common causes include upstream application server crashed or is not running and application server is overloaded and timing out. To fix it, verify the upstream application server is running.
Example Response
HTTP/1.1 502 Bad Gateway Content-Type: text/html <h1>502 Bad Gateway</h1><p>The server received an invalid response from the upstream server.</p>
Common Causes
- • Upstream application server crashed or is not running
- • Application server is overloaded and timing out
- • Incorrect proxy configuration (wrong upstream port/host)
- • Network connectivity issue between proxy and upstream
- • Application server running out of memory
How to Fix
- 1. Verify the upstream application server is running
- 2. Check proxy configuration for correct upstream address and port
- 3. Review upstream server logs for crash or error messages
- 4. Increase proxy timeout settings if the upstream is slow
- 5. Restart the upstream application server
Frequently Asked Questions
What is the difference between 502 and 504?
502 means the proxy received an invalid or malformed response from the upstream. 504 means the proxy did not receive any response within the timeout period. 502 is a bad response; 504 is no response.
Why does nginx return 502?
Nginx returns 502 when it cannot connect to the upstream server (e.g., PHP-FPM, Node.js, Gunicorn) or receives a malformed response. Common fixes: verify the upstream is running, check the socket/port, and increase proxy_read_timeout.
Can CDNs cause 502 errors?
Yes. If a CDN like Cloudflare cannot reach your origin server, it returns 502. Check your origin server's health and ensure the CDN configuration points to the correct origin.