Docker Compose untuk Multi-Service: Menjalankan Aplikasi dan Database secara Bersamaan
Menjalankan satu container Docker untuk aplikasi sederhana adalah langkah awal. Namun, aplikasi production nyata membutuhkan kombinasi service: web server, database, cache, message queue, dan lainnya. Mengelola container-container ini secara manual dengan docker run menjadi tidak praktis dan rentan error. Docker Compose adalah tool yang memungkinkan kita mendefinisikan dan menjalankan multi-container application dalam satu file konfigurasi.
Mengapa Multi-Service Orchestration Penting
Aplikasi modern terdiri dari komponen terpisah yang saling berkomunikasi. Sebuah web app memerlukan database untuk persistence, Redis untuk caching, dan mungkin Elasticsearch untuk search. Menjalankan masing-masing dengan command terpisah menyebabkan beberapa masalah: dependency harus dijalankan dalam urutan tertentu, environment variables tersebar di berbagai tempat, dan cleanup menjadi rumit.
Docker Compose menyederhanakan ini dengan declarative configuration. Kita definisikan semua service, network, dan volume dalam satu docker-compose.yml. Satu command docker compose up menjalankan seluruh stack secara konsisten di semua environment.
Struktur File docker-compose.yml
File docker-compose.yml menggunakan format YAML dengan beberapa key komponen utama. Setiap service adalah container yang akan dijalankan. Network memungkinkan container saling berkomunikasi. Volume digunakan untuk persistent storage.
version: '3.8'
services:
# Define individual services here
networks:
# Define custom networks
volumes:
# Define named volumesVersion directive menentukan format file. Services block berisi definisi container. Setiap service memiliki konfigurasi image, ports, environment variables, dan dependencies.
Contoh Stack: Node.js + PostgreSQL + Redis
Mari kita buat stack lengkap dengan tiga service: aplikasi Node.js sebagai backend, PostgreSQL sebagai database, dan Redis untuk caching. Konfigurasi ini merepresentasikan arsitektur common untuk web application.
version: '3.8'
services:
app:
build:
context: .
dockerfile: Dockerfile
container_name: node-app
ports:
- "3000:3000"
environment:
- NODE_ENV=development
- DATABASE_URL=postgresql://postgres:password@db:5432/myapp
- REDIS_URL=redis://cache:6379
depends_on:
- db
- cache
networks:
- app-network
volumes:
- .:/app
- /app/node_modules
db:
image: postgres:15-alpine
container_name: postgres-db
environment:
- POSTGRES_USER=postgres
- POSTGRES_PASSWORD=password
- POSTGRES_DB=myapp
ports:
- "5432:5432"
volumes:
- postgres-data:/var/lib/postgresql/data
networks:
- app-network
cache:
image: redis:7-alpine
container_name: redis-cache
ports:
- "6379:6379"
networks:
- app-network
volumes:
postgres-data:
networks:
app-network:
driver: bridgeService app menggunakan build context untuk membangun image dari Dockerfile lokal. Port mapping 3000:3000 mengekspos aplikasi ke host. Environment variables menyediakan connection string ke database dan cache.
Service db menggunakan official PostgreSQL image dari Docker Hub. Environment variables mengkonfigurasi initial database credentials. Named volume postgres-data memastikan data tetap persisten meskipun container di-restart.
Service cache menggunakan Redis Alpine image yang lightweight. Tidak ada volume karena Redis dalam contoh ini hanya untuk cache yang boleh hilang saat restart.
Mengelola Service Dependencies
Container sering memiliki startup order requirements. Database harus ready sebelum aplikasi mencoba connect. Directive depends_on mengekspresikan dependency ini.
services:
app:
depends_on:
- db
- cacheNamun, depends_on hanya menunggu container start, bukan service ready. PostgreSQL container mungkin sudah berjalan, tetapi database belum siap menerima connection. Untuk production-grade dependency management, gunakan wait-for-it script atau health checks.
services:
app:
depends_on:
db:
condition: service_healthy
db:
healthcheck:
test: ["CMD-SHELL", "pg_isready -U postgres"]
interval: 5s
timeout: 5s
retries: 5Healthcheck memastikan Docker menunggu sampai database benar-benar ready sebelum menandai service sebagai healthy.
Deep Learning Bootcamp
A beginner-friendly, highly interactive bootcamp designed to take you from found...
Environment Variables dan File .env
Hardcoding credentials dalam docker-compose.yml adalah bad practice untuk production. Docker Compose mendukung environment variable substitution dan file .env terpisah.
services:
db:
environment:
- POSTGRES_USER=${DB_USER}
- POSTGRES_PASSWORD=${DB_PASSWORD}
- POSTGRES_DB=${DB_NAME}File .env di direktori yang sama:
DB_USER=postgres
DB_PASSWORD=securepassword123
DB_NAME=myappDocker Compose secara otomatis membaca file .env dan mensubstitusi variabel. File .env ditambahkan ke .gitignore untuk menjaga credential tetap private.
Networking Antar Service
Docker Compose secara otomatis membuat default network yang menghubungkan semua service. Setiap service dapat mengakses service lain menggunakan service name sebagai hostname.
Dalam contoh kita:
- Aplikasi Node.js connect ke database dengan hostname
db - Aplikasi connect ke Redis dengan hostname
cache - Port internal dapat diakses tanpa publish ke host
Custom network dengan driver bridge memberikan isolasi lebih baik. Service hanya dapat berkomunikasi jika berada dalam network yang sama.
Command untuk Mengelola Multi-Service Stack
Docker Compose CLI menyediakan command untuk lifecycle management lengkap.
# Build dan jalankan semua service dalam background
docker compose up -d
# Melihat status service yang berjalan
docker compose ps
# Melihat logs dari semua service
docker compose logs -f
# Melihat logs dari service spesifik
docker compose logs -f app
# Restart service tertentu
docker compose restart app
# Scale service ke multiple instance
docker compose up -d --scale app=3
# Stop dan hapus semua container
docker compose down
# Stop, hapus container dan volume
docker compose down -vCommand up -d membangun image jika diperlukan, membuat network dan volume, lalu menjalankan container dalam detached mode. Command down membersihkan semua resources yang dibuat Compose.
Development Workflow dengan Docker Compose
Untuk development, bind mount memungkinkan live reload. Source code di host di-mount ke dalam container. Perubahan file langsung terlihat tanpa rebuild image.
services:
app:
volumes:
- .:/app
- /app/node_modulesVolume kedua untuk node_modules adalah anonymous volume yang mencegah bind mount menimpa dependencies yang di-install dalam container.
Best Practices untuk Production
Konfigurasi development dan production berbeda. Gunakan multiple Compose file untuk environment-specific overrides.
# Base configuration
docker-compose.yml
# Production overrides
docker-compose.prod.ymlCommand untuk production:
docker compose -f docker-compose.yml -f docker-compose.prod.yml up -dFile production dapat menonaktifkan bind mounts, menggunakan image pre-built dari registry, dan mengaktifkan restart policies.
services:
app:
image: myregistry.com/myapp:latest
restart: unless-stopped
deploy:
replicas: 2Kesimpulan
Docker Compose mengubah cara kita mengembangkan dan mendeploy multi-service application. Satu file konfigurasi mendefinisikan seluruh stack, memastikan consistency across environments. Service discovery otomatis melalui DNS, dependency management, dan networking built-in mengurangi complexity operational.
Ingin menguasai container orchestration dan modern DevOps practices? Bergabunglah di DevOps Engineering Bootcamp Rumah Coding. Program hands-on mencakup Docker, Kubernetes, CI/CD pipelines, dan cloud deployment untuk mempersiapkan karir di dunia DevOps.
Course Terkait
Deep Learning Bootcamp
A beginner-friendly, highly interactive bootcamp designed to take you from foundational concepts to deploying real-world Artificial Intelligence applications. Through a completely project-based approach, you will master the core of Deep Learning, Artificial Neural Networks, and Computer Vision using Python and TensorFlow, ultimately building a professional-grade AI web application for your portfolio.
GreenGuard: Intelligent Plant Disease Diagnosis Web App
- Interactive Image Upload UI: A clean, user-friendly interface built with Streamlit that supports drag-and-drop image uploads directly from a computer or mobile phone.
- Real-Time AI Inference: Utilizes a lightweight, optimized CNN model (like MobileNetV2) to process the image and return a diagnosis in seconds without heavy server load.
- Confidence Scoring Dashboard: Visually displays the model's prediction probability (e.g., "95% confident this is Tomato Late Blight") using interactive progress bars or charts.
LLM Bootcamp
This project-based bootcamp is designed for beginners to dive practically into the world of Large Language Models (LLMs). Through hands-on building, you will learn how to interact with top-tier AI APIs, master prompt engineering, orchestrate complex workflows using LangChain, and implement Retrieval-Augmented Generation (RAG) to query your own documents. By the end of this course, you will have the skills to build, test, and deploy a fully functional, custom AI web application.
Domain-Specific AI Knowledge Assistant
- Dynamic Document Processing: A sidebar interface allowing users to upload new PDF or TXT files, which the app automatically chunks, embeds, and stores in the vector database.
- Context-Aware Chat UI: A modern chat interface built with Streamlit that maintains conversation history, allowing users to ask follow-up questions naturally.
- Strict Guardrails (Anti-Hallucination): System instructions designed so the AI politely declines to answer questions that fall outside the context of the uploaded documents.
Machine Learning Bootcamp
A beginner-friendly, 7-week project-based bootcamp designed to take you from Python basics to deploying your first Machine Learning model. Through hands-on practice, you will master essential data manipulation, build predictive algorithms, and develop an end-to-end, industry-ready application to kickstart your career in data science.
End-to-End Student Success Predictor
- Automated Data Pipeline: A preprocessing script that automatically cleans missing values, encodes categorical data (like course type or student background), and scales numerical inputs.
- Predictive Engine: A tuned machine learning classification model (e.g., Random Forest) specifically optimized for high Recall, ensuring that "at-risk" students are not missed.
- Interactive Web Dashboard: A user-friendly Streamlit interface featuring a sidebar where instructors can manually input a student's study hours, quiz scores, and login frequency to get an instant pass/fail probability.