Container-to-Container Communication
On a user-defined network, containers reach each other using their container names as hostnames.
Once containers share a user-defined network, they can talk to each other by name. Docker runs a built-in DNS server that resolves container names to their current IP addresses.
Using the container name as a hostname
If a Postgres container is named db, an app on the same network connects to it using the hostname db — no IP addresses, no linking flags.
Why names beat IPs
Container IP addresses can change when they restart. Names stay stable, so your connection strings keep working.
Example
# db is reachable from api simply as the hostname "db"
docker network create app-net
docker run -d --name db --network app-net \
-e POSTGRES_PASSWORD=secret postgres:16
docker run -it --rm --network app-net postgres:16 \
psql -h db -U postgres
# Connects to the db container by nameWhen to use it
- An API container connects to a database container using the hostname db because they share the same user-defined network.
- A microservice mesh places all services on one user-defined network so each can call others by service name, matching their Docker Compose service keys.
- A developer tests inter-service HTTP calls locally by putting both containers on a shared network and using container names as the hostname in URLs.
More examples
API calls database by container name
Places both containers on app-net so the API can reach Postgres using the hostname 'postgres'.
docker network create app-net
docker run -d --name postgres \
--network app-net \
-e POSTGRES_PASSWORD=secret \
postgres:16-alpine
docker run -d --name api \
--network app-net \
-e DATABASE_URL=postgres://postgres:secret@postgres:5432/app \
myapi:latestVerify DNS resolution between containers
Confirms that Docker's embedded DNS resolves the container name 'postgres' to its IP on the shared network.
docker exec api ping -c2 postgres
docker exec api nslookup postgresConnect an existing container to a network
Attaches an already-running container to an additional network without restarting it.
# Add a running container to a second network
docker network connect app-net legacy-service
# Verify it now appears on both networks
docker inspect legacy-service --format '{{range $k,$v := .NetworkSettings.Networks}}{{$k}}\n{{end}}'
Discussion