D: Docker Compose is a powerful tool that simplifies managing multi-container Docker applications. At its core lies the docker-compose.yml file, written in YAML format. Let’s break down its structure with clear examples!
π 1. What is Docker Compose?
Docker Compose allows you to define and run multi-container applications using a single configuration file (docker-compose.yml
). Instead of running multiple docker run
commands, you declare services, networks, and volumes in YAML.
Example Use Case:
- Running a web app with a frontend, backend, and database in one command.
π 2. Basic YAML Structure
A docker-compose.yml
file typically has these main sections:
version: "3.8" # Compose file version
services: # Define your containers
web: # Service name
image: nginx:latest
ports:
- "80:80"
db:
image: postgres:13
environment:
POSTGRES_PASSWORD: example
volumes: # Persistent data storage
db_data:
π 3. Key Components Explained
β version
- Specifies the Compose file format version.
- Latest stable version:
"3.8"
(as of 2023).
β‘ services
Each service represents a container. Common configurations:
β image
β Pulls from Docker Hub (e.g., nginx:latest
).
β build
β Builds from a local Dockerfile
.
β ports
β Maps host:container ports ("8080:80"
).
β environment
β Sets env variables (POSTGRES_PASSWORD: "secret"
).
β depends_on
β Defines startup order.
Example:
services:
app:
build: .
ports:
- "5000:5000"
depends_on:
- redis
redis:
image: redis
β’ volumes
Persists data beyond container lifecycle.
volumes:
db_data: # Named volume
./app-data:/data # Bind mount (host:container)
β£ networks
(Optional)
Creates custom networks for secure communication.
networks:
app_network:
driver: bridge
π 4. Full Example: WordPress + MySQL
version: "3.8"
services:
wordpress:
image: wordpress:latest
ports:
- "8000:80"
environment:
WORDPRESS_DB_HOST: db
WORDPRESS_DB_USER: wpuser
WORDPRESS_DB_PASSWORD: wppass
depends_on:
- db
volumes:
- wp_data:/var/www/html
db:
image: mysql:5.7
environment:
MYSQL_ROOT_PASSWORD: rootpass
MYSQL_DATABASE: wpdb
MYSQL_USER: wpuser
MYSQL_PASSWORD: wppass
volumes:
- db_data:/var/lib/mysql
volumes:
wp_data:
db_data:
How to Run?
docker-compose up -d # Detached mode
π 5. Pro Tips
β
Use .env
for secrets β Avoid hardcoding passwords.
β
Override settings β Use docker-compose.override.yml
.
β
Scale services β docker-compose up --scale web=3
.
π― Conclusion
Docker Compose YAML is easy yet powerful! Start with simple services, then expand to networks, volumes, and environment variables.
Next Steps:
πΉ Try modifying the WordPress example.
πΉ Explore docker-compose logs
for debugging.
πΉ Check the official docs for advanced features.
Happy Dockering! ππ