Container DNS and User-Defined Networks
The problem: no DNS on the default bridge
Section titled “The problem: no DNS on the default bridge”As you saw in the previous lesson, containers on the default bridge can reach each other by IP address but not by name. This is a significant limitation in practice — IP addresses are dynamic and change every time a container is recreated.
Hardcoding IP addresses into application configuration is fragile. You need a way to refer to services by a stable name. That is exactly what user-defined networks provide.
The solution: create a user-defined bridge
Section titled “The solution: create a user-defined bridge”Use docker network create to create a named bridge network:
docker network create appnetDocker creates a new bridge (separate from docker0) and starts an embedded DNS resolver scoped to that network. Containers attached to appnet can resolve each other’s names automatically.
Running containers on a user-defined network
Section titled “Running containers on a user-defined network”Start an nginx container named web on appnet:
docker run -d --name web --network appnet nginx:alpineStart an Alpine container named client on the same network:
docker run -it --name client --network appnet alpine shInside the client shell, ping web by name:
ping -c 3 webThe ping succeeds. Docker’s embedded DNS resolver translates web to the container’s IP address automatically.
Inspecting the network
Section titled “Inspecting the network”From the host, inspect appnet to see which containers are attached and what IPs they were assigned:
docker network inspect appnetThe output includes a Containers section listing each attached container with its name, IP, and MAC address.
Teardown
Section titled “Teardown”docker stop web clientdocker rm web clientdocker network rm appnetHands-on: DNS on a user-defined network
Section titled “Hands-on: DNS on a user-defined network”# Create a user-defined bridge network
docker network create appnet
# Start an nginx container on appnet
docker run -d --name web --network appnet nginx:alpine
# Start a client container on appnet and ping web by name
docker run --rm --name client --network appnet alpine ping -c 3 web
# Inspect the network to see attached containers
docker network inspect appnet
# Cleanup
docker stop web && docker rm web
docker network rm appnet