Nginx 502 Bad Gateway in Docker: 127.0.0.1 & DNS Fix

16 min readBy Yun Sanghun (M. Yun)

When an Nginx reverse proxy container returns HTTP/1.1 502 Bad Gateway with connect() failed (111: Connection refused) while connecting to upstream in a Docker Compose stack, the failure almost always traces back to one of four container networking mistakes: the backend application is listening on its private loopback interface (127.0.0.1) instead of 0.0.0.0, the containers are running on Docker's legacy default bridge network where embedded DNS is disabled, Nginx has cached a stale upstream container IP address after a rolling redeploy instead of re-querying Docker's internal DNS server at 127.0.0.11, or Nginx started accepting traffic before the upstream container finished opening its TCP socket. In this empirical troubleshooting guide, I reproduce each failure mode on Docker Engine 27.3.1 with Nginx 1.27.3 and verify the exact configuration fixes.

Nginx Error Log Signature Root Cause Domain Container Diagnostic Command Permanent Production Fix
connect() failed (111: Connection refused) immediately on boot 1. Loopback Socket Binding (127.0.0.1) docker exec backend-api netstat -tln shows 127.0.0.1:3000 LISTEN Bind backend server to 0.0.0.0:3000 (--host 0.0.0.0)
[emerg] host not found in upstream "backend-api" at startup 2. Default Bridge / Separate Subnets docker inspect shows default bridge or mismatched Compose networks Attach both services to a shared user-defined bridge network
connect() failed (111: Connection refused) after docker compose up -d 3. Cached Stale Container IP docker exec reverse-proxy getent hosts backend-api shows a newer IP than Nginx logs Configure resolver 127.0.0.11 valid=5s ipv6=off; with a $variable in proxy_pass
502 Bad Gateway only during the first 5–15 seconds of cold startup 4. Cold-Start Port Readiness Race docker compose logs backend-api shows migrations still running when Nginx starts Add a container healthcheck and gate Nginx with condition: service_healthy

Quick Fix (TL;DR: Four-Step Docker Nginx 502 Remediation):

  1. Inspect the Nginx error log for POSIX errno 111: Run docker logs <nginx_container> --tail 50 | grep -iE "502|error|refused" to confirm whether Nginx is hitting connect() failed (111: Connection refused) while connecting to upstream.
  2. Bind the backend application to 0.0.0.0: Never bind containerized Node.js, FastAPI, Gunicorn, or Go servers to 127.0.0.1 or localhost. Always listen on 0.0.0.0 so the container's eth0 bridge interface accepts incoming packets.
  3. Use Docker's embedded DNS (127.0.0.11) with a variable in proxy_pass: Add resolver 127.0.0.11 valid=5s ipv6=off;, set $backend_service "http://backend-api:3000";, and proxy_pass $backend_service; inside your location block so Nginx re-resolves container IP changes automatically.
  4. Share a user-defined bridge network: Attach both Nginx and the backend container to an explicit bridge network in docker-compose.yml.

Tested on: Windows 11 Pro 23H2 | WSL 2 Kernel 6.6.87.2-microsoft-standard-WSL2 | Official Docker Engine 27.3.1, build ce12230 (desktop-linux) | nginx:1.27.3-alpine | python:3.11-alpine | OpenObserve v0.14.2 | Execution Date: 2025-01-21.

502 Bad Gateway vs 504 Gateway Timeout in Nginx Logs

Docker CLI executing Nginx 502 Bad Gateway triage on Docker Engine 27.3.1: reproducing POSIX errno 111 Connection refused on 127.0.0.1:3000 versus HTTP 200 OK with 0.0.0.0:3000 and resolver 127.0.0.11
Nginx 1.27.3 inside Docker returns HTTP/1.1 502 Bad Gateway with POSIX error (111: Connection refused) whenever the upstream container listens exclusively on 127.0.0.1:3000 or rotates to a new bridge IP (172.18.0.5), whereas binding 0.0.0.0:3000 and resolving via Docker's embedded DNS (127.0.0.11) restores HTTP/1.1 200 OK in 1.8 ms.

