Docker Compose: create and manage multi-container applications
Introduction
Docker Compose is a tool for defining and running multi-container Docker applications. With Compose, you use a YAML file (typically named docker-compose.yml
) to configure your application’s services, networks, and volumes. Then, with a single command, you create and start all the services defined in your configuration.
Docker Compose is ideal for:
- Development environments
- Automated testing environments
- Single host deployments
- CI/CD workflows
Using Docker Compose involves a three-step process:
- Define your application’s environment in a Dockerfile
- Define the services that make up your application in a
docker-compose.yml
file - Run
docker compose up
to start and run your entire application
Usage
Installation
Before using Docker Compose, make sure you have Docker installed and the Docker engine running on your system.
To install Docker Compose:
|
|
Creating a docker-compose.yml file
Here’s a basic example of a docker-compose.yml
file:
|
|
This configuration sets up two services:
- A web server using the nginx:alpine image
- A database using the postgres:13 image
Basic Commands
Start your services
|
|
Add -d
to run in detached mode (background):
|
|
Stop your services
|
|
To remove volumes as well:
|
|
View running services
|
|
View logs
|
|
Follow logs with:
|
|
Execute commands in a service container
|
|
Scaling Services
You can run multiple instances of a service:
|
|
This starts 3 instances of the web service.
Environment Variables
You can use environment variables in your docker-compose.yml:
|
|
Create a .env
file in the same directory:
NGINX_PORT=8080
Working with Networks
Docker Compose automatically creates a network for your application. You can also define custom networks:
|
|
Depends On
Specify dependencies between services:
|
|
Health Checks
Add health checks to ensure services are properly started:
|
|
Example: Full-Stack Web Application
Here’s a more complete example for a web application with frontend, backend, and database:
|
|
This setup demonstrates how Docker Compose can orchestrate a complete application stack with multiple interconnected services.
Resources
Last updated 04 May 2025, 18:44 CEST.