TExcelTAD
Home › Docker Compose › Compose Exercises

Compose Exercises

Time to practise what the course covered. There are two kinds of exercises:

  • Compose files (compose playgrounds): the starter file is broken or incomplete, and its output shows what Compose currently makes of it. Fix the file so docker compose config (or docker stack config) produces what the exercise asks for. On this site the saved output belongs to the starter; check your solution against the hidden one, or run it on a machine with Docker.
  • Python models: the starter runs as-is and prints placeholder results. Replace the TODO parts, press ▶ Run, and compare with the "Expected" lines.

Try each one for a few minutes before opening the solution.

# Exercise Concept
1 The missing volume named volumes
2 Which volume name? project prefix, name:, external
3 Tiers networks, internal
4 Predict the merge override files
5 No debug port in production !override, !reset
6 Enabled services profiles
7 Project name precedence project names
8 DRY logging x- fragments, anchors
9 Watch dispatcher develop & watch
10 Password as a secret configs & secrets
11 Make it stack-ready Compose → Swarm

1. The missing volume

The database should keep its data in a named volume called pgdata. Compose refuses the file. Fix it so docker compose config succeeds and the volume is named demo_pgdata.

compose · try it yourself
services:
  db:
    image: postgres:17
    environment:
      POSTGRES_PASSWORD: example
    volumes:
      - pgdata:/var/lib/postgresql/data
service "db" refers to undefined volume pgdata: invalid compose project
Show solution

Named volumes must be declared at the top level:

yaml
services:
  db:
    image: postgres:17
    environment:
      POSTGRES_PASSWORD: example
    volumes:
      - pgdata:/var/lib/postgresql/data

volumes:
  pgdata:

The rendered file then ends with volumes: pgdata: name: demo_pgdata.

2. Which volume name?