Engineers proxying HTTP traffic through Nginx to containerized Node.js, Python FastAPI, Go, or Spring Boot services frequently conflate HTTP 502 Bad Gateway with HTTP 504 Gateway Timeout, leading them to waste time increasing proxy_read_timeout or proxy_connect_timeout values that have zero effect on a 502 error. At the Linux kernel and TCP transport layer, these two HTTP status codes represent fundamentally different upstream failure states (and if your upstream is a long-lived Server-Sent Events endpoint stalling or dropping at 60 seconds, see our n8n MCP Server Trigger Nginx SSE buffering & 60s timeout benchmark, or generate matched proxy blocks in our Nginx 502/504 Timeout Config Generator):

  • 504 Gateway Timeout (ETIMEDOUT / POSIX errno 110): Nginx either completed the TCP three-way handshake with the backend container and waited longer than proxy_read_timeout (default 60s) for the application to emit HTTP response headers, or sent a TCP SYN packet to an unassigned IP address where no host or firewall replied until proxy_connect_timeout expired.
  • 502 Bad Gateway (ECONNREFUSED / POSIX errno 111): Nginx sent a TCP SYN packet to the target container IP and port, and the Linux kernel at that destination immediately rejected the connection by returning a TCP RST, ACK packet in under 2 milliseconds. No timeout timer ever runs because the remote kernel actively refused the socket handshake.
Split terminal comparison contrasting HTTP 502 Bad Gateway immediate TCP RST (errno 111 in 1.8 ms) against HTTP 504 Gateway Timeout upstream worker stall (errno 110 after 60.0 s)
Contrasting Nginx upstream failure modes on Docker Engine 27.3.1: an unbound or stale container port triggers an immediate kernel TCP RST and returns HTTP 502 Bad Gateway (111: Connection refused) in 1.8 ms, whereas a hanging backend worker or silently dropped SYN stalls until proxy_read_timeout (60.0 s) expires with HTTP 504 Gateway Timeout (110: Operation timed out).

Root Cause 1: Application Listening on Localhost (127.0.0.1)

The single most common cause of an immediate 502 Bad Gateway when moving an application into Docker is leaving the web framework bound to its local development default of localhost or 127.0.0.1 (for example, app.listen(3000, '127.0.0.1') in Express or running uvicorn main:app --port 8000 without a --host flag). On a bare-metal Linux server or local workstation, when Nginx and your application run inside the same host operating system, both processes share the same loopback interface (lo), so Nginx can forward traffic to http://127.0.0.1:3000 without issue.

Inside Docker, however, every container runs inside its own isolated Linux network namespace (netns) with a dedicated virtual Ethernet pair (eth0) attached to the Docker bridge and its own private loopback interface (lo). When your application binds to 127.0.0.1:3000 inside the backend container, the Linux kernel attaches that listening socket exclusively to the backend container's private lo interface. When Nginx in a separate container sends a TCP SYN packet across the Docker bridge to the backend container's bridge IP (172.18.0.2:3000 arriving on eth0), the kernel finds no socket bound to eth0 and immediately replies with a TCP RST packet. Here is that exact failure reproduced on Docker Desktop for Windows 11 where gfl-proxy (Nginx) forwards to gfl-app:3000 on the shared gfl-net bridge, but the Python server inside gfl-app listens only on 127.0.0.1:

Terminal capture showing gfl-proxy returning HTTP/1.1 502 Bad Gateway with connect() failed (111: Connection refused) to 172.18.0.2:3000 while gfl-app listens on 127.0.0.1:3000
nginx answers 502 Bad Gateway. Its log says connect() failed (111: Connection refused) to upstream http://172.18.0.2:3000/, and netstat -tln inside gfl-app shows the server listening only on 127.0.0.1:3000.

The Fix: Bind to 0.0.0.0 (All Interfaces)

Inspecting the three diagnostic commands in the capture above pinpoints why the connection fails even though Docker DNS resolution succeeded. First, docker exec gfl-proxy wget -S -qO /dev/null 127.0.0.1:8080 returns HTTP/1.1 502 Bad Gateway. Second, docker logs gfl-proxy prints connect() failed (111: Connection refused) while connecting to upstream, client: 127.0.0.1, ... upstream: "http://172.18.0.2:3000/", proving that Nginx resolved the hostname gfl-app to 172.18.0.2 via Docker's embedded DNS server. Third, running docker exec gfl-app netstat -tln reveals that port 3000 is bound strictly to 127.0.0.1:3000 (alongside Docker's internal DNS listener at 127.0.0.11:39087).

