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.
502 Bad Gateway: [error] connect() failed (111: Connection refused) while connecting to upstream
# /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?
Related Developer Error Solutions
Browse All 35 GuidesNginx 413 Request Entity Too Large
Increase Nginx client_max_body_size and framework upload limits to allow large file and payload transfers.
CORS 'Access-Control-Allow-Origin' Missing
Resolve browser cross-origin resource sharing errors by configuring backend HTTP headers and handling preflight OPTIONS requests.
Docker: Bind for 0.0.0.0:Port Failed
Identify and terminate conflicting host processes or adjust Docker port mapping to resolve port bind collisions.