How to use Docker Compose to manage multiple containers?
Published on Aug. 22, 2023, 12:19 p.m.
To use Docker Compose to manage multiple containers, you need to define the containers and their configuration in a YAML file called docker-compose.yml.
Here is an example docker-compose.yml file that defines two containers, a web server and a database, and links them together:
version: '3'
services:
web:
image: nginx:latest
ports:
- "80:80"
volumes:
- ./web:/usr/share/nginx/html
depends_on:
- db
db:
image: mysql:latest
environment:
MYSQL_ROOT_PASSWORD: password
In this example, the web service uses the nginx image and maps port 80 of the container to port 80 of the host machine. It also mounts the ./web directory on the host to the /usr/share/nginx/html directory in the container. The db service uses the mysql image and sets the MYSQL_ROOT_PASSWORD environment variable to “password”.
To start the containers defined in the docker-compose.yml file, run the following command in the directory containing the file:
docker-compose up
This will create and start the containers, and display their logs in the terminal. If you want to run the containers in the background, use the -d or --detach option:
docker-compose up -d
To stop and remove the containers, run the following command:
docker-compose down
This will stop the containers and remove them, as well as any volumes and networks created by the docker-compose up command.
Docker Compose is a powerful tool that allows you to easily manage multiple containers and their configuration. You can define environment variables, mount volumes, link containers together, and much more using the docker-compose.yml file.