Docker Networking Overview
Learning Objectives
- You understand that Docker Compose creates a private network for the services defined in the Docker Compose configuration.
- You understand that the services in a private network can communicate with each other, and that the services need to be explicitly exposed to the local machine to be accessed from the local machine.
In the previous chapter, we added a load balancer to the walking skeleton to distribute the requests. Understanding how the services are connected and how they communicate with each other is a key when trying to debug issues that eventually arise.
Docker Compose and networking
When we run the command docker compose up
, Docker reads in the compose.yaml
file and creates the services defined in the file. Each service is run in its own container, and the containers are connected to a network that is also created by Docker Compose.
The network created by Docker Compose is a bridge network, which is a private network that is isolated from the host network (i.e., your machine). The services can communicate with each other using the addresses of the containers within the network, but the services cannot be accessed from the local machine, unless explicitly configured in the compose.yaml
file.
Load balancer and server replicas
When we think of the load balancer and the server replicas from the last chapter, the load balancer is responsible for routing the requests to the server replicas. The ports of the replicas are not exposed, which means that they cannot be accessed from the local machine. The load balancer, on the other hand, is exposed to the local machine, and it has been configured to route requests to the server replicas.
The separation of (1) the docker network with the load balancer and the two replicas, and (2) the local machine is visualized in Figure 1 below.
Adding a database
Now, let’s add a database to the picture. We have previously configured a database similar to the following in the compose.yaml
file (the PostgreSQL extensions are omitted).
database:
container_name: postgresql_database
image: postgres:17.0
restart: unless-stopped
env_file:
- project.env
The service database
explicitly states a name for the container, postgresql_database
. This is the name that can be used to access the database service from other services within the Docker network. The database is not, however, exposed to the local machine, as the ports are not bound to the local machine. This is visualized in Figure 2 below.