DEV Community

Sanghun Yun
Sanghun Yun

Posted on Edited on Originally published at gearflowlab.com

How to Fix Nginx 502 Bad Gateway with Docker (Resolving Upstream Connection Refused)

When a containerized Nginx reverse proxy returns HTTP 502 Bad Gateway with connect() failed (111: Connection refused) while connecting to upstream, guessing at timeout directives wastes hours. In Docker Compose stacks, the failure traces to container namespace isolation or stale bridge IP caching rather than slow responses.

Lab Reproduction Findings (Docker Engine 27.3.1 + nginx:1.27.3)

  • Loopback Namespace Mismatch: Writing proxy_pass http://127.0.0.1:3000; inside containerized Nginx dials Nginx's own loopback interface, while binding the backend app to 127.0.0.1 instead of 0.0.0.0 refuses sibling bridge traffic.
  • Stale Container IP Cache: Static proxy_pass http://backend-api:3000; resolves Docker DNS once at startup; recreating backend-api assigns a new 172.18.0.x IP while Nginx keeps dialing the dead address.
  • Dynamic DNS Fix: Pairing resolver 127.0.0.11 valid=10s ipv6=off; with a $upstream variable forces automatic IP re-resolution without reloads.

Full nginx.conf, Compose Stack & Interactive Config Generator

Top comments (0)