Quick reference Docker Compose v2. Syntax, commands, profiles, healthchecks, networking, dan advanced patterns.
Struktur dasar Docker Compose terdiri dari services, volumes, dan networks untuk mendefinisikan aplikasi multi-container.
services:
app:
image: myapp:latest
ports:
- "3000:3000"
environment:
NODE_ENV: production
db:
image: postgres:16
volumes:
- db_data:/var/lib/postgresql/data
volumes:
db_data:Perintah-perintah umum Docker Compose untuk mengelola lifecycle container, mulai dari build hingga cleanup.
# Start services
docker compose up
docker compose up -d # Detached mode
docker compose up --build # Rebuild images
docker compose up --force-recreate # Force recreate
# Stop & remove
docker compose down
docker compose down -v # Remove volumes too
# Specific services
docker compose up app db # Only app & db
docker compose restart api # Restart service
# Build
docker compose build
docker compose build --no-cache app # No cache
# Logs
docker compose logs
docker compose logs -f app # Follow logs
docker compose logs --tail=100 app # Last 100 lines
# Execute commands
docker compose exec app sh # Shell in container
docker compose run app npm test # Run one-off command
# Scale
docker compose up --scale api=3 # 3 instances
# Status & stats
docker compose ps
docker compose top
docker compose stats
# Validate
docker compose config # Check syntax
# Watch mode (v2.22+)
docker compose watch
# Profiles
docker compose --profile dev upKonfigurasi service mendefinisikan bagaimana setiap container berjalan, termasuk image, ports, environment, dan dependencies.
services:
app:
# Image or build
image: node:20-alpine
# OR
build:
context: ./app
dockerfile: Dockerfile.dev
args:
NODE_ENV: development
# Ports
ports:
- "3000:3000" # host:container
- "127.0.0.1:3001:3001" # Bind to localhost only
# Environment
environment:
NODE_ENV: production
API_URL: https://api.example.com
env_file:
- .env
- .env.local
# Volumes
volumes:
- ./src:/app/src # Bind mount
- node_modules:/app/node_modules # Named volume
- /app/temp # Anonymous volume
# Networks
networks:
- frontend
- backend
# Dependencies
depends_on:
- db
# OR with condition
db:
condition: service_healthy
restart: true
# Command
command: npm run dev
# OR
entrypoint: ["/bin/sh", "-c"]
# Restart policy
restart: unless-stopped # no, always, on-failure, unless-stopped
# Profiles
profiles: [dev, debug]
# Healthcheck
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost:3000/health"]
interval: 30s
timeout: 10s
retries: 3
start_period: 40sProfiles memungkinkan kita mengaktifkan atau menonaktifkan services tertentu berdasarkan environment atau use case.
services:
app:
image: myapp
# No profile = always runs
redis:
image: redis:7
profiles: [dev]
adminer:
image: adminer
profiles: [debug]docker compose up # app only
docker compose --profile dev up # app + redis
docker compose --profile dev --profile debug up # allHealth checks memverifikasi bahwa service berjalan dengan baik sebelum service lain yang bergantung padanya dijalankan.
services:
db:
image: postgres:16
healthcheck:
test: ["CMD-SHELL", "pg_isready -U postgres"]
interval: 5s
timeout: 5s
retries: 5
start_period: 10s
app:
depends_on:
db:
condition: service_healthy # Wait for healthy!Watch mode memungkinkan file di-sync otomatis ke container saat development, sehingga perubahan langsung terlihat.
services:
web:
build: .
develop:
watch:
# Sync files (hot reload)
- path: ./src
action: sync
target: /app/src
# Rebuild on change
- path: ./package.json
action: rebuild
# Sync + restart
- path: ./config
action: sync+restart
target: /app/configdocker compose watchExtends memungkinkan kita mewarisi konfigurasi dari service lain, mengurangi duplikasi kode.
# base.yml
services:
base:
build: .
environment:
NODE_ENV: ${NODE_ENV}# compose.yml
services:
api:
extends:
file: base.yml
service: base
ports:
- "3000:3000"Multiple compose files memungkinkan kita memisahkan konfigurasi untuk environment berbeda seperti dev, staging, production.
# Override with multiple files
docker compose -f compose.yml -f compose.dev.yml up
# Or set environment variable
export COMPOSE_FILE=compose.yml:compose.dev.yml
docker compose up# compose.yml (base)
services:
app:
image: myapp
# compose.dev.yml (overrides)
services:
app:
build: .
volumes:
- ./src:/app/srcResource limits membatasi penggunaan CPU dan memory untuk setiap service agar tidak mengganggu service lain.
services:
app:
deploy:
resources:
limits:
cpus: '0.5'
memory: 512M
reservations:
cpus: '0.25'
memory: 256MNetworks mengatur bagaimana container berkomunikasi satu sama lain dan dengan dunia luar.
services:
frontend:
networks:
- frontend-net
backend:
networks:
- frontend-net
- backend-net
db:
networks:
- backend-net
networks:
frontend-net:
driver: bridge
backend-net:
driver: bridge
internal: true # No external accessExternal network memungkinkan kita menggunakan network yang sudah ada dari Docker host.
networks:
existing:
external: true
name: my-existing-networkVolumes menyimpan data secara persistent sehingga tidak hilang ketika container dihapus atau di-restart.
services:
db:
volumes:
# Named volume
- postgres_data:/var/lib/postgresql/data
# Bind mount
- ./init.sql:/docker-entrypoint-initdb.d/init.sql
# Anonymous volume
- /var/lib/postgresql/temp
volumes:
postgres_data:
driver: localExternal volume memungkinkan kita menggunakan volume yang sudah ada dari Docker host.
volumes:
existing:
external: true
name: my-existing-volumeSecrets menyimpan informasi sensitif seperti password dengan aman dan terpisah dari kode aplikasi.
secrets:
db_password:
file: ./db_password.txt
services:
db:
secrets:
- db_password
environment:
POSTGRES_PASSWORD_FILE: /run/secrets/db_passwordLogging mengatur bagaimana log dari container disimpan dan dikelola untuk debugging dan monitoring.
services:
app:
logging:
driver: "json-file"
options:
max-size: "10m"
max-file: "3"Environment variables memungkinkan kita mengkonfigurasi aplikasi tanpa mengubah kode, menggunakan file .env atau langsung di YAML.
services:
app:
environment:
# From .env file
DATABASE_URL: ${DATABASE_URL}
# With default value
LOG_LEVEL: ${LOG_LEVEL:-info}
# Direct value
NODE_ENV: productionDATABASE_URL=postgres://localhost:5432/db
LOG_LEVEL=debugInit containers menjalankan tugas setup atau migrasi database sebelum aplikasi utama dijalankan.
services:
migrate:
image: myapp
command: npm run migrate
depends_on:
db:
condition: service_healthy
restart: "no" # Run once
app:
depends_on:
migrate:
condition: service_completed_successfullyCommon patterns menunjukkan contoh konfigurasi Docker Compose yang sering digunakan untuk berbagai jenis aplikasi.
Konfigurasi lengkap untuk aplikasi full-stack dengan frontend, backend, dan database.
services:
frontend:
build: ./frontend
ports:
- "3000:3000"
environment:
VITE_API_URL: http://localhost:4000
api:
build: ./api
ports:
- "4000:4000"
environment:
DATABASE_URL: postgres://user:pass@db:5432/app
depends_on:
db:
condition: service_healthy
db:
image: postgres:16-alpine
volumes:
- postgres_data:/var/lib/postgresql/data
healthcheck:
test: ["CMD-SHELL", "pg_isready"]
volumes:
postgres_data:services:
app:
build:
context: .
target: development
volumes:
- ./src:/app/src
- /app/node_modules # Preserve node_modules
environment:
NODE_ENV: development
develop:
watch:
- path: ./src
action: sync
target: /app/srcContext variables memungkinkan kita menggunakan environment variables di YAML untuk membuat konfigurasi lebih dinamis.
services:
app:
image: myapp:${TAG:-latest}
environment:
ENV: ${ENVIRONMENT}
BUILD_DATE: ${BUILD_DATE}Best practices adalah panduan untuk menulis Docker Compose yang aman, maintainable, dan optimal.
postgres:16, not postgres:latest)depends_on with condition: service_healthyunless-stopped for production).env files for configuration.gitignore)docker compose config to validateTroubleshooting berisi perintah-perintah untuk debug masalah dengan Docker Compose.
# View logs
docker compose logs -f service_name
# Check service status
docker compose ps
# Inspect service
docker inspect container_id
# Enter container
docker compose exec service_name sh
# Restart service
docker compose restart service_name
# Remove everything
docker compose down -v --remove-orphans
# Validate config
docker compose config
# Check resource usage
docker compose statsPerbedaan antara Docker Compose v1 dan v2, serta kapan menggunakan yang mana.
Docker Compose v1 (deprecated):
docker-compose (with hyphen)Docker Compose v2 (current):
docker compose (with space)Link-link berguna untuk belajar Docker Compose lebih dalam.
Happy composing! 🐳