A container can be attached to several networks. On each one it has an IP and can resolve the names of the other containers on that network.
Connect a running container
docker network connect backend web frontend 172.18.0.0/16 backend 172.19.0.0/16
┌──────────────────────┐ ┌──────────────────────┐
│ tools 172.18.0.3 │ │ api 172.19.0.2 │
│ web 172.18.0.2 ───┼────────┼─ web 172.19.0.3 │
└──────────────────────┘ └──────────────────────┘web now has one IP per network:
docker inspect --format '{{range $net, $cfg := .NetworkSettings.Networks}}{{$net}} {{$cfg.IPAddress}}{{println}}{{end}}' webbackend 172.19.0.3
frontend 172.18.0.2docker network disconnect backend web removes it again.
| Container | Can resolve |
|---|---|
web | tools, api |
tools | web |
api | web |
How names resolve
Every container on a user-defined network sends DNS queries to Docker's embedded server at 127.0.0.11. It answers with the IP of the container on a network the asker shares.
docker exec tools nslookup webServer: 127.0.0.11
Address: 127.0.0.11:53
Non-authoritative answer:
Name: web
Address: 172.18.0.2A name on a network tools is not attached to:
docker exec tools nslookup apiServer: 127.0.0.11
Address: 127.0.0.11:53
** server can't find api: NXDOMAINgetent hosts NAME resolves the same way the application does. It exists in Debian-based images such as nginx, which have no nslookup:
docker exec web getent hosts api172.19.0.2 apiAliases
An alias is an extra DNS name for a container on one network. Set it when the container joins:
| When | Command |
|---|---|
At docker run | docker run -d --name cache --network backend --network-alias redis redis:7.4 |
| When connecting | docker network connect --alias catalog backend api |
An alias cannot be added to an existing connection. Disconnect and connect again:
docker network disconnect backend api
docker network connect --alias catalog backend api
docker inspect --format '{{json .NetworkSettings.Networks.backend.DNSNames}}' api["api","catalog","99fddfcd7640"]The container answers to its name, every alias, and its short ID. Aliases let a client keep a fixed name (redis, db) while the container behind it changes.