basforge

Search titles, text and the “If it doesn’t work” cases.

    RU

    Docker DNS in nginx — caches the old IP without resolver and a variable

    nginx resolves a container hostname in proxy_pass http://api:8000; once at startup. Recreating api with a new IP leaves the proxy returning 502, and starting nginx while api is down fails outright — fix both with resolver 127.0.0.11 and a variable in proxy_pass.

    Why this happens

    When proxy_pass contains a static hostname, nginx queries DNS only on startup or reload. In Docker, container IPs are ephemeral: docker compose up -d --force-recreate often assigns a different address in the same subnet, leaving nginx sending traffic to a dead IP (Docker).

    Before and after

    # Breaks after recreating the api container (and fails to start without it)
    location /api/ {
        proxy_pass http://api:8000;
    }
    # Re-queries Docker's embedded DNS every 30 seconds
    resolver 127.0.0.11 valid=30s ipv6=off;
    
    location /api/ {
        set $api http://api:8000;
        proxy_pass $api;
    }

    Keep the side effect in mind: when proxy_pass uses a variable, a trailing slash no longer strips the location prefix — if you need to drop /api/, add rewrite ^/api/(.*)$ /$1 break; before proxy_pass.

    If it doesn’t work

    The nginx container crashes on startup: host not found in upstream "api"

    Cause
    The api service isn’t up yet, and a static proxy_pass http://api:8000; must resolve the hostname before nginx starts.
    Fix
    Add resolver 127.0.0.11 valid=30s ipv6=off; and move the target into a variable: set $api http://api:8000; proxy_pass $api;.

    Even with resolver 127.0.0.11, nginx logs no resolver defined or can’t resolve the name

    Cause
    The containers run on Docker’s default bridge network, which has no embedded DNS server at 127.0.0.11.
    Fix
    Put both containers on a shared user-defined network (docker network create proxy or a Compose network, Docker networks).