Proxies and container addresses

Docker's DNS (127.0.0.11) returns the current address of a service's containers. A proxy that resolved the name once keeps the old address after the container is recreated.

How it works

A recreated container gets a new IP address on its networks. nginx resolves a name written in proxy_pass when it starts and never again; with a resolver 127.0.0.11 directive and the address in a variable, it asks again when the answer expires (valid=, or the 600-second TTL of Docker's DNS). With Compose, depends_on with restart: true restarts the proxy after the service it depends on is recreated.

What breaks

After a deployment the proxy answers 502 Bad Gateway, although the new container works, until someone restarts the proxy. With a variable but no resolver, nginx cannot resolve anything; with a variable, proxy_pass sends the URI as written, so a trailing / changes the path the service receives.

In compose.yaml

services:
  frontend:
    build: ./frontend
    depends_on:
      api:
        condition: service_started
        restart: true

See it break, then fix it

Write the Dockerfile or the compose file, type the docker commands, and watch a simulated server run them through reboots, upgrades and traffic. Free to start.