BelajarKoding Logobelajarkoding

Platform belajar web development Indonesia. Artikel, cheat sheets, roadmap, dan code challenges untuk developer Indonesia.

Navigasi

  • Artikel
  • Cheat Sheets
  • Roadmap
  • Challenges
  • Pricing
  • Search

Produk Lain

  • JagoHermes
  • KelasClaude
  • KilatKoding
  • BelajarVibeCoding
  • JualanKoding

Support

  • Privacy Policy
  • Terms of Service
  • Email

© 2026 BelajarKoding. All rights reserved.

Galih PratamaBagian dari ekosistem Galih Pratama
belajarkoding LogobyGalih Pratama
RoadmapArtikelCheat SheetsChallengesUpgrade
belajarkoding LogobyGalih Pratama
RoadmapArtikelCheat SheetsChallengesUpgrade
belajarkoding LogobyGalih Pratama
RoadmapArtikelCheat SheetsChallengesUpgrade

Daftar Isi

Basic StructureCommon CommandsService ConfigurationProfilesHealth ChecksWatch Mode (v2.22+)ExtendsMultiple Compose FilesResource LimitsNetworksExternal NetworkVolumesExternal VolumeSecretsLoggingEnvironment VariablesInit ContainersPattern UmumFull-Stack AppDevelopment with Hot ReloadContext VariablesBest PracticesTroubleshootingVersion DifferencesResources
Docker ComposeDockerDevOpsContainers

Docker Compose Cheat Sheet

Quick reference Docker Compose v2. Syntax, commands, profiles, healthchecks, networking, dan advanced patterns.

YAML7 min read1.315 kata
Cheat sheet ini adalah konten premium. Login atau daftar untuk mengakses konten premium.

#Basic Structure

Struktur dasar Docker Compose terdiri dari services, volumes, dan networks untuk mendefinisikan aplikasi multi-container.

yaml
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:

#Common Commands

Perintah-perintah umum Docker Compose untuk mengelola lifecycle container, mulai dari build hingga cleanup.

bash
# 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 up

#Service Configuration

Konfigurasi service mendefinisikan bagaimana setiap container berjalan, termasuk image, ports, environment, dan dependencies.

yaml
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: 40s

#Profiles

Profiles memungkinkan kita mengaktifkan atau menonaktifkan services tertentu berdasarkan environment atau use case.

yaml
services:
 app:
  image: myapp
  # No profile = always runs
 
 redis:
  image: redis:7
  profiles: [dev]
 
 adminer:
  image: adminer
  profiles: [debug]
bash
docker compose up          # app only
docker compose --profile dev up   # app + redis
docker compose --profile dev --profile debug up # all

#Health Checks

Health checks memverifikasi bahwa service berjalan dengan baik sebelum service lain yang bergantung padanya dijalankan.

yaml
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 (v2.22+)

Watch mode memungkinkan file di-sync otomatis ke container saat development, sehingga perubahan langsung terlihat.

yaml
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/config
bash
docker compose watch

#Extends

Extends memungkinkan kita mewarisi konfigurasi dari service lain, mengurangi duplikasi kode.

yaml
# base.yml
services:
 base:
  build: .
  environment:
   NODE_ENV: ${NODE_ENV}
yaml
# compose.yml
services:
 api:
  extends:
   file: base.yml
   service: base
  ports:
   - "3000:3000"

#Multiple Compose Files

Multiple compose files memungkinkan kita memisahkan konfigurasi untuk environment berbeda seperti dev, staging, production.

bash
# 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
yaml
# compose.yml (base)
services:
 app:
  image: myapp
 
# compose.dev.yml (overrides)
services:
 app:
  build: .
  volumes:
   - ./src:/app/src

#Resource Limits

Resource limits membatasi penggunaan CPU dan memory untuk setiap service agar tidak mengganggu service lain.

yaml
services:
 app:
  deploy:
   resources:
    limits:
     cpus: '0.5'
     memory: 512M
    reservations:
     cpus: '0.25'
     memory: 256M

