Docker Exercises
Time to practise. Each exercise models one Docker concept in Python. The starter playground runs as-is and prints placeholder results so you can see the format. Replace the TODO parts, press ▶ Run, and compare your output with the "Expected" lines. The solutions are hidden below each exercise. Try for a few minutes first!
At the end there are two "real Docker" exercises to try on a machine with Docker installed.
| # | Exercise | Concept |
|---|---|---|
| 1 | Image reference parser | registries, repositories, tags |
| 2 | Which steps rebuild? | build cache |
| 3 | Port spec parser | publishing ports |
| 4 | .dockerignore matcher | build context |
| 5 | Compose start order | depends_on |
| 6 | Container environment | ENV, env_file, environment |
| 7 | Multi-stage image size | multi-stage builds |
| 8 | Restart decision | restart policies |
| 9 | Fix the Dockerfile | best practices (real Docker) |
| 10 | Two containers, one network | networks (real Docker) |
1. Image reference parser
Write split_reference(ref) that returns (registry, repository, tag). Default registry docker.io, default tag latest; single-name Docker Hub images live under library/. The first part is a registry only if it contains a . or a :.
Expected:
('docker.io', 'library/redis', 'latest')
('ghcr.io', 'acme/api', '1.2')
('registry.local:5000', 'tools', 'latest')def split_reference(ref):
# TODO: split off the registry, the tag, and add library/ when needed
return ("?", ref, "?")
print(split_reference("redis"))
print(split_reference("ghcr.io/acme/api:1.2"))
print(split_reference("registry.local:5000/tools"))('?', 'redis', '?')
('?', 'ghcr.io/acme/api:1.2', '?')
('?', 'registry.local:5000/tools', '?')
Show solution
def split_reference(ref):
registry, path = "docker.io", ref
first, _, rest = ref.partition("/")
if rest and ("." in first or ":" in first):
registry, path = first, rest
tag = "latest"
if ":" in path.rsplit("/", 1)[-1]: # only look for a tag after the last slash
path, tag = path.rsplit(":", 1)
if registry == "docker.io" and "/" not in path:
path = "library/" + path
return registry, path, tag2. Which steps rebuild?
Given the list of Dockerfile steps and the set of step indexes whose cache key changed, return the steps that will be rebuilt. Remember: once a step misses the cache, every later step is rebuilt too.
Expected:
['COPY . .', 'CMD ["python", "app.py"]']
['COPY requirements.txt .', 'RUN pip install -r requirements.txt', 'COPY . .', 'CMD ["python", "app.py"]']def rebuilt_steps(steps, changed):
# TODO
return [steps[i] for i in sorted(changed)]
steps = ["FROM python:3.12-slim", "WORKDIR /app", "COPY requirements.txt .",
"RUN pip install -r requirements.txt", "COPY . .", 'CMD ["python", "app.py"]']
print(rebuilt_steps(steps, {4})) # only the source code changed
print(rebuilt_steps(steps, {2, 4})) # requirements.txt changed too['COPY . .']
['COPY requirements.txt .', 'COPY . .']
Show solution
def rebuilt_steps(steps, changed):
first = min(changed)
return steps[first:]3. Port spec parser
Parse a -p value into a dictionary. Forms: HOST:CONTAINER, IP:HOST:CONTAINER, optionally followed by /udp or /tcp (default tcp, default IP 0.0.0.0).
Expected:
{'ip': '0.0.0.0', 'host': 8080, 'container': 80, 'proto': 'tcp'}
{'ip': '127.0.0.1', 'host': 5432, 'container': 5432, 'proto': 'tcp'}
{'ip': '0.0.0.0', 'host': 5353, 'container': 53, 'proto': 'udp'}def parse_port(spec):
# TODO
return {"ip": "?", "host": 0, "container": 0, "proto": "?"}
print(parse_port("8080:80"))
print(parse_port("127.0.0.1:5432:5432"))
print(parse_port("5353:53/udp")){'ip': '?', 'host': 0, 'container': 0, 'proto': '?'}
{'ip': '?', 'host': 0, 'container': 0, 'proto': '?'}
{'ip': '?', 'host': 0, 'container': 0, 'proto': '?'}
Show solution
def parse_port(spec):
spec, _, proto = spec.partition("/")
parts = spec.split(":")
ip = parts[0] if len(parts) == 3 else "0.0.0.0"
return {"ip": ip, "host": int(parts[-2]), "container": int(parts[-1]), "proto": proto or "tcp"}4. .dockerignore matcher
Write is_ignored(path, patterns). A pattern matches a path if fnmatchcase(path, pattern) is true or the path is inside a matching folder (path.startswith(pattern + "/")). Patterns starting with ! re-include. The last matching pattern wins. (This simplified version lets * cross /; real Docker doesn't.)
Expected:
.git/HEAD True
debug.log True
src/app.py False
secrets/key.pem True
secrets/README.md Falsefrom fnmatch import fnmatchcase
def is_ignored(path, patterns):
# TODO: loop over the patterns, the last match decides
return False
patterns = [".git", "*.log", "secrets/*", "!secrets/README.md"]
for path in [".git/HEAD", "debug.log", "src/app.py", "secrets/key.pem", "secrets/README.md"]:
print(path, is_ignored(path, patterns)).git/HEAD False
debug.log False
src/app.py False
secrets/key.pem False
secrets/README.md False
Show solution
from fnmatch import fnmatchcase
def is_ignored(path, patterns):
ignored = False
for p in patterns:
negate = p.startswith("!")
p = p.lstrip("!")
if fnmatchcase(path, p) or path.startswith(p + "/"):
ignored = not negate
return ignored5. Compose start order
deps maps each service to the services it depends on. Return a start order where every service comes after its dependencies. When several services are ready, take them alphabetically. Raise ValueError("cycle") if no service can start.
Expected: ['cache', 'db', 'api', 'web', 'worker']
def start_order(deps):
# TODO
return sorted(deps)
print(start_order({"web": ["api"], "api": ["db", "cache"], "db": [], "cache": [], "worker": ["db"]}))['api', 'cache', 'db', 'web', 'worker']
Show solution
def start_order(deps):
order, done = [], set()
while len(order) < len(deps):
ready = sorted(s for s, d in deps.items() if s not in done and set(d) <= done)
if not ready:
raise ValueError("cycle")
order.append(ready[0])
done.add(ready[0])
return order6. Container environment
Combine the image's ENV, a list of env_file dictionaries and the environment: dictionary into the final container environment (later sources win).
Expected: {'PORT': '9000', 'DEBUG': '1', 'TZ': 'UTC'}
def container_env(image_env, env_files, environment):
# TODO
return dict(image_env)
print(container_env({"PORT": "8000", "DEBUG": "0"}, [{"DEBUG": "1", "TZ": "UTC"}], {"PORT": "9000"})){'PORT': '8000', 'DEBUG': '0'}
Show solution
def container_env(image_env, env_files, environment):
env = dict(image_env)
for f in env_files:
env.update(f)
env.update(environment)
return env7. Multi-stage image size
Each stage has a base size, files it adds itself and files it copies from other stages (all in MB). Compute the size of the image you get when the build stops at a given stage.
Expected: 1526 92
def final_size(stages, final):
# TODO: base + own additions + copied files of that stage only
return 0
stages = {
"build": {"base": 1100, "adds": {"node_modules": 420, "dist": 6}},
"runtime": {"base": 48, "copies": {"dist": 6, "node_modules (prod)": 38}},
}
print(final_size(stages, "build"), final_size(stages, "runtime"))0 0
Show solution
def final_size(stages, final):
stage = stages[final]
return stage["base"] + sum(stage.get("adds", {}).values()) + sum(stage.get("copies", {}).values())8. Restart decision
Write should_restart(policy, exit_code, stopped_by_user, retries=0, max_retries=None) for the policies no, on-failure, always and unless-stopped. A container stopped by the user is never restarted right away.
Expected: False True False False True False (one per line).
def should_restart(policy, exit_code, stopped_by_user, retries=0, max_retries=None):
# TODO
return False
print(should_restart("no", 1, False))
print(should_restart("on-failure", 1, False))
print(should_restart("on-failure", 0, False))
print(should_restart("on-failure", 1, False, retries=3, max_retries=3))
print(should_restart("always", 0, False))
print(should_restart("unless-stopped", 0, True))False
False
False
False
False
False
Show solution
def should_restart(policy, exit_code, stopped_by_user, retries=0, max_retries=None):
if stopped_by_user:
return False
if policy in ("always", "unless-stopped"):
return True
if policy == "on-failure":
return exit_code != 0 and (max_retries is None or retries < max_retries)
return False9. Fix the Dockerfile (real Docker)
This Dockerfile works, but it has at least seven problems. Find them, then rewrite it.
FROM node:latest
COPY . /app
RUN cd /app && npm install
ENV API_KEY=sk-live-1234
EXPOSE 3000
CMD npm startShow solution
Problems: an unpinned latest base; a full (not slim/alpine) image; all source copied before installing dependencies (every code change re-installs); cd instead of WORKDIR; npm install instead of a reproducible npm ci with production dependencies only; a secret in ENV; shell-form CMD (no signals, and npm as PID 1); runs as root; no .dockerignore (so node_modules and .git are copied).
FROM node:22-alpine
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci --omit=dev
COPY --chown=node:node . .
USER node
EXPOSE 3000
CMD ["node", "server.js"]Plus a .dockerignore with node_modules, .git and .env, and API_KEY supplied at run time as a secret.
10. Two containers, one network (real Docker)
Without Compose, start Redis and a client container so that the client can reach Redis by name, and no port is published to the host. Then prove it with redis-cli ping.
Show solution
docker network create practice-net
docker run -d --name cache --network practice-net redis:8
docker run --rm --network practice-net redis:8 redis-cli -h cache ping
docker rm -f cache && docker network rm practice-netSample output of the third command:
PONGOn the default bridge network the name cache would not resolve. A user-defined network provides DNS.
Test yourself
In exercise 2, step 2 (COPY requirements.txt .) misses the cache. Is the FROM step (index 0) rebuilt?
- Yes, everything is rebuilt
- No, only the step that missed and everything after it
- Only if FROM uses latest
- Only the FROM step
In exercise 10, why does the client container reach Redis as cache?
- Because port 6379 is published
- Both containers are on the same user-defined network, which provides DNS by container name
- Redis registers itself with Docker Hub
- Because of the default bridge network
Which change in exercise 9 makes code edits stop re-installing all npm packages?
- Using USER node
- Copying package.json and package-lock.json and running npm ci before copying the rest of the source
- Using EXPOSE
- Switching to Alpine