Docker Compose
Docker Compose simplifies the management of multi-container applications.
Instead of running multiple docker run
commands, Compose uses a single configuration file to define and manage services.
What is Docker Compose?
Docker Compose is a tool for defining and running multi-container Docker applications. You use a YAML file to configure your application’s services, networks, and volumes — then launch them all with a single command.
- Defined using a
docker-compose.yml
file - Supports isolated services and networking between containers
- Perfect for microservices, full-stack development, and testing pipelines
Installing Docker Compose
Docker Compose is included in Docker Desktop for Windows and macOS. For Linux:
sudo apt update
sudo apt install docker-compose
Verify installation:
docker-compose --version
Writing a docker-compose.yml
File
Below is an example configuration for a .NET Web API with a PostgreSQL database:
version: '3.8'
services:
webapp:
build: .
ports:
- "8080:80"
depends_on:
- db
db:
image: postgres:15
environment:
POSTGRES_USER: admin
POSTGRES_PASSWORD: secret
POSTGRES_DB: mydb
volumes:
- postgres_data:/var/lib/postgresql/data
volumes:
postgres_data:
This file defines two services — webapp
and db
— and creates a named volume to persist data.
Running and Managing Docker Compose
-
Start services:
docker-compose up -d
-
Stop services:
docker-compose down
-
View logs:
docker-compose logs
-
Rebuild after changes:
docker-compose up --build
Networking in Docker Compose
By default, all services in a Docker Compose file are connected to the same network,
allowing them to communicate using their service names. For example, webapp
can connect to
db
using just the hostname db
.
Best Practices for Docker Compose
- Use environment variables and
.env
files to keep secrets out of your YAML. - Use named volumes for data persistence.
- Use
depends_on
to define service dependencies. - Use
docker-compose.override.yml
for local overrides without changing the base config.
Docker Compose is a powerful tool for orchestrating multi-service applications with ease. It is ideal for development, testing, and CI environments where simplicity and reproducibility matter.