Networks and service-to-service calls
Let containers find and call each other by name instead of chasing IP addresses.
Open this lesson in the learning hubKey points
- Create a user-defined bridge network and Docker adds DNS. Containers then resolve each other by container name.
- The old default
bridgenetwork has no DNS. That is whydb:5432fails there. - On the same network you use the container port. Publishing with
-pis only for traffic coming from the host. - So the app can dial
jdbc:postgresql://db:5432/appeven though the host never sees port 5432. - Need the host machine from inside a container?
host.docker.internalworks on Docker Desktop, not on plain Linux.
Example
docker network create appnet
docker run -d --name db --network appnet \
-e POSTGRES_PASSWORD=secret postgres:16
# note: no -p on db. only the api is reachable from the host.
docker run -d --name api --network appnet -p 8080:8080 \
-e SPRING_DATASOURCE_URL=jdbc:postgresql://db:5432/postgres \
-e SPRING_DATASOURCE_USERNAME=postgres \
-e SPRING_DATASOURCE_PASSWORD=secret \
myapp:1.0
# "db" resolves inside the network and nowhere else
docker exec api getent hosts db
Same network, call by name, use the container port. No -p needed.
This is a reading copy. The full lesson — with the visual explainer, the interactive lab and a Run button for the code — lives in the Docker course, and every lesson in it is listed on the Docker contents page.