Compose Exercises
Time to practise what the course covered. There are two kinds of exercises:
- Compose files (
composeplaygrounds): the starter file is broken or incomplete, and its output shows what Compose currently makes of it. Fix the file sodocker compose config(ordocker 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
TODOparts, 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.
services:
db:
image: postgres:17
environment:
POSTGRES_PASSWORD: example
volumes:
- pgdata:/var/lib/postgresql/dataservice "db" refers to undefined volume pgdata: invalid compose project
Show solution
Named volumes must be declared at the top level:
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:
shop_pgdata
acme-media
legacy_data (external)
certs (external)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
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.
# $ docker compose config --networks
services:
proxy:
image: nginx:1.29
ports: ["80:80"]
api:
image: ghcr.io/acme/api:3.1
db:
image: postgres:17default
Show solution
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: trueBecause 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:
image api:3.1
command ['flask', 'run', '--debug']
environment {'LOG_LEVEL': 'debug', 'WORKERS': '4', 'FLASK_DEBUG': '1'}
ports ['8000:8000', '5678:5678']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
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 out5. 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).
# $ 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: warnname: 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:
# compose.prod.yaml
services:
api:
ports: !override ["8000:8000"]
environment:
DEBUG: !reset null
LOG_LEVEL: warn6. 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:
['api', 'db']
['adminer', 'api', 'db', 'mailpit']
['adminer', 'api', 'db', 'migrate']
['adminer', 'api', 'db', 'mailpit', 'migrate']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
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:
staging
shop-dev
shop
myshopimport 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
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).
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
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: *logging9. 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:
sync
rebuild
ignored
sync+restart
rebuild
nothingrules = [
{"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
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.
services:
api:
image: ghcr.io/acme/api:3.1
environment:
DB_USER: app
DB_PASSWORD: ${DB_PASSWORD:-changeme}
# --- db_password.txt
correct-horse-battery-staplename: 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
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.txtThe 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.)
# $ 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:
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:17The 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?
- docker compose -f compose.yaml -f compose.prod.yaml config
- docker compose merge
- docker compose up --dry-run only
- docker stack config
Which tool reuses settings inside one file without any Compose-specific feature?
- extends
- include
- YAML anchors and aliases
- profiles