Docker Compose: 101

Enrique Pittaluga
2 min readOct 21, 2020

Docker compose is a tool that is automatically installed when Docker is installed on your machine.

Docker Compose automates some of the CLI commands and allows you to connect and start multiple Docker containers.

It makes use of a yml file which is designed to build, network and run the docker containers required by the project. The yml file will then be executed by the docker-compose script and parse the instructions to configure the containers and connections. In the project directory, create a docker-compose.yml file:

> touch docker-compose.yml

The yml file makes use of a special syntax to execute the build and run commands.

By embedding the docker images in the same docker-compose file, docker compose grants access between the containers automatically.

Up and - -build

Docker-compose runs and builds containers using different commands than the traditional docker script. For instance, instead of using the run command to instantiate a container, docker-compose uses up. This command should be executed from the project directory with the docker-compose.yml file:

> docker-compose up

Similarly, Docker-compose simplifies the build and run process by using the same command, up, and receiving the - -build flag as well.

> docker-compose up --build

Additional Commands

Detach

Sometimes it would be nice to start up a container in the background freeing your terminal up for further commands. In these cases, you can use the -d flag, or detach, to run the process in the background.

> docker-compose up -d

Down

In order to stop the processes you can use the down command:

> docker-compose down

As before, you must be in the directory where the docker-compose.yml is located for this command to take effect on the container instances managed by Docker Compose.

PS

> docker-compose ps

Restart Policies

In real world applications it is possible for a container to crash and terminate a running process. Docker Compose provides several options to developers for automate responses to crashes, known as restart policies. These restart policies are: no, always, on-failure, and unless-stopped. Fortunately, the meaning of these policies are easy to understand: “no” means that a container should never restart and it is the default; always means that a container should always restart; on-failure means that a container should restart if the failure produces a non-zero error code; and unless-stopped means that a container will always restart unless manually stopped by a developer.

Docker Compose manages each service (container) separately and consequently each service has its own restart policy managed in the docker-compose.yml file.

References

--

--