Service Discovery & DNS

In a dynamic environment where containers are created and destroyed every minute, IP addresses are ephemeral. You can never hardcode 172.17.0.2 in your application config.

Instead, Docker provides a built-in DNS Server so containers can find each other by name.

1. The Embedded DNS Server (127.0.0.11)

Every Docker container has a resolv.conf file pointing to 127.0.0.11. This is a lightweight DNS server embedded in the Docker daemon.

When your app resolves db:

  1. Query goes to 127.0.0.11.
  2. Docker checks if db is a container name or alias in the same network.
  3. If yes, it returns the container’s private IP.
  4. If no, it forwards the query to the host’s DNS (e.g., 8.8.8.8).

2. Interactive: DNS Resolver

Type a hostname to see how Docker resolves it.

root@web:/# ping
Container Resolver (127.0.0.11)
Waiting...
Docker Network: my-net
db → 172.18.0.5
redis → 172.18.0.6
api → 172.18.0.7

3. Round-Robin Load Balancing

If you scale a service (e.g., docker service create --replicas 3 --name web ...), Docker assigns multiple IPs to the same DNS name.

When you query web, Docker returns the list of IPs in a round-robin fashion.

# First query
nslookup web
# -> 10.0.0.5, 10.0.0.6, 10.0.0.7

# Second query
nslookup web
# -> 10.0.0.6, 10.0.0.7, 10.0.0.5

This provides a basic, client-side load balancing mechanism out of the box.

4. Summary

  • 127.0.0.11: The magic IP that handles all DNS inside containers.
  • Automatic Registration: Containers are automatically added to DNS when they join a network.
  • Load Balancing: DNS responses are rotated for scaled services.