Write volume_name(project, key, options) that returns the Docker name of a top-level volume: options["name"] if set, otherwise <project>_<key>. External volumes keep their name (or the key if there's no name) and get (external) appended.

Expected:

text
shop_pgdata
acme-media
legacy_data (external)
certs (external)
python · try it yourself
def volume_name(project, key, options):
    # TODO
    return "?"

print(volume_name("shop", "pgdata", {}))
print(volume_name("shop", "media", {"name": "acme-media"}))
print(volume_name("shop", "old", {"external": True, "name": "legacy_data"}))
print(volume_name("shop", "certs", {"external": True}))
?
?
?
?
Show solution
python
def volume_name(project, key, options):
    if options.get("external"):
        return f"{options.get('name', key)} (external)"
    return options.get("name", f"{project}_{key}")

3. Tiers

proxy should only be on a frontend network, db only on a backend network that has no internet access, and api on both. Right now everything shares the default network. Change the file so docker compose config --networks lists backend and frontend (and no default), and backend is internal.

compose · try it yourself
# $ docker compose config --networks
services:
  proxy:
    image: nginx:1.29
    ports: ["80:80"]
  api:
    image: ghcr.io/acme/api:3.1
  db:
    image: postgres:17
default
Show solution
yaml
services:
  proxy:
    image: nginx:1.29
    ports: ["80:80"]
    networks: [frontend]
  api:
    image: ghcr.io/acme/api:3.1
    networks: [frontend, backend]
  db:
    image: postgres:17
    networks: [backend]

networks:
  frontend:
  backend:
    internal: true

Because every service lists its networks, nobody uses default and Compose doesn't create it.

4. Predict the merge

Write merge(base, override) for a service, following Compose's rules: image and command are replaced, environment is merged by key, ports are concatenated without duplicates (keep the order: base first).

Expected:

text
image       api:3.1
command     ['flask', 'run', '--debug']
environment {'LOG_LEVEL': 'debug', 'WORKERS': '4', 'FLASK_DEBUG': '1'}
ports       ['8000:8000', '5678:5678']
python · try it yourself
def merge(base, override):
    # TODO: start from base, then apply each key of override with the right rule
    return dict(base)

base = {"image": "api:3.1", "command": ["gunicorn", "app:app"],
        "environment": {"LOG_LEVEL": "info", "WORKERS": "4"}, "ports": ["8000:8000"]}
override = {"command": ["flask", "run", "--debug"],
            "environment": {"LOG_LEVEL": "debug", "FLASK_DEBUG": "1"}, "ports": ["5678:5678", "8000:8000"]}

for key, value in merge(base, override).items():
    print(f"{key:<11} {value}")
image       api:3.1
command     ['gunicorn', 'app:app']
environment {'LOG_LEVEL': 'info', 'WORKERS': '4'}
ports       ['8000:8000']
Show solution
python
def merge(base, override):
    out = dict(base)
    for key, value in override.items():
        if key == "environment":
            out[key] = {**base.get(key, {}), **value}
        elif key == "ports":
            out[key] = list(dict.fromkeys(base.get(key, []) + value))
        else:
            out[key] = value
    return out

5. No debug port in production

The base file publishes the debugger port 5678 and sets DEBUG. Edit only compose.prod.yaml so that the merged production config publishes just port 8000 and has no DEBUG variable (but keeps LOG_LEVEL).

compose · try it yourself
# $ docker compose -f compose.yaml -f compose.prod.yaml config
services:
  api:
    image: ghcr.io/acme/api:3.1
    ports: ["8000:8000", "5678:5678"]
    environment:
      DEBUG: "1"
      LOG_LEVEL: info

# --- compose.prod.yaml
services:
  api:
    ports: ["8000:8000"]
    environment:
      LOG_LEVEL: warn
name: demo
services:
  api:
    environment:
      DEBUG: "1"
      LOG_LEVEL: warn
    image: ghcr.io/acme/api:3.1
    networks:
      default: null
    ports:
      - mode: ingress
        target: 8000
        published: "8000"
        protocol: tcp
      - mode: ingress
        target: 5678
        published: "5678"
        protocol: tcp
networks:
  default:
    name: demo_default
Show solution

Plain values can only add or change. Use the merge tags:

yaml
# compose.prod.yaml
services:
  api:
    ports: !override ["8000:8000"]
    environment:
      DEBUG: !reset null
      LOG_LEVEL: warn

6. Enabled services

Write enabled(services, active): a service without profiles is always enabled; a service with profiles is enabled if any of them is in active; "*" in active enables everything. Return the names sorted.

Expected:

text
['api', 'db']
['adminer', 'api', 'db', 'mailpit']
['adminer', 'api', 'db', 'migrate']
['adminer', 'api', 'db', 'mailpit', 'migrate']
python · try it yourself
services = {
    "api": [], "db": [],
    "adminer": ["debug", "tools"], "mailpit": ["debug"], "migrate": ["tools"],
}

def enabled(services, active):
    # TODO
    return sorted(name for name, profiles in services.items() if not profiles)

print(enabled(services, []))
print(enabled(services, ["debug"]))
print(enabled(services, ["tools"]))
print(enabled(services, ["*"]))
['api', 'db']
['api', 'db']
['api', 'db']
['api', 'db']
Show solution
python
def enabled(services, active):
    on = []
    for name, profiles in services.items():
        if not profiles or "*" in active or set(profiles) & set(active):
            on.append(name)
    return sorted(on)

7. Project name precedence

Write project_name(flag, env, file_name, directory): the first of -p flag, COMPOSE_PROJECT_NAME, top-level name: and the directory that is not None wins. Names that don't come from the flag are normalised: lower-case, keep only a-z 0-9 _ -.

Expected:

text
staging
shop-dev
shop
myshop
python · try it yourself
import re

def project_name(flag=None, env=None, file_name=None, directory="demo"):
    # TODO
    return directory

print(project_name(flag="staging", env="shop-dev", file_name="shop"))
print(project_name(env="shop-dev", file_name="shop"))
print(project_name(file_name="shop"))
print(project_name(directory="My Shop"))
demo
demo
demo
My Shop
Show solution
python
def project_name(flag=None, env=None, file_name=None, directory="demo"):
    if flag is not None:
        return flag
    for candidate in (env, file_name, directory):
        if candidate is not None:
            return re.sub(r"[^a-z0-9_-]", "", candidate.lower())

8. DRY logging

Three services repeat the same logging block. Move it into an x-logging extension field with an anchor and use an alias in each service. The rendered services must stay exactly the same (only an x-logging key is added at the end).

compose · try it yourself
services:
  web:
    image: ghcr.io/acme/web:2.0
    logging:
      driver: local
      options: {max-size: 10m, max-file: "3"}
  api:
    image: ghcr.io/acme/api:3.1
    logging:
      driver: local
      options: {max-size: 10m, max-file: "3"}
  worker:
    image: ghcr.io/acme/api:3.1
    command: ["celery", "-A", "app", "worker"]
    logging:
      driver: local
      options: {max-size: 10m, max-file: "3"}
name: demo
services:
  api:
    image: ghcr.io/acme/api:3.1
    logging:
      driver: local
      options:
        max-file: "3"
        max-size: 10m
    networks:
      default: null
  web:
    image: ghcr.io/acme/web:2.0
    logging:
      driver: local
      options:
        max-file: "3"
        max-size: 10m
    networks:
      default: null
  worker:
    command:
      - celery
      - -A
      - app
      - worker
    image: ghcr.io/acme/api:3.1
    logging:
      driver: local
      options:
        max-file: "3"
        max-size: 10m
    networks:
      default: null
networks:
  default:
    name: demo_default
Show solution
yaml
x-logging: &logging
  driver: local
  options: {max-size: 10m, max-file: "3"}

services:
  web:
    image: ghcr.io/acme/web:2.0
    logging: *logging
  api:
    image: ghcr.io/acme/api:3.1
    logging: *logging
  worker:
    image: ghcr.io/acme/api:3.1
    command: ["celery", "-A", "app", "worker"]
    logging: *logging

9. Watch dispatcher

Write action_for(path, rules): return the action of the first rule whose path equals the file or is a parent folder of it, or "ignored" if none matches. Then batch_action(paths, rules) returns the most expensive action of a batch (rebuild > sync+restart > sync; ignore "ignored"), or "nothing".

Expected:

text
sync
rebuild
ignored
sync+restart
rebuild
nothing
python · try it yourself
rules = [
    {"path": "src", "action": "sync"},
    {"path": "config/nginx.conf", "action": "sync+restart"},
    {"path": "package.json", "action": "rebuild"},
]
COST = {"sync": 1, "sync+restart": 2, "rebuild": 3}

def action_for(path, rules):
    # TODO
    return "ignored"

def batch_action(paths, rules):
    # TODO
    return "nothing"

print(action_for("src/app/main.js", rules))
print(action_for("package.json", rules))
print(action_for("srcs/old.js", rules))
print(batch_action(["src/a.js", "config/nginx.conf"], rules))
print(batch_action(["src/a.js", "package.json", "README.md"], rules))
print(batch_action(["README.md"], rules))
ignored
ignored
ignored
nothing
nothing
nothing
Show solution
python
def action_for(path, rules):
    for rule in rules:
        if path == rule["path"] or path.startswith(rule["path"] + "/"):
            return rule["action"]
    return "ignored"

def batch_action(paths, rules):
    actions = [a for a in (action_for(p, rules) for p in paths) if a != "ignored"]
    return max(actions, key=COST.get) if actions else "nothing"

Note srcs/old.js: a plain startswith("src") would wrongly match it, which is why the solution checks for src/.

10. Password as a secret

The API gets its database password from an environment variable. Change the file so that the password comes from a secret read from ./db_password.txt, mounted at /run/secrets/db_password, and the app is told where to find it with DB_PASSWORD_FILE. No password may remain in environment.

compose · try it yourself
services:
  api:
    image: ghcr.io/acme/api:3.1
    environment:
      DB_USER: app
      DB_PASSWORD: ${DB_PASSWORD:-changeme}

# --- db_password.txt
correct-horse-battery-staple
name: demo
services:
  api:
    environment:
      DB_PASSWORD: changeme
      DB_USER: app
    image: ghcr.io/acme/api:3.1
    networks:
      default: null
networks:
  default:
    name: demo_default
Show solution
yaml
services:
  api:
    image: ghcr.io/acme/api:3.1
    environment:
      DB_USER: app
      DB_PASSWORD_FILE: /run/secrets/db_password
    secrets:
      - db_password

secrets:
  db_password:
    file: ./db_password.txt

The short form - db_password already targets /run/secrets/db_password. The rendered file shows only the secret's source file, never its content.

11. Make it stack-ready

This file works with docker compose, but docker stack config rejects it. Fix it so docker stack config -c compose.yaml succeeds, without losing the 3 replicas, and with the adminer debugging tool removed. (Hint: there's more than one problem; fix them one at a time and re-check.)

compose · try it yourself
# $ docker stack config -c compose.yaml
name: shop
services:
  api:
    image: ghcr.io/acme/api:3.1
    depends_on:
      db: {condition: service_healthy}
    deploy:
      replicas: 3
  db:
    image: postgres:17
  adminer:
    image: adminer:5
    profiles: [debug]
services.api.depends_on: must be a list
Show solution

Swarm rejects the top-level name, depends_on with conditions and profiles:

yaml
services:
  api:
    image: ghcr.io/acme/api:3.1
    depends_on: [db]          # accepted (but ignored by Swarm); or remove it
    deploy:
      replicas: 3
  db:
    image: postgres:17

The stack name comes from the deploy command instead: docker stack deploy -c compose.yaml shop.

Next: put it all together in the Mini Project: Full-Stack App.

Test yourself

Which command shows the final configuration after merging compose.yaml and compose.prod.yaml?

  1. docker compose -f compose.yaml -f compose.prod.yaml config
  2. docker compose merge
  3. docker compose up --dry-run only
  4. docker stack config

Which tool reuses settings inside one file without any Compose-specific feature?

  1. extends
  2. include
  3. YAML anchors and aliases
  4. profiles