502 Bad Gateway
Server Error - Invalid response from upstream server
HTTP 502 Bad Gateway
What It Means
The HTTP 502 Bad Gateway error occurs when a server acting as a gateway or proxy received an invalid response from the upstream server. The problem is between your reverse proxy (like Nginx) and your application server.
Request Flow
User → Nginx (proxy) → App Server ❌ → 502
Common Causes
- App server crashed: Your Node/Python/PHP process died
- Not listening: App isn't bound to the expected port
- Firewall: Connection blocked between proxy and app
- Socket mismatch: Wrong Unix socket path configured
- Container stopped: Docker container failed to start
- Overloaded: App server can't handle request volume
How to Debug
# 1. Is the app server running?
ps aux | grep node
systemctl status myapp
# 2. Is it listening on the right port?
ss -tlnp | grep 3000
netstat -tlnp | grep 3000
# 3. Can you reach it directly?
curl http://localhost:3000/health
# 4. Check Nginx error logs
tail -f /var/log/nginx/error.log
# 5. Check app logs
journalctl -u myapp -f
Nginx Configuration Check
# Verify upstream matches your app
upstream app {
server 127.0.0.1:3000; # Must match app's actual port
}
server {
location / {
proxy_pass http://app;
proxy_connect_timeout 60s;
proxy_read_timeout 60s;
}
}
502 vs Other 5xx Errors
| Code | Problem Location |
|---|---|
| 500 | App server itself crashed |
| 502 | Proxy → App connection failed |
| 503 | Server intentionally unavailable |
| 504 | App took too long to respond |
Prevention
- Use process manager (PM2, systemd) to auto-restart crashed apps
- Configure health checks in your load balancer
- Monitor app server directly, not just the proxy
- Set up alerts for process crashes
- Increase worker processes for high traffic