- DevOps with Kubernetes
- Hideto Saito Hui Chuan Chloe Lee Cheng Yang Wu
- 445字
- 2025-04-04 15:00:00
An overview of Docker compose
Docker compose is a tool that enables us to run multiple containers with ease. It's a built-in tool in the Docker CE distribution. All it does is read docker-compose.yml (or .yaml) to run the defined containers. A docker-compose file is a YAML-based template, and it typically looks like this:
version: '3'
services:
hello-world:
image: hello-world
Launching it is pretty simple: save the template to docker-compose.yml and use the docker-compose up command to start it:
$ docker-compose up
Creating network "user_default" with the default driver
Pulling hello-world (hello-world:)...
...
Creating user_hello-world_1 ... done
Attaching to user_hello-world_1
hello-world_1 |
hello-world_1 | Hello from Docker!
hello-world_1 | This message shows that your installation appears to be working correctly.
...
user_hello-world_1 exited with code 0
Let's take a look at what docker-compose did when the up command was executed.
Docker compose is basically a medley of Docker functions for multiple containers. For example, the counterpart of docker build is docker-compose build; the former builds a Docker image and the latter builds Docker images listed in docker-compose.yml. Remember, however, that the docker-compose run command doesn't correspond to docker run; it's actually used to run a specific container from the configuration in docker-compose.yml. In fact, the closest command to docker run is docker-compose up.
The docker-compose.yml file consists of different configurations of volumes, networks, and services. There should be a version definition to indicate which version of the docker-compose format should be used. With this understanding of the template structure, what the previous hello-world example does is quite clear; it creates a service called hello-world that uses the hello-world:latest image.
Since there's no network defined, docker-compose will create a new network with a default driver and connect services to that network, as shown at the start of the output of the example.
The network name of a container will be the name of the service. You may notice that the name displayed in the console differs slightly from its original one in docker-compose.yml. This is because Docker compose tries to avoid name conflicts between containers. As a result, Docker compose runs the container with the name it generated and makes a network alias with the service name. In this example, both hello-world and user_hello-world_1 are resolvable to other containers within the same network.