To allow the backend container's virtual Ethernet interface (eth0) to accept connections from the Nginx reverse proxy container, you must configure your application server to bind to the IPv4 wildcard address 0.0.0.0 (INADDR_ANY):

// File: backend-api/server.js (Node.js 20 Express)
const express = require('express');
const app = express();
const PORT = process.env.PORT || 3000;
const HOST = process.env.HOST || '0.0.0.0'; // Never use '127.0.0.1' or 'localhost' in Docker

app.get('/health', (req, res) => {
  res.status(200).json({ status: 'ok', listen: `${HOST}:${PORT}` });
});

app.listen(PORT, HOST, () => {
  console.log(`Backend API listening on http://${HOST}:${PORT}`);
});
# File: backend-api/Dockerfile (Python 3.11 FastAPI / Uvicorn)
FROM python:3.11-alpine
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
EXPOSE 8000
# Uvicorn defaults to --host 127.0.0.1 if --host 0.0.0.0 is omitted!
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]
Code and Dockerfile editor comparing broken 127.0.0.1 loopback binding against production 0.0.0.0 wildcard binding in Node.js 20 Express and Python 3.11 FastAPI Uvicorn
Updating Node.js Express (app.listen(PORT, '0.0.0.0')) and Python FastAPI (uvicorn main:app --host 0.0.0.0 --port 8000) to bind INADDR_ANY (0.0.0.0) instead of the default 127.0.0.1 loopback address so the container's eth0 bridge interface accepts upstream TCP handshakes from Nginx.

A common security question from developers is whether binding a backend service to 0.0.0.0:3000 exposes the application directly to the public internet or bypasses host firewall rules. Because 0.0.0.0 (INADDR_ANY) only binds all IPv4 interfaces inside the container's isolated Linux network namespace (specifically the container's private loopback lo at 127.0.0.1 and its virtual Ethernet interface eth0 at 172.18.0.2), the port remains completely unreachable from external hosts as long as you omit the ports: - "3000:3000" mapping on the backend service in docker-compose.yml. Only peer containers attached to the same internal user-defined Docker bridge network (such as your Nginx reverse proxy container) can route TCP packets across the virtual bridge to 172.18.0.2:3000, preserving strict zero-trust network isolation on the host.

Split terminal trace comparing Linux network namespace loopback (lo) isolation when bound to 127.0.0.1:3000 versus eth0 bridge reachability when bound to 0.0.0.0:3000
Tracing the TCP packet path across isolated Linux network namespaces on gfl-net (172.18.0.0/16): when gfl-app binds 127.0.0.1:3000, incoming SYN packets arriving on eth0 (172.18.0.2) from gfl-proxy (172.18.0.3) are rejected by the kernel with TCP RST, whereas binding 0.0.0.0:3000 opens the socket on both lo and eth0.

To verify that changing the socket binding from 127.0.0.1 to 0.0.0.0 resolves the 502 Bad Gateway error without modifying a single line of the Nginx configuration, I removed the gfl-app container (docker rm -f gfl-app) and recreated it on the exact same gfl-net network with python -m http.server 3000 --bind 0.0.0.0 (container ID 65445f69bd641750697f2ab1f0c31de8c76d315dd3de030c068d5b03c93ead30). Running docker exec gfl-app netstat -tln now confirms 0.0.0.0:3000 LISTEN alongside Docker's embedded DNS socket at 127.0.0.11:36559, and re-running the identical wget -S -qO /dev/null 127.0.0.1:8080 probe from inside gfl-proxy immediately returns HTTP/1.1 200 OK (Content-Length: 805):

Terminal capture showing gfl-app recreated with --bind 0.0.0.0, netstat -tln confirming 0.0.0.0:3000 LISTEN, and gfl-proxy returning HTTP/1.1 200 OK (Content-Length: 805)
With gfl-app restarted using --bind 0.0.0.0 on gfl-net, netstat -tln confirms 0.0.0.0:3000 LISTEN and the untouched gfl-proxy immediately returns HTTP/1.1 200 OK (Content-Length: 805).

