CodeBlanks Logo Icon CodeBlanks

Challenge - Compose

Combine web and database with compose.

Challenge: a Compose stack

WordPress + MySQL is the classic Compose example. In this challenge you'll define a two-service stack in a single file: the database will persist in a named volume, WordPress will connect to the database by service name, and only WordPress will publish a port.

services:
  db:
    image: mysql:8
    environment:
      MYSQL_ROOT_PASSWORD: gizli
      MYSQL_DATABASE: wp
    volumes:
      - dbveri:/var/lib/mysql
  wordpress:
    image: wordpress:6
    ports:
      - "8080:80"
    environment:
      WORDPRESS_DB_HOST: db
      WORDPRESS_DB_PASSWORD: gizli
    depends_on:
      - db
volumes:
  dbveri:

Practice compose.yaml

Write the compose.yaml from the card: the db service (mysql:8, MYSQL_ROOT_PASSWORD: gizli, dbveri:/var/lib/mysql); the wordpress service (wordpress:6, "8080:80", WORDPRESS_DB_HOST: db, db under depends_on); dbveri: under a top-level volumes.

Starter code

terminal
# compose.yaml
# buraya yaz

Sample solution

terminal
# compose.yaml
services:
  db:
    image: mysql:8
    environment:
      MYSQL_ROOT_PASSWORD: gizli
    volumes:
      - dbveri:/var/lib/mysql
  wordpress:
    image: wordpress:6
    ports:
      - "8080:80"
    environment:
      WORDPRESS_DB_HOST: db
    depends_on:
      - db

volumes:
  dbveri:

Expected output

[+] Running 3/3
 ✔ Volume "proje_dbveri"  Created
 ✔ Container proje-db-1  Started
 ✔ Container proje-wordpress-1  Started

Practice Manage the stack

Write three commands: start the stack in the background; show the status of the services; follow the logs of the wordpress service live.

Starter code

terminal
# buraya yaz

Sample solution

terminal
docker compose up -d
docker compose ps
docker compose logs -f wordpress

Expected output

[+] Running 2/2
 ✔ Container proje-db-1  Started
 ✔ Container proje-wordpress-1  Started
NAME                 SERVICE     STATUS         PORTS
proje-db-1           db          Up 5 seconds   3306/tcp, 33060/tcp
proje-wordpress-1    wordpress   Up 4 seconds   0.0.0.0:8080->80/tcp

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Why does WORDPRESS_DB_HOST take the value db?

  • db is an IP address
  • It's MySQL's default name
  • It was chosen arbitrarily
  • On the Compose network, the service name is the DNS name Correct answer

Explanation: Containers find each other by name on the shared default network.

2 Start the stack in the background.

Question
docker compose up ____
Answer
docker compose up -d

Explanation: -d (detached) releases the terminal.

3 Match.

Term Meaning
dbveri Persistent MySQL data
8080:80 Only WordPress published
depends_on Start order
WORDPRESS_DB_HOST: db Connection by service name

All lessons in Beginner