Service Discovery & DNS
Inside a Compose project you never type an IP address. The API connects to db:5432, the worker to redis:6379, and it just works. This lesson explains the machinery behind that: Docker's embedded DNS server, which names it answers for, how scaled services resolve, and the handful of settings that change name resolution.
The embedded DNS server
Every container on a user-defined network (and Compose networks are user-defined) gets nameserver 127.0.0.11 in its /etc/resolv.conf. That address is a small DNS server built into the Docker engine. For each query it checks, in order:
- names it knows on the networks the asking container is attached to: service names, container names, aliases, hostnames;
- otherwise it forwards the query to the host's DNS servers (or the ones in
dns:).
api container Docker engine upstream
┌──────────────┐ "db?" ┌─────────────────────────────┐ "pypi.org?" ┌──────────┐
│ resolv.conf │────────▶│ 127.0.0.11 embedded DNS │──────────────▶│ host DNS │
│ 127.0.0.11 │◀────────│ db -> 172.20.0.3 (backend) │◀──────────────│ / dns: │
└──────────────┘ └─────────────────────────────┘ └──────────┘A sample session inside a running project:
$ docker compose exec api cat /etc/resolv.conf
nameserver 127.0.0.11
options ndots:0
$ docker compose exec api getent hosts db
172.20.0.3 dbThe answer depends on who asks: names are scoped per network. A container that doesn't share a network with db gets "not found", exactly as in the Networks tier example.
Which names resolve?
For a container demo-api-1 of service api on network backend, all of these work from other containers on backend:
| Name | Example | Notes |
|---|---|---|
| service name | api |
the one to use; returns every replica |
| container name | demo-api-1 |
one specific replica |
container_name |
shop-api |
if you set one (then no scaling) |
| network alias | api.internal |
per network, from networks.<net>.aliases |
hostname |
api-01 |
only inside the container itself, it's not registered for others unless it equals a name above |
Scaled services: one name, many IPs
With three replicas of worker, the name worker resolves to three addresses. The order is rotated between queries, so clients that just take the first address spread out roughly evenly. This is DNS round-robin, not a real load balancer: clients that cache the answer (the JVM, some HTTP pools) stick to one replica until the cache expires.
import itertools
# what the embedded DNS knows, per network
records = {
"backend": {
"db": ["172.20.0.3"],
"worker": ["172.20.0.5", "172.20.0.6", "172.20.0.7"],
"api": ["172.20.0.4"], "api.internal": ["172.20.0.4"],
},
"frontend": {"api": ["172.21.0.2"], "proxy": ["172.21.0.3"]},
}
attached = {"proxy": ["frontend"], "api": ["frontend", "backend"], "worker": ["backend"]}
rotation = itertools.count()
def lookup(client, name):
for net in attached[client]:
ips = records[net].get(name)
if ips:
r = next(rotation) % len(ips)
return f"{', '.join(ips[r:] + ips[:r])} (via {net})"
return "NXDOMAIN -> forwarded upstream, not found"
for client, name in [("api", "db"), ("api", "worker"), ("api", "worker"),
("proxy", "api"), ("proxy", "db"), ("worker", "api.internal")]:
print(f"{client:<6} asks {name:<13} -> {lookup(client, name)}")api asks db -> 172.20.0.3 (via backend)
api asks worker -> 172.20.0.6, 172.20.0.7, 172.20.0.5 (via backend)
api asks worker -> 172.20.0.7, 172.20.0.5, 172.20.0.6 (via backend)
proxy asks api -> 172.21.0.2 (via frontend)
proxy asks db -> NXDOMAIN -> forwarded upstream, not found
worker asks api.internal -> 172.20.0.4 (via backend)
Two details from the model are real behaviour: proxy asking for api gets the API's address on the frontend network, and proxy asking for db gets nothing because they share no network.
If you need real load balancing with health awareness, put a proxy (nginx, Traefik, HAProxy, Envoy) in front, or move to Swarm, whose services get one stable virtual IP: see Service Discovery & Load Balancing.
container_name and scaling don't mix
A fixed container_name is tempting ("I want it to be called shop-api"), but container names are unique on a host, so the service can't have more than one replica. Compose checks this:
services:
api:
image: ghcr.io/acme/api:3.0
container_name: shop-api
deploy:
replicas: 3services.deploy.replicas: can't set container_name and api as container name must be unique: invalid compose project
Prefer service names for discovery and leave container names to Compose.
Settings that affect resolution
services:
api:
image: ghcr.io/acme/api:3.0
hostname: api-01
extra_hosts:
- "billing.legacy.local:10.0.5.20"
- "host.docker.internal:host-gateway"
dns: [1.1.1.1]
dns_search: [corp.example]
links: ["db:database"]
db:
image: postgres:17name: demo
services:
api:
links:
- db:database
dns:
- 1.1.1.1
dns_search:
- corp.example
extra_hosts:
- billing.legacy.local=10.0.5.20
- host.docker.internal=host-gateway
hostname: api-01
image: ghcr.io/acme/api:3.0
networks:
default: null
depends_on:
db:
condition: service_started
restart: true
required: true
db:
image: postgres:17
networks:
default: null
networks:
default:
name: demo_default
extra_hostswrites lines into the container's/etc/hosts. Compose normalisesname:iptoname=ip. The special valuehost-gatewayresolves to the host's address, sohost.docker.internalreaches a service running directly on your Linux machine (Docker Desktop provides that name automatically).dns/dns_searchchange only the upstream servers and search domains. The embedded server still answers for service names first.linksis a legacy feature from before user-defined networks. It adds an extra name (database) and, as the output shows, an implicitdepends_on(withrestart: true). On a modern network you don't need it: usealiasesfor extra names anddepends_onfor order.
The localhost trap
Inside a container, localhost is the container itself. A connection string that works on your laptop (postgres://localhost:5432) fails inside the API container: nothing listens on port 5432 there. The fix is the service name, and the published port doesn't matter either: container-to-container traffic uses the container port.
from urllib.parse import urlsplit
services = {"db": 5432, "redis": 6379} # service -> container port
published = {"db": "15432:5432"} # host port mappings (irrelevant inside)
def check(url):
u = urlsplit(url)
host, port = u.hostname, u.port
if host in ("localhost", "127.0.0.1"):
return "wrong: localhost is the api container itself"
if host not in services:
return f"wrong: no service called {host!r}"
if port != services[host]:
return f"wrong: {host} listens on {services[host]} inside the network (host port mappings don't apply)"
return "ok"
for url in ["postgres://app@localhost:5432/app", "postgres://app@db:15432/app",
"postgres://app@database:5432/app", "postgres://app@db:5432/app",
"redis://redis:6379/0"]:
print(f"{url:<36} {check(url)}")postgres://app@localhost:5432/app wrong: localhost is the api container itself
postgres://app@db:15432/app wrong: db listens on 5432 inside the network (host port mappings don't apply)
postgres://app@database:5432/app wrong: no service called 'database'
postgres://app@db:5432/app ok
redis://redis:6379/0 ok
From the host, it's the other way around: use localhost:15432 (the published port), because the host isn't on the project network and can't resolve db.
Across projects
Service names are only registered on networks the service joins. To let project B call project A's api, both join one shared external network (see Networks), and then B can use api, or, more robustly, an alias that is unique across projects (two projects might both have a service called api!).
Learn more: Kubernetes DNS · Docker Networks · Scaling & Resources
Test yourself
What is 127.0.0.11 inside a Compose container?
- The host machine
- Docker's embedded DNS server
- The default gateway
- The db service
The db service publishes "15432:5432". Which address should the api container use?
- localhost:15432
- db:15432
- db:5432
- host.docker.internal:5432
Why can't a service with container_name: shop-api be scaled to 3?
- Scaling needs Swarm
- Container names must be unique, so only one container can have that name
- DNS can't resolve it
- container_name disables networking