The exact same container loopback isolation rule applies in the reverse direction when Nginx runs inside a Docker container, or inside GUI-managed Nginx Proxy Manager (jc21/nginx-proxy-manager:2.11.3), and attempts to proxy traffic to a backend via http://127.0.0.1:3000. Inside the Nginx container, 127.0.0.1:3000 dials the proxy container's own loopback interface rather than the backend container or the host machine (a trap we also cover in our Docker Windows 11 ECONNREFUSED localhost guide). When both containers run in Docker, always set the upstream target to the backend's Compose service name (for example, http://backend-api:3000) on a shared bridge network, and verify in centralized log telemetry that upstream_addr resolves to the container bridge IP with http_status: 200:

Live Nginx Proxy Manager v2.11.3 Proxy Hosts UI at http://127.0.0.1:8181/nginx/proxy contrasting service name routing (http://backend-api:3000) against loopback routing (http://127.0.0.1:3000)
In containerized reverse proxy and Nginx Proxy Manager deployments, forwarding to 127.0.0.1:3000 routes traffic to the proxy container's own loopback interface and logs POSIX errno 111 (HTTP 502), whereas targeting the Compose service name (backend-api:3000) on a shared bridge network with 0.0.0.0 binding returns HTTP 200 OK.

Root Cause 2: Docker Bridge Network Isolation & DNS Resolution

Default Bridge vs. User-Defined Bridge Networks

Even when your backend application correctly binds to 0.0.0.0:3000, Nginx will fail to reach it if the two containers are attached to Docker's legacy default bridge network (docker0) or split across separate Compose project networks. By design, Docker disables its embedded DNS server (127.0.0.11:53) on the default bridge network; containers launched via standalone docker run commands without a --network flag inherit the host's external /etc/resolv.conf and cannot resolve peer container names. When Nginx starts on the default bridge with proxy_pass http://backend-api:3000;, the master process immediately aborts startup with [emerg] 1#1: host not found in upstream "backend-api".

Docker container network namespace diagram showing why proxy_pass 127.0.0.1 triggers HTTP 502 Errno 111 versus Docker embedded DNS 127.0.0.11 resolving 0.0.0.0 upstream service containers
Container NetNS Routing: Calling 127.0.0.1:3000 inside Nginx hits Nginx's own isolated loopback (Errno 111), whereas pairing resolver 127.0.0.11 valid=10s with an upstream service bound to 0.0.0.0:3000 on a user-defined Docker Compose bridge survives container recreations cleanly.

Attaching both containers to an explicit user-defined bridge network in docker-compose.yml instructs Docker Engine to inject nameserver 127.0.0.11 into each container's /etc/resolv.conf and register service names automatically:

VS Code editor displaying production docker-compose.yml with reverse-proxy and backend-api attached to the shared production-tier bridge network and external: true multi-Compose fix
Production docker-compose.yml attaching both reverse-proxy (nginx:1.27.3-alpine) and backend-api to the user-defined production-tier bridge network so Docker's embedded DNS server (127.0.0.11:53) resolves service names automatically without exposing port 3000 on the host.

Correct docker-compose.yml Architecture

# File: docker-compose.yml
services:
  reverse-proxy:
    image: nginx:1.27.3-alpine
    container_name: reverse-proxy
    restart: unless-stopped
    ports:
      - "80:80"
      - "443:443"
    volumes:
      - ./nginx.conf:/etc/nginx/conf.d/default.conf:ro
    networks:
      - production-tier

  backend-api:
    build: ./backend-api
    container_name: backend-api
    restart: unless-stopped
    environment:
      - PORT=3000
      - HOST=0.0.0.0
    # Notice: no host ports: mapping is needed! Port 3000 is reachable on production-tier.
    networks:
      - production-tier

networks:
  production-tier:
    driver: bridge

Diagnostic Command: Verify Network Membership

If your Nginx proxy and backend application live in two separate docker-compose.yml repositories, Docker Compose prefixes each default network with its directory name (creating isolated subnets such as proxy_default on 172.18.0.0/16 and app_default on 172.19.0.0/16). Always run docker inspect on both containers to confirm they share the exact same network name and subnet prefix, and verify that /etc/resolv.conf inside Nginx points to 127.0.0.11 (see also our Docker WSL 2 DNS resolution failure breakdown):

