How is a docker-compose.yaml structured? Explain it using a WordPress site with a MySQL database.
Under services: each container is described (image, volumes, networks, ports, environment, restart, depends_on); named volumes and networks are declared again at top level; docker compose up -d starts the whole stack.
services:
db:
image: mysql:5.7
container_name: mysql_database
volumes:
- db_data:/var/lib/mysql
restart: always
networks:
- custom_net
environment:
MYSQL_ROOT_PASSWORD: word@press
MYSQL_DATABASE: wordpress
MYSQL_USER: wordpress
MYSQL_PASSWORD: abc@123
wordpress:
depends_on:
- db
image: wordpress:latest
container_name: wp_frontend
volumes:
- wordpress_files:/var/www/html
networks:
- custom_net
ports:
- "8000:80"
restart: always
environment:
WORDPRESS_DB_HOST: db:3306
WORDPRESS_DB_USER: wordpress
WORDPRESS_DB_PASSWORD: abc@123
WORDPRESS_DB_NAME: wordpress
volumes:
wordpress_files:
db_data:
networks:
custom_net:
driver: bridge
| Key | Meaning |
|---|---|
image / container_name |
Which image to run, and a fixed container name |
volumes |
db_data persists MySQL's data folder, so posts survive recreating the container |
networks |
Both services join the user-defined bridge custom_net, so WordPress can reach the database by service name: WORDPRESS_DB_HOST: db:3306 |
ports |
Only WordPress is published (host 8000 to container 80); the database stays internal |
environment |
Configuration passed to the images (database name, users, passwords) |
restart: always |
Docker restarts the container whenever it stops unexpectedly |
depends_on |
WordPress is started after the db container |
Top-level volumes: and networks: declare the named volumes and user-defined networks, just as docker volume create and docker network create must come before you can use them. YAML indentation is significant. The old version: line at the top is obsolete and ignored in Compose V2.
Gotcha: plaintext passwords in the Compose file end up in version control and in docker inspect. Production setups use .env files kept out of git, or Docker secrets.
* Two services on custom_net, each with a named volume; only WordPress is published. *
Go deeper:
TechWorld with Nana: Ultimate Docker Compose Tutorial — building a multi-container stack step by step.
Docker Docs: Compose file reference — every top-level element and service attribute.
vsupalov.com: YAML for Docker Compose and Kubernetes — the YAML rules (indentation, lists, maps) that Compose files depend on.