502 Bad Gateway
The proxy server received an invalid response from the upstream server.
Usually happens because:
- ☑ Upstream application process (Node.js/PM2/PHP-FPM) crashed
- ☑ Reverse proxy (Nginx) configuration listening
- ☑ Firewalls blocking connection ports between
🔍 Quick Checklist:
Meaning
The HTTP 502 Bad Gateway server error status code indicates that the server, while acting as a gateway or proxy, received an invalid response from the upstream server it accessed in attempting to fulfill the request.
Root Causes
- Upstream application process (Node.js/PM2/PHP-FPM) crashed or is not running.
- Reverse proxy (Nginx) configuration listening to wrong backend port.
- Firewalls blocking connection ports between proxy and app servers.
| Cause | Frequency |
|---|---|
| Upstream application process (Node.js/PM2/PHP-FPM) crashed | ⭐⭐⭐⭐⭐ |
| Reverse proxy (Nginx) configuration listening | ⭐⭐⭐⭐ |
| Firewalls blocking connection ports between | ⭐⭐⭐ |
Common Mistakes
- Assuming 502 is a client browser error (502 is strictly a server-to-server connection error).
- Leaving port firewalls closed on private VPC networks, blocking proxies from hitting application clusters.
How to Fix
Framework-Specific Examples
Simulating gateway failures in Express.
app.get('/gateway', (req, res) => {
res.status(502).send('Invalid upstream response');
});Server Configuration Examples
Enforcing Nginx error page redirects for upstream server crashes.
error_page 502 /502.html;
location = /502.html {
root /usr/share/nginx/html;
}Prevention
- Configure automated process managers (PM2, systemd, or Kubernetes) to restart crashed applications automatically.
- Monitor proxy error logs constantly.
Frequently Asked Questions (FAQ)
Q: What is the most common cause of a 502 Bad Gateway?
The backend application server (like Node.js or PHP-FPM) is shut down, crashed, or not listening on the port configured in your reverse proxy (like Nginx or Apache).
Q: How does 502 differ from 504?
502 Bad Gateway means the upstream server replied with an invalid response or reset the connection immediately. 504 Gateway Timeout means the upstream server accepted the connection but took too long to return any response.
Q: Can Cloudflare trigger 502 Bad Gateway?
Yes. If Cloudflare successfully routes traffic to your server, but your Nginx proxy or origin server is offline, Cloudflare returns a '502 Bad Gateway' error screen.
Q: Is 502 Bad Gateway cached by browsers?
No. The 502 status code represents a temporary connection failure and is never cached by browsers.