Split terminal comparison showing Nginx aborting startup with [emerg] host not found in upstream on the default bridge network versus resolving backend-api via 127.0.0.11 on the production-tier bridge
Containers launched on Docker's default bridge network lack the 127.0.0.11 embedded DNS daemon and abort Nginx startup with [emerg] host not found in upstream "backend-api", whereas attaching both containers to the user-defined production-tier bridge injects nameserver 127.0.0.11 into /etc/resolv.conf and enables Layer-3 routing across 172.22.0.0/16.

Root Cause 3: Recreated Container Gets a New IP While Nginx Keeps the Old One (Tested)

Why Static proxy_pass Breaks on Container Recreation

The most deceptive Docker Nginx failure occurs when your stack works flawlessly after docker compose up -d, but suddenly starts returning 502 Bad Gateway hours or days later right after you redeploy the backend container (for example, via docker compose up -d --no-deps --build backend-api). When you write a static hostname in proxy_pass http://backend-api:3000;, Nginx resolves backend-api through /etc/resolv.conf (127.0.0.11) only once when the Nginx master process starts or reloads and caches that IPv4 address in memory forever. Across a 200-request benchmark comparing all four upstream configurations on Docker Engine 27.3.1, both loopback binding and post-redeploy IP rotation caused 100% HTTP 502 failures with sub-2ms TCP RST latencies, whereas pairing 0.0.0.0 with dynamic 127.0.0.11 resolution achieved 100% HTTP 200 OK at a median latency of 1.8 ms:

Dual-panel Matplotlib benchmark chart comparing 200-request HTTP 200 OK vs 502 failure rates and p50/p99 response latencies across four Docker Nginx upstream configurations
Empirical 200-request benchmark across four Docker Nginx upstream configurations on Engine 27.3.1: loopback binding (127.0.0.1:3000) and static proxy_pass after an upstream IP shift both produced 100% HTTP 502 errors (p50 = 1.4–1.6 ms TCP RST), while binding 0.0.0.0 with resolver 127.0.0.11 valid=5s and a variable proxy_pass achieved 100% HTTP 200 OK at p50 = 1.8 ms.

Why do many developers miss this static DNS caching bug during local testing? Because when you stop and recreate a single container on an otherwise idle Docker bridge network, Docker's IPAM address allocator frequently hands the recreated container the exact same IPv4 address it held before (172.18.0.3), masking the stale-DNS caching bug until another container grabs the freed IP during a rolling deployment or multi-service update. To prove how container IP reassignment triggers an immediate 502 Bad Gateway under static proxy_pass while dynamic resolution prevents it, I tested three container recreation scenarios on 2025-01-21 on Docker Desktop for Windows 11, using nginx:1.27.3-alpine on the gfl-net bridge network with proxy_pass http://gfl-app:80:

Terminal capture showing three container recreation cases on gfl-net: fixed.conf reusing 172.18.0.3, fixed.conf failing with HTTP 502 when a filler container takes 172.18.0.3, and resolver.conf succeeding at 172.18.0.5
Static proxy_pass (fixed.conf) keeps working while the recreated app gets its old IP (172.18.0.3) back, but returns HTTP 502 (111: Connection refused) as soon as a filler container takes 172.18.0.3 and the app moves to 172.18.0.5. The resolver 127.0.0.11 + variable config (resolver.conf) returns HTTP 200 in the same scenario.

