Docker-compose is a useful tool for orchestrating multi-container Docker applications. It allows you to run applications based on a YAML file. These files are a list of instructions specifying the parameters of the applications to be launched.
In our example, we will run two containers – a MySQL database and a basic WordPress web application.
Docker build files might look like this:
version: '3.3'
services:
db:
image: mysql:5.7
volumes:
- db_data:/var/lib/mysql
restart: always
environment:
MYSQL_ROOT_PASSWORD: somewordpress
MYSQL_DATABASE: wordpress
MYSQL_USER: wordpress
MYSQL_PASSWORD: wordpress
wordpress:
depends_on:
- db
image: wordpress:latest
ports:
- "8000:80"
restart: always
environment:
WORDPRESS_DB_HOST: db:3306
WORDPRESS_DB_USER: wordpress
WORDPRESS_DB_PASSWORD: wordpress
WORDPRESS_DB_NAME: wordpress
volumes:
db_data: {}
We can use some basic docker-compose commands to manage containers:
Build or rebuild websites
docker-compose build
Create and run containers
docker-compose up
As you can see, the containers have been launched and the logs printed on the console. To run in the background, use the -d parameter.
Run a one-time command on the website
docker-compose run
ex: docker-compose run wordpress
For example, you can print the Debian version of the WordPress container.
Show list of running containers
docker ps
The docker ps command shows:
Print a list of information about running containers from the current docker-compose.yaml file
docker-compose ps
Show all logs in the container since its launch
docker logs <service>
Stop and delete containers, networks, volumes and images created with the “up” command
docker-compose down
Kill one or more running containers
docker kill <container_id>
Show image list
docker images
Execute the command in a running container
docker exec <service> <bash_command>
Delete all unused data
docker system prune
Kill all running containers
docker kill $(docker ps -q)
Stop all running containers
docker stop $(docker ps -q)
Delete all images
docker rmi $(docker images -q)
Remove all containers
docker rm $(docker container ps -q)
Docker-compose is a useful and easy tool for managing multiple containers. You can decide how containers are separated, what resources they can use and how they communicate with each other. You can also set what happens if the status of one of the containers changes. This feature allows you to automatically restore your system state.