🔧 Error Fixes
· 1 min read

502 Bad Gateway — How to Fix It


502 Bad Gateway
502 Bad Gateway — nginx
HTTP ERROR 502

A reverse proxy (Nginx, Cloudflare, AWS ALB) tried to forward your request to a backend server, but the backend didn’t respond properly.

Fix 1: Backend Server Is Down

# Check if your app is running
systemctl status myapp
pm2 status
docker ps

# Restart it
systemctl restart myapp
pm2 restart all
docker restart container-name

Fix 2: Wrong Proxy Target

# ❌ Nginx is pointing to the wrong port
location / {
    proxy_pass http://localhost:3000;  # But app runs on 8080
}

# ✅ Match the actual port
location / {
    proxy_pass http://localhost:8080;
}

# Reload Nginx
sudo nginx -t && sudo systemctl reload nginx

Fix 3: Backend Crashed on Startup

# Check the application logs
journalctl -u myapp -n 50
pm2 logs
docker logs container-name

# Common crash causes:
# - Missing environment variables
# - Database connection failed
# - Port already in use
# - Syntax error in code

Fix 4: Timeout — Backend Too Slow

# Nginx — increase proxy timeout
location / {
    proxy_pass http://localhost:3000;
    proxy_connect_timeout 60s;
    proxy_send_timeout 60s;
    proxy_read_timeout 60s;
}

Fix 5: Socket File Missing

# ❌ Unix socket doesn't exist
location / {
    proxy_pass http://unix:/run/myapp.sock;  # 💥 File not found
}

# ✅ Check the socket exists
ls -la /run/myapp.sock

# Restart the app to recreate it
systemctl restart myapp

Fix 6: PHP-FPM / Gunicorn Not Running

# PHP
sudo systemctl status php-fpm
sudo systemctl restart php-fpm

# Python (Gunicorn)
ps aux | grep gunicorn
sudo systemctl restart gunicorn

Debugging

# 1. Is the backend running?
curl -v http://localhost:3000

# 2. Check Nginx error log
tail -20 /var/log/nginx/error.log

# 3. Check Nginx config
sudo nginx -t

# 4. Check if the port is listening
ss -tlnp | grep 3000
📘