The three empirical test cases in the capture above reveal the exact mechanics of stale IP caching on gfl-net:

  • Case 1 (fixed.conf, no competing container launched): gfl-app starts at 172.18.0.3 and returns HTTP 200 after 0s. When gfl-app is removed and immediately recreated with no other container starting in between, Docker reassigns 172.18.0.3 to the new container, so Nginx's stale cached IP accidentally keeps working (HTTP 200 after 0s).
  • Case 2 (fixed.conf, filler container takes the freed IP): While gfl-app is down during recreation, a filler container starts on gfl-net and claims 172.18.0.3. The recreated gfl-app receives 172.18.0.5. Because fixed.conf uses a static proxy_pass, Nginx keeps dialing 172.18.0.3:80 (where the filler container refuses the connection) and fails with HTTP 502 after 0s and nginx: connect() failed (111: Connection refused) while connecting to upstream. I did not test the case where the old IP stays empty. Then no container is there to refuse the connection, so expect a different error than 111 (typically a 504 Gateway Timeout after proxy_connect_timeout expires).
  • Case 3 (resolver.conf with resolver 127.0.0.11 valid=5s and variable proxy_pass): Even when the filler container takes 172.18.0.3 and gfl-app moves to 172.18.0.5, Nginx re-queries 127.0.0.11 and returns HTTP 200 after 0s.
Live OpenObserve v0.14.2 Logs Explorer at http://127.0.0.1:5080 displaying stream docker_nginx_proxy_logs across the 3-case container recreation IP shift from 172.18.0.3 to 172.18.0.5
Inspecting containerized Nginx upstream telemetry in OpenObserve v0.14.2 (:5080): when gfl-app rotates from 172.18.0.3 to 172.18.0.5, static proxy_pass continues dialing 172.18.0.3:80 and logs errno 111 HTTP 502 events, whereas enabling resolver 127.0.0.11 updates upstream_addr to 172.18.0.5:80 and restores HTTP 200 responses.

The Solution: Variable proxy_pass with Docker's Embedded DNS

To force standard open-source Nginx to resolve upstream container hostnames dynamically at request time rather than once at boot, you must combine two directives inside /etc/nginx/conf.d/default.conf: declare Docker's embedded DNS server with resolver 127.0.0.11 valid=5s ipv6=off;, and pass the upstream URL through an Nginx variable (set $backend_service "http://backend-api:3000"; followed by proxy_pass $backend_service;). Passing a $variable to proxy_pass switches Nginx from its configuration-time ngx_http_upstream_add host lookup to its runtime ngx_resolver phase handler, expiring the cached container IP every 5 seconds. Note one important URI-forwarding nuance: when proxy_pass uses a variable without a trailing URI path (set $backend_service "http://backend-api:3000";), Nginx automatically forwards the original $request_uri intact; if you need to strip a location prefix such as /api/, capture the subpath with a regex (location ~ ^/api/(.*)$) and append /$1$is_args$args explicitly:

# File: /etc/nginx/conf.d/default.conf
server {
    listen 80;
    server_name api.gearflowlab.com;

    # 1. Query Docker's embedded DNS server (127.0.0.11) and expire cached IPs every 5s:
    resolver 127.0.0.11 valid=5s ipv6=off;
    resolver_timeout 3s;

    location / {
        # 2. Store the upstream target in a variable to force runtime DNS re-resolution:
        set $backend_service "http://backend-api:3000";
        proxy_pass $backend_service;

        proxy_http_version 1.1;
        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 5s;
        proxy_next_upstream error timeout http_502 http_503;
    }
}
VS Code editor displaying /etc/nginx/conf.d/default.conf with resolver 127.0.0.11 valid=5s ipv6=off and set $backend_service alongside URI path forwarding regex rules and nginx -t verification
Combining resolver 127.0.0.11 valid=5s ipv6=off with set $backend_service "http://backend-api:3000" and proxy_pass $backend_service in /etc/nginx/conf.d/default.conf forces Nginx to re-query Docker's embedded DNS server every 5 seconds instead of caching the boot-time container IP forever.

Root Cause 4: Startup Race Conditions & Healthchecks

Fix with Docker Compose Healthchecks

Even with 0.0.0.0 socket binding, a shared production-tier bridge network, and dynamic 127.0.0.11 DNS resolution in place, stacks frequently emit a burst of 502 Bad Gateway errors during the first 5 to 15 seconds after running docker compose up -d. Adding a plain depends_on: - backend-api clause to reverse-proxy only instructs Docker Compose to wait until the backend-api container process (PID 1) has been created. It does not wait for Node.js TypeScript compilation, Prisma or Alembic database migrations, or Uvicorn worker initialization to actually open TCP port 3000. As a result, Nginx starts in under a second and immediately begins forwarding client requests to backend-api:3000 while the port is still closed. To eliminate cold-boot 502 errors completely, define a container-level healthcheck on backend-api and gate reverse-proxy with condition: service_healthy (see our full Docker Compose healthcheck troubleshooting guide for wget vs curl image traps):

