D: 🚀 Introduction
Docker Compose is a powerful tool that simplifies the process of running multi-container Docker applications. If you’re new to Docker, this guide will walk you through the basics of Docker Compose with clear examples and best practices.
🔹 What is Docker Compose?
Docker Compose is a YAML-based configuration tool that allows you to define and manage multiple containers as a single service. Instead of running multiple docker run
commands, you can define everything in a single docker-compose.yml
file.
✅ Why Use Docker Compose?
✔ Simplifies container orchestration
✔ Easy to share and reproduce environments
✔ Automates service dependencies
🔹 Step 1: Install Docker & Docker Compose
Before using Docker Compose, ensure you have:
- Docker Engine installed (Download Docker)
- Docker Compose (usually included with Docker Desktop)
Verify installation:
docker --version
docker-compose --version
🔹 Step 2: Create a docker-compose.yml
File
This file defines services, networks, and volumes.
📂 Example: Simple Web App with Nginx & MySQL
version: '3.8' # Compose file version
services:
web:
image: nginx:latest
ports:
- "80:80"
depends_on:
- db
db:
image: mysql:5.7
environment:
MYSQL_ROOT_PASSWORD: example
MYSQL_DATABASE: mydb
volumes:
- db_data:/var/lib/mysql
volumes:
db_data:
📌 Key Components:
services
: Defines containers (e.g.,web
,db
)ports
: Maps host port to container portvolumes
: Persistent storage for databasesdepends_on
: Ensuresdb
starts beforeweb
🔹 Step 3: Run Docker Compose
Navigate to the directory containing docker-compose.yml
and run:
docker-compose up -d # Runs in detached mode
✅ Common Commands: | Command | Description |
---|---|---|
docker-compose up |
Starts containers | |
docker-compose down |
Stops & removes containers | |
docker-compose ps |
Lists running services | |
docker-compose logs |
Shows container logs |
🔹 Step 4: Customizing with Environment Variables
Instead of hardcoding values, use .env
files:
📄 .env
File Example
MYSQL_ROOT_PASSWORD=securepassword
MYSQL_DATABASE=app_db
📄 Updated docker-compose.yml
db:
image: mysql:5.7
environment:
MYSQL_ROOT_PASSWORD: ${MYSQL_ROOT_PASSWORD}
MYSQL_DATABASE: ${MYSQL_DATABASE}
🔹 Step 5: Scaling Services
Need multiple instances? Use scale
:
docker-compose up -d --scale web=3 # Runs 3 web containers
🔹 Troubleshooting Tips 🛠️
🔸 Issue: Containers fail to start
✅ Fix: Check logs with docker-compose logs [service]
🔸 Issue: Port conflicts
✅ Fix: Change host port (e.g., 8080:80
instead of 80:80
)
🔸 Issue: Volume permissions
✅ Fix: Use named volumes or adjust permissions in Dockerfile
🔹 Conclusion 🎉
Docker Compose makes managing multi-container apps effortless! 🚀
✔ Define services in YAML
✔ Automate dependencies
✔ Scale easily
💡 Next Steps:
- Explore advanced features like
networks
andhealthchecks
- Try deploying with
docker-compose.prod.yml
for production
Happy Dockering! 🐳
📢 Need help? Drop a comment below! 👇