How to Fix nginx 502 Bad Gateway in Under 5 Minutes
You see this in your browser and your stomach drops:
502 Bad Gateway
nginx/1.24.0
Or in your logs:
2024/01/15 03:42:11 [error] 1234#1234: *1 connect() failed (111: Connection refused) while connecting to upstream, client: 203.0.113.5, server: yourdomain.com, request: "GET / HTTP/1.1", upstream: "http://127.0.0.1:3000/", host: "yourdomain.com"
Here's exactly what this means and how to fix it.
What nginx 502 Actually Means
502 is NOT an nginx problem. nginx is fine. The problem is that nginx is trying to forward your request to your backend app (Node, Python, Rails, etc.) — and that app isn't responding.
nginx is the middleman. Your app is dead.
Step 1: Check if Your App is Running
# Check if your Node/Python/whatever process is alive
ps aux | grep node
ps aux | grep python
ps aux | grep gunicorn
# Or check what's listening on your port
ss -tlnp | grep :3000
If nothing is listening on port 3000 (or whatever your upstream is), your app crashed.
Step 2: Read the Actual App Logs
# If using PM2
pm2 logs --lines 50
# If using systemd
journalctl -u your-app-name -n 50 --no-pager
# If using Docker
docker logs your-container-name --tail 50
The real error is always in the app logs, not the nginx logs.
Step 3: Restart and Monitor
# PM2
pm2 restart your-app
# systemd
sudo systemctl restart your-app
# Watch logs as it starts
pm2 logs --lines 0
Step 4: Check nginx Config for Upstream Errors
# Verify your nginx config is correct
sudo nginx -t
# Check upstream address matches where your app runs
grep -r "proxy_pass" /etc/nginx/sites-enabled/
Common mistake: your app runs on port 8080 but nginx points to 3000.
Step 5: Prevent it From Happening Again
Add a health check and auto-restart:
# PM2 auto-restart config (ecosystem.config.js)
module.exports = {
apps: [{
name: 'your-app',
script: 'server.js',
max_restarts: 10,
min_uptime: '10s',
watch: false
}]
}
The Full Diagnostic Checklist
# 1. Is app running?
ss -tlnp | grep :3000
# 2. App logs
pm2 logs --lines 50
# 3. nginx error log
sudo tail -50 /var/log/nginx/error.log
# 4. nginx config valid?
sudo nginx -t
# 5. Disk full? (apps crash silently when disk is full)
df -h
# 6. RAM full?
free -h
Nine times out of ten, the fix is in step 2.
I built ARIA to solve exactly this.
Try it free at step2dev.com — no credit card needed.
Top comments (0)