# File: docker-compose.yml (Cold-Boot Readiness Gating)
services:
  backend-api:
    build: ./backend-api
    container_name: backend-api
    environment:
      - PORT=3000
      - HOST=0.0.0.0
    healthcheck:
      test: ["CMD-SHELL", "wget -qO- http://127.0.0.1:3000/health || exit 1"]
      interval: 5s
      timeout: 3s
      retries: 5
      start_period: 15s
    networks:
      - production-tier

  reverse-proxy:
    image: nginx:1.27.3-alpine
    container_name: reverse-proxy
    depends_on:
      backend-api:
        condition: service_healthy
    ports:
      - "80:80"
    volumes:
      - ./nginx.conf:/etc/nginx/conf.d/default.conf:ro
    networks:
      - production-tier

networks:
  production-tier:
    driver: bridge
Split comparison contrasting cold-start 502 Bad Gateway errors under plain depends_on against zero cold-boot 502s using a Docker Compose healthcheck and condition: service_healthy
Plain depends_on launches Nginx as soon as the backend container process starts (returning HTTP 502 while database migrations or TypeScript builds are still initializing), whereas condition: service_healthy waits until wget -qO- http://127.0.0.1:3000/health returns 200 OK before starting Nginx.

Pairing condition: service_healthy with resolver 127.0.0.11 valid=5s ipv6=off; covers both lifecycle transitions of a production Docker stack: service_healthy prevents cold-boot 502 responses while the backend initializes its listening socket, and the 5-second embedded DNS TTL bounds the maximum stale-IP window during rolling container recreations to at most 5.0 seconds (p50 = 1.8s), compared to a 300-second stall under Nginx's default resolver TTL or an infinite outage under a static proxy_pass:

Nginx Upstream Configuration Cold-Boot Behavior Behavior After Container IP Shift (.3 -> .5) Max Stale-IP 502 Window
Static proxy_pass http://backend-api:3000; 502 for 12s without healthcheck Permanent 502 Bad Gateway until manual reload Infinite (requires nginx -s reload)
resolver 127.0.0.11; (default 300s TTL) + $var 502 for 12s without healthcheck Caches old IP for up to 5 minutes 300.0 seconds
resolver 127.0.0.11 valid=30s ipv6=off; + $var 502 for 12s without healthcheck Re-queries embedded DNS every 30s 30.0 seconds
resolver 127.0.0.11 valid=5s ipv6=off; + $var + service_healthy 0 cold-boot 502s (waits for /health) Automatic re-resolution to new container IP <= 5.0 seconds (p50 = 1.8s)
Dual-panel Matplotlib chart showing rolling container recreation recovery over a 30-second timeline and maximum stale-DNS 502 windows across resolver TTL settings
Measured recovery timeline when recreating backend-api on a new bridge IP (172.18.0.3 -> 172.18.0.5) at t = 5s: static proxy_pass remains stuck in a permanent HTTP 502 state until a manual reload, whereas resolver 127.0.0.11 valid=5s bounds the maximum stale-DNS window to <= 5.0 seconds.

Production Verification Checklist

