Docker Compose — Profiles & Extensions — Practice Exercises
Test your understanding of profiles, extensions, anchors, and includes.
Exercise 1: Basic Profile
Add a debug profile to an adminer service so it only starts when explicitly requested.
Solution
services:
db:
image: postgres:16
environment:
POSTGRES_PASSWORD: secret
adminer:
image: adminer
ports:
- "8080:8080"
profiles:
- debug
docker compose up -d # Only db starts
docker compose --profile debug up -d # db + adminer start
Exercise 2: Multiple Profiles
Create three profiles: dev, test, monitoring. Assign services to appropriate profiles.
Solution
services:
api:
image: myapi:latest
mailhog:
image: mailhog/mailhog
profiles: [dev]
test-runner:
image: myapi:latest
command: npm test
profiles: [test]
prometheus:
image: prom/prometheus
profiles: [monitoring]
docker compose --profile dev up -d
docker compose --profile test run --rm test-runner
docker compose --profile monitoring up -d
Exercise 3: YAML Extension
Extract common logging config into an x-logging extension and apply it to three services.
Solution
x-logging: &logging
logging:
driver: json-file
options:
max-size: "10m"
max-file: "3"
services:
api:
<<: *logging
image: myapi:latest
worker:
<<: *logging
image: myworker:latest
scheduler:
<<: *logging
image: myscheduler:latest
Verify: docker compose config
Exercise 4: Anchors for Environment
Use a YAML anchor to share environment variables across services, then override one variable.
Solution
x-env: &base-env
LOG_LEVEL: info
NODE_ENV: production
services:
api:
image: node:20-alpine
environment:
<<: *base-env
PORT: "3000"
worker:
image: node:20-alpine
environment:
<<: *base-env
LOG_LEVEL: debug # Override base value
Exercise 5: Compose Include
Split a compose file into a main file and a separate database file using include:.
Solution
compose.yml:
include:
- compose.db.yml
services:
api:
image: myapi:latest
depends_on:
- db
compose.db.yml:
services:
db:
image: postgres:16
environment:
POSTGRES_PASSWORD: secret
volumes:
- db-data:/var/lib/postgresql/data
volumes:
db-data:
docker compose config # Shows merged result
docker compose up -d # Starts api + db