error http
HTTP 502 Bad Gateway
Understanding HTTP 502 Bad Gateway - the server acting as a gateway received an invalid response from the upstream server.
What It Means
HTTP 502 Bad Gateway indicates that the server, while acting as a gateway or proxy, received an invalid response from an upstream server it accessed while attempting to fulfill the request.
In practice, this usually means Nginx (or another reverse proxy) tried to connect to your application server (Node.js, Python, PHP-FPM) and either got a malformed response or the connection was refused.
Common Causes
- Application server has crashed or is not running
- Application server is listening on a different port than the proxy expects
- PHP-FPM, Gunicorn, or Node.js process is not running
- Upstream server returned a malformed HTTP response
- Socket file (.sock) does not exist or has wrong permissions
- Application server ran out of memory and was killed (OOMKilled)
- SSL/TLS certificate issues between proxy and upstream
How to Fix
Check if your application is running
# Check if the process is running
ps aux | grep node
ps aux | grep gunicorn
ps aux | grep php-fpm
# Check if the port is being listened on
ss -tlnp | grep :3000
# Restart the application
sudo systemctl restart your-app
pm2 restart all
# Check application logs
journalctl -u your-app --since "5 minutes ago"
docker logs <container> --tail 50
Verify Nginx upstream configuration
# Check that upstream matches your app's port/socket
upstream backend {
server 127.0.0.1:3000; # Must match your app's port
# or
server unix:/var/run/app.sock; # Must match your app's socket
}
server {
location / {
proxy_pass http://backend;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
}
Increase proxy timeouts
# Sometimes 502 occurs because the upstream is slow to respond
location / {
proxy_pass http://backend;
proxy_connect_timeout 60s;
proxy_send_timeout 60s;
proxy_read_timeout 60s;
}
Fix PHP-FPM issues
# Check PHP-FPM status
sudo systemctl status php8.2-fpm
# Check socket exists
ls -la /var/run/php/php8.2-fpm.sock
# Restart PHP-FPM
sudo systemctl restart php8.2-fpm
Docker-specific fixes
# Check container health
docker ps --filter "status=running"
# Check if the app inside the container is listening
docker exec <container> curl -s http://localhost:3000/health
# Check for OOMKilled
docker inspect <container> | grep -i oom
Increase buffer sizes
# If the upstream response is too large for the default buffer
proxy_buffer_size 128k;
proxy_buffers 4 256k;
proxy_busy_buffers_size 256k;