nginx returns `502 Bad Gateway` and the error log says `connect() failed (111: Connection refused) while connecting to upstream`.
BeginnerTroubleshootingLoad balancers and reverse proxies
Answer
Likely causes → nginx reached the upstream host but nothing accepted on that port: the app is down or restarting, listens on a different port, or is bound to 127.0.0.1 while nginx connects via another IP (or vice versa, e.g. localhost resolving to ::1 while the app listens on IPv4 only).
Diagnose →
sudo tail -n 20 /var/log/nginx/error.log # shows the exact upstream address
sudo ss -ltnp | grep <port>
curl -v http://<upstream-address>/health # from the nginx host
Fix → Start/fix the app, or point proxy_pass at the address it actually listens on (use 127.0.0.1 instead of localhost to avoid the IPv6 surprise).
Prevent → Health checks with retries (max_fails, fail_timeout), process supervision, and readiness checks before nginx sends traffic.
More on Load balancers and reverse proxies
nginx returns `504 Gateway Time-out` with `upstream timed out (110: Connection timed out) while reading response header from upstream`.BeginnerAn ALB target group shows all targets `unhealthy` with `Health checks failed with these codes: [404]`.BeginnerAn ALB returns sporadic `502`s, and access logs show `elb_status_code=502` with `target_status_code=-`. Load is low.Intermediatenginx logs `upstream prematurely closed connection while reading response header from upstream`.Intermediatenginx error log shows `no live upstreams while connecting to upstream` and every request gets 502.IntermediateAn NLB shows all targets healthy, but clients from the internet time out connecting through it.Intermediate