Skip to main content
Network & HTTP · Developer Error Resolution Lab

Fix Nginx Error: '502 Bad Gateway' (Connection Refused to Upstream)

Resolve reverse proxy gateway errors when Nginx cannot establish a connection with Node.js, Next.js, or Gunicorn backends.

Triggered Error Message:

502 Bad Gateway: [error] connect() failed (111: Connection refused) while connecting to upstream

Customize Solution for Your Environment
# /etc/nginx/sites-available/api.example.com
server {
    listen 80;
    server_name api.example.com;

    location / {
        proxy_pass http://127.0.0.1:3000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_connect_timeout 60s;
        proxy_read_timeout 60s;
    }
}

Root Cause & Mechanism Analysis

Why does this error occur?

The backend server process (e.g. Next.js on port 3000) has crashed or stopped, is listening only on IPv6 (`::1`) while Nginx proxies to IPv4 (`127.0.0.1`), or firewall/SELinux blocks the proxy connection.

Frequently Asked Questions

Why use 127.0.0.1 instead of localhost in Nginx?
`localhost` can resolve to IPv6 `::1` while Node.js might be bound to IPv4 `0.0.0.0`, resulting in immediate connection refusal.
Browse All 35 Guides