#Networks

Networks mengatur bagaimana container berkomunikasi satu sama lain dan dengan dunia luar.

yaml
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 access

#External Network

External network memungkinkan kita menggunakan network yang sudah ada dari Docker host.

yaml
networks:
 existing:
  external: true
  name: my-existing-network

#Volumes

Volumes menyimpan data secara persistent sehingga tidak hilang ketika container dihapus atau di-restart.

yaml
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: local

#External Volume

External volume memungkinkan kita menggunakan volume yang sudah ada dari Docker host.

yaml
volumes:
 existing:
  external: true
  name: my-existing-volume

#Secrets

Secrets menyimpan informasi sensitif seperti password dengan aman dan terpisah dari kode aplikasi.

yaml
secrets:
 db_password:
  file: ./db_password.txt
 
services:
 db:
  secrets:
   - db_password
  environment:
   POSTGRES_PASSWORD_FILE: /run/secrets/db_password

#Logging

Logging mengatur bagaimana log dari container disimpan dan dikelola untuk debugging dan monitoring.

yaml
services:
 app:
  logging:
   driver: "json-file"
   options:
    max-size: "10m"
    max-file: "3"

#Environment Variables

Environment variables memungkinkan kita mengkonfigurasi aplikasi tanpa mengubah kode, menggunakan file .env atau langsung di YAML.

yaml
services:
 app:
  environment:
   # From .env file
   DATABASE_URL: ${DATABASE_URL}
 
   # With default value
   LOG_LEVEL: ${LOG_LEVEL:-info}
 
   # Direct value
   NODE_ENV: production
.env
DATABASE_URL=postgres://localhost:5432/db
LOG_LEVEL=debug

#Init Containers

Init containers menjalankan tugas setup atau migrasi database sebelum aplikasi utama dijalankan.

yaml
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_successfully

#Pattern Umum

Common patterns menunjukkan contoh konfigurasi Docker Compose yang sering digunakan untuk berbagai jenis aplikasi.

#Full-Stack App

Konfigurasi lengkap untuk aplikasi full-stack dengan frontend, backend, dan database.

yaml
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:

#Development with Hot Reload

yaml
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/src

#Context Variables

Context variables memungkinkan kita menggunakan environment variables di YAML untuk membuat konfigurasi lebih dinamis.

yaml
services:
 app:
  image: myapp:${TAG:-latest}
  environment:
   ENV: ${ENVIRONMENT}
   BUILD_DATE: ${BUILD_DATE}

#Best Practices

Best practices adalah panduan untuk menulis Docker Compose yang aman, maintainable, dan optimal.

  • Use specific image versions (postgres:16, not postgres:latest)
  • Use named volumes for data persistence
  • Add healthchecks for databases
  • Use depends_on with condition: service_healthy
  • Set restart policies (unless-stopped for production)
  • Use .env files for configuration
  • Don't commit secrets (add to .gitignore)
  • Use profiles for optional services
  • Separate base/dev/prod configs with multiple files
  • Use docker compose config to validate

#Troubleshooting

Troubleshooting berisi perintah-perintah untuk debug masalah dengan Docker Compose.

bash
# 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 stats

#Version Differences

Perbedaan antara Docker Compose v1 dan v2, serta kapan menggunakan yang mana.

Docker Compose v1 (deprecated):

  • Command: docker-compose (with hyphen)
  • Version field required in YAML

Docker Compose v2 (current):

  • Command: docker compose (with space)
  • Version field optional (deprecated)
  • Built into Docker CLI
  • Watch mode support

#Resources

Link-link berguna untuk belajar Docker Compose lebih dalam.

  • Compose Specification
  • Compose CLI Reference
  • Awesome Compose

Happy composing! 🐳

Baca Cheat Sheet Lengkap

Login untuk mengakses konten premium ini.

LoginDaftar Gratis
Share: