Networks between containers

How containers find each other by name.

An application and its database usually live in different containers and need to talk. For that you create a user-defined network. Containers in such a network see each other, and Docker's built-in DNS answers a container's name with its current address. There is no need to publish the database port on the host: the traffic stays inside the network.

docker network create shop
docker run -d --name db --network shop -e POSTGRES_PASSWORD=example postgres:16.4
docker run -d --name api --network shop -e DATABASE_HOST=db -p 8080:8080 shop-api:1.0

The application connects to the host db on port 5432. Only the application's port 8080 is open to the outside, and the database is reachable only by containers in the shop network.

Container addresses change every time a container is recreated, so they are not written into settings. A container name, or a service name in Compose, stays the same. The default network (bridge) cannot do this: in it, containers do not find each other by name. That is why related containers always get their own network; Docker Compose does this automatically.

Networks also separate containers. A container in the shop network does not see containers in the blog network unless it is explicitly connected to both. That way, for example, one project's database is not reachable from another project's application. A running container can be attached to one more network with docker network connect.

A common mistake is to put an address like 172.18.0.3, spotted in docker inspect, into the application's settings. After the database is recreated the address changes and the application loses its connection. The second mistake is to publish the database port with -p just so the application on the same server can connect: that opens the database to the outside for no reason.

Practice

  1. How to find the database

    The application and the database db run in the same user-defined network. Which database address should the application use?

    • The IP address from docker inspect
    • The container name db
    • localhost
    • The host address and the database's published port
  2. User-defined networks

    Which statements about user-defined networks are true? Mark all.

    • Containers find each other by name
    • For two containers in the network to talk, the port must be published with -p
    • Containers in different networks do not see each other by default
    • Name lookup also works in the default bridge network
  3. Creating a network

    Which command creates a user-defined network named shop?