Before exposing a containerized Nginx reverse proxy to production traffic (or whenever you are triaging an active HTTP 502 Bad Gateway incident) work systematically from the Nginx error log signature down to the container network namespace. First inspect whether the log prints [emerg] host not found in upstream (Domain 2: default bridge or split Compose networks where Docker's embedded DNS at 127.0.0.11:53 is unavailable) versus connect() failed (111: Connection refused) while connecting to upstream (Domain 1: 127.0.0.1 loopback socket binding inside the app container, Domain 3: stale cached container IP after a rolling container recreate, or Domain 4: cold-start port readiness race before the application binds port 3000). The four-domain decision matrix below maps each error signature directly to its container verification probe and permanent fix:

Four-domain Docker and Nginx 502 Bad Gateway diagnostic decision tree mapping error log tokens (errno 111, [emerg] host not found, stale IP, cold-start race) to container probes and fixes
End-to-end diagnostic decision tree mapping each Nginx error.log signature ([emerg] host not found in upstream, 111: Connection refused against 127.0.0.1 vs a stale bridge IP, and startup-window 502s) to its container network probe and permanent Compose or nginx.conf fix.

Once your docker-compose.yml and /etc/nginx/conf.d/default.conf updates are deployed, run this four-command verification sequence from the Docker host to confirm end-to-end DNS resolution, Layer-4 socket reachability, wildcard interface binding, and zero public host-port exposure:

  1. Verify embedded DNS resolution from inside the Nginx container: Run docker exec reverse-proxy getent hosts backend-api and confirm it returns the current production-tier bridge IP (172.22.0.4) via 127.0.0.11.
  2. Test direct container-to-container HTTP connectivity from inside Nginx: Run docker exec reverse-proxy wget -qO- http://backend-api:3000/health to verify that the TCP handshake and HTTP response succeed across the bridge before testing Nginx routing.
  3. Check for wildcard listening ports inside the backend container: Run docker exec backend-api netstat -tulpn | grep LISTEN and confirm the application socket is bound to 0.0.0.0:3000 (never 127.0.0.1:3000).
  4. Audit active Nginx resolver directives and host port isolation: Run docker exec reverse-proxy nginx -T 2>/dev/null | grep -E "resolver|backend_service|proxy_pass" and docker port backend-api to confirm dynamic 5-second DNS resolution is active while port 3000 remains unexposed on the host.
# 4-Command Production Connectivity, Embedded DNS & Socket Security Audit:
docker exec reverse-proxy getent hosts backend-api
docker exec reverse-proxy wget -qO- http://backend-api:3000/health
docker exec backend-api netstat -tulpn | grep LISTEN
docker exec reverse-proxy nginx -T 2>/dev/null | grep -E "resolver|backend_service|proxy_pass"
Four-command production connectivity, embedded DNS 127.0.0.11, and socket security audit card for Docker Nginx reverse proxy deployments
Four-command production connectivity and socket security audit verifying 127.0.0.11 embedded DNS resolution (getent hosts), direct upstream health response (wget -qO-), 0.0.0.0 wildcard socket binding (netstat -tulpn), and active variable proxy_pass directives (nginx -T).

Scope & Testbed Notes: All container network traces, socket tables, and container recreation benchmarks in this guide were executed and verified on 2025-01-21 using Official Docker Desktop (Docker Engine 27.3.1, build ce12230 on WSL 2 Linux kernel 6.6.87.2-microsoft-standard-WSL2) with nginx:1.27.3-alpine, python:3.11-alpine, jc21/nginx-proxy-manager:2.11.3, and OpenObserve v0.14.2.

Nginx 502 Upstream Socket & 127.0.0.11 DNS Caching Q&A

Why does Nginx in Docker log connect() failed (111: Connection refused) to a running app container?

Either the backend application inside the peer container is bound to 127.0.0.1 instead of 0.0.0.0, or Nginx cached an old container IP address before the backend container was recreated. Bind the backend to 0.0.0.0 and configure resolver 127.0.0.11 valid=10s in Nginx.

Why does resolver 127.0.0.11 fail if proxy_pass uses a hardcoded upstream name without a variable?

Nginx resolves static hostnames in proxy_pass only once during startup or reload and ignores the resolver directive thereafter. Assign the upstream URL to a set $upstream variable inside the location block so Nginx re-queries Docker's embedded DNS server at 127.0.0.11 when TTL expires.

Does depends_on in Docker Compose stop cold-start 502 Bad Gateway errors?

A plain depends_on list only waits until Docker creates the backend container process, not until its HTTP port opens. Pair a container healthcheck on the backend service with condition: service_healthy under depends_on so Nginx waits until the port accepts connections.

100% Client-Side Utilities · Printable A4 Runbook

Run Prefilled Sizing Math & Download the 1-Page Runbook

Generate Docker DNS-safe Nginx, Caddy 2, and Traefik v3 reverse-proxy configs with 127.0.0.1 loopback host bindings.

Paired Prefilled Calculators & Vector PDF Checklist

Yun Sanghun (M. Yun) · Linux, Docker & AI Infrastructure Engineer