Docker Compose
Docker Compose is a tool for defining and running multi-container Docker applications. With Compose, you use a YAML file to configure your application’s services. Then, with a single command, you create and start all the services from your configuration.
This outline covers the features of Docker Compose and provides examples for using it to run the application.
Using Docker Compose
To use Docker Compose, you must install it. Docker Compose is included in Docker Desktop. If you are not using Docker Desktop, you can install Docker Compose separately by following the instructions found here.
For more information about Docker Compose, you can refer to the Docker Compose documentation.
Note:
This application uses Docker Compose version 3.9
or higher.
The example code in this outline will demonstrate the docker-compose
commands.
Before running any commands, be sure to:
- Ensure that Docker Compose is installed.
- Make sure to set up Docker by running
docker version
in your command line.
To start the application with Docker Compose, run the following command in the application’s root directory:
docker-compose up -d
Running Tests
To run the tests using Docker Compose, run the following command in the application’s root directory:
docker-compose run web pytest
Building the Application
To build the application using Docker Compose, run the following command in the application’s root directory:
docker-compose build
This will build all the images defined in the docker-compose.yml
file.
Defining Services
The docker-compose.yml
file defines the services in the application. The file contains the following structure:
version: '3.9'
services:
web:
build: .
ports:
- '8080:8080'
depends_on:
- redis
redis:
image: redis:alpine
This file defines two services:
web
: The web service builds from the current directory and exposes port 8080, using a dependency on the redis service.redis
: The redis service uses the imageredis:alpine
.
To modify the services in the application, you can edit the docker-compose.yml
file and then rebuild and restart the application.
Scaling Services
To scale the application, you can use the docker-compose scale
command.
Example: Scale the web
service to 3 containers:
docker-compose scale web=3
Stopping Services
To stop the services, run the following command in the application’s root directory:
docker-compose down
This command will stop and remove all the containers, networks, and volumes created by Docker Compose.
Viewing Logs
To view logs from a service, run the following command:
docker-compose logs <service name>
For example, to view logs from the web
service, run:
docker-compose logs web
Executing Commands
To execute commands within a running container, use the docker-compose exec
command.
Example: Run the command ls -l
in the web
container:
docker-compose exec web ls -l
Troubleshooting
If you encounter any issues running the application, you can use the following resources: