Docker Compose tutorial
Docker Compose is a tool for defining and running multiple Docker containers, which simplifies the deployment and management of multi-container applications. This tutorial will introduce how to use Docker Compose to quickly build and manage multi-container applications.
Step 1: Install Docker Compose
First, make sure you have Docker installed. Then, you can install Docker Compose by following these steps:
- Open a terminal or command line interface.
- Run the following command to download the Docker Compose installation script:
$ sudo curl -L "https://github.com/docker/compose/releases/latest/download/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose
- Grant execute permission:
$ sudo chmod +x /usr/local/bin/docker-compose
- Verify installation:
$ docker-compose --version
If the installation was successful, the version information of Docker Compose will be displayed.
Step 2: Write the Docker Compose file
Docker Compose uses a YAML-formatted file to define services, networks, volumes, etc. for multi-container applications. Create a file named at the root of your project docker-compose.yml
and edit it as follows:
version: '3'
services:
web:
build: .
ports:
- "80:80"
db:
image: mysql:5.7
environment:
- MYSQL_ROOT_PASSWORD=secret
In this example, two services are defined: web
and db
. web
The service builds an image using the Dockerfile in the current directory, and maps port 80 of the container to port 80 of the host. db
The service uses the MySQL 5.7 image and sets environment variables MYSQL_ROOT_PASSWORD
.
Step 3: Start the Docker Compose application
To start the Docker Compose application, simply run the following command in a terminal or command line interface:
$ docker-compose up
This command will start the corresponding container according to the service defined in the Docker Compose file. If you need to run in the background, use -d
the parameter:
$ docker-compose up -d
Step 4: Manage the Docker Compose application
The application lifecycle can be managed easily with Docker Compose. Here are some commonly used administrative commands:
docker-compose ps
: View the status of all containers in the application.docker-compose logs
: View the logs of all containers in the application.docker-compose exec
: Execute the command in the specified container.docker-compose stop
: Stops the container in the application.docker-compose start
: Start the container in the application.docker-compose restart
: Restart the container in the application.docker-compose down
: Stop and remove containers, networks, and volumes in the application.
Summarize
This tutorial introduces the basic usage of Docker Compose. By writing Docker Compose files, you can quickly build and manage multi-container applications. With Docker Compose, you can easily define and run multiple containers, and manage the entire application lifecycle with simple commands.