Interview Prep/Networking/Load balancers and reverse proxies

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.

All Networking questions Roadmap: Networking for DevOps

More on Load balancers and reverse proxies