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
apiservice isn’t up yet, and a staticproxy_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
bridgenetwork, which has no embedded DNS server at127.0.0.11. - Fix
- Put both containers on a shared user-defined network (
docker network create proxyor a Compose network, Docker networks).