Running one container is fine.
But real apps usually need many containers:
Starting each one with long docker run commands is painful ๐.
๐ Docker Compose solves this.
Docker Compose lets you define and run multiple containers using one file called docker-compose.yml.
In simple words:
๐ Mostly used in development and testing, but also useful in small production setups.
Imagine ordering food ๐๐๐ฅค:
Instead of ordering one by one, you order a combo.
๐ Docker Compose = Combo order for containers.
This file describes:
Everything in YAML format.
version: "3.9"
services:
web:
image: nginx
ports:
- "80:80"
db:
image: mysql:8
environment:
MYSQL_ROOT_PASSWORD: rootversion: "3.9"
services:
web:
image: nginx
ports:
- "80:80"
db:
image: mysql:8
environment:
MYSQL_ROOT_PASSWORD: rootWhat happens:
Start everything:
docker compose up
docker compose upRun in background:
docker compose up -d
docker compose up -dStop containers:
docker compose down
docker compose down๐ One command replaces many docker run commands.
Each container is called a service.
Example:
services: frontend: backend: database:
services:
frontend:
backend:
database:Compose automatically:
backend can talk to database directly)By default:
๐ Example:
backend:
depends_on:
- dbbackend:
depends_on:
- dbBackend can reach DB using:
mysql -h db
mysql -h dbNo IP needed ๐.
Used to persist data.
services:
db:
image: mysql
volumes:
- db_data:/var/lib/mysql
volumes:
db_data:services:
db:
image: mysql
volumes:
- db_data:/var/lib/mysql
volumes:
db_data:Now:
You can define env variables directly:
environment: APP_ENV: production
environment:
APP_ENV: productionOr use .env file (cleaner way):
MYSQL_ROOT_PASSWORD=root
MYSQL_ROOT_PASSWORD=rootCompose automatically loads it.
Instead of using prebuilt images:
web:
build: .
ports:
- "3000:3000"web:
build: .
ports:
- "3000:3000"Then run:
docker compose up --build
docker compose up --build๐ Great for local development.
web:
depends_on:
- dbweb:
depends_on:
- dbThis ensures:
๐ Note: It doesn’t wait for DB to be ready, only started.
Stop and remove containers:
docker compose down
docker compose downRemove volumes also:
docker compose down -v
docker compose down -v| Feature | Docker Compose | Docker Swarm |
|---|---|---|
| Purpose | Local / simple setups | Production clustering |
| Scaling | Manual | Automatic |
| Nodes | Single host | Multiple hosts |
| Complexity | Simple ๐ | Medium |
๐ Compose = local orchestration
๐ Swarm = cluster orchestration
Use Docker Compose when: