Networks and service-to-service calls

Docker · lesson 11 of 31 · 3 min read

Let containers find and call each other by name instead of chasing IP addresses.

Open this lesson in the learning hub

Key points

  • Create a user-defined bridge network and Docker adds DNS. Containers then resolve each other by container name.
  • The old default bridge network has no DNS. That is why db:5432 fails there.
  • On the same network you use the container port. Publishing with -p is only for traffic coming from the host.
  • So the app can dial jdbc:postgresql://db:5432/app even though the host never sees port 5432.
  • Need the host machine from inside a container? host.docker.internal works 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.