Skip to content
devops.academy

Exercises — Module 5: Docker

Environment: Docker installed on your Linux VM or laptop (Docker Desktop fine). Keep a scratch dir ~/docker-drills. Cleanup habit after every session: docker system df then prune what you understand.


Part A — Warm-Up Drills

Drill 1 — Lifecycle reps (do until fluid). Pull nginx:1.25; run detached named web publishing 8080→80; curl it; view logs; exec a shell inside and cat /etc/nginx/nginx.conf; stop; start again; remove. Now do the whole cycle in under 60 seconds. ✓ You never had to look up a flag.

Drill 2 — Image vs container. Run three containers from the same nginx image with different names. Inside one, touch /tmp/marker. Check the other two — is it there? Remove that container, run a new one — marker? ✓ Explain out loud: image = template, container = instance, container FS = ephemeral.

Drill 3 — Inspect everything. For a running container, extract using docker inspect (+ --format or jq): its IP address, its restart policy, its env vars, the image digest it runs. For the image: layer count via docker history. ✓ Four one-liners saved in your notes.

Drill 4 — Exit-code detective. Run: docker run --name a alpine sh -c 'exit 3'; docker run --name b --memory 6m python:3.12-slim python -c "x='a'*10**9"; check both with docker inspect --format '{{.State.ExitCode}} {{.State.OOMKilled}}'. ✓ You saw 3 and 137/OOMKilled=true — and can now decode both in production.

Drill 5 — Port & bind sanity. Run nginx with -p 127.0.0.1:8081:80 vs -p 8082:80. From another machine, which is reachable? Confirm with ss -tulpn on the host and connect it to Module 4's bind-address lesson. ✓ One-sentence rule for when to use each.


Part B — Guided Labs

Lab 1 — Dockerize a Flask App, Then Do It Right (90 min)

  1. Write a 20-line Flask app: GET / returns hostname + a counter, GET /health returns ok. Run it locally in a venv first.
  2. Naive Dockerfile v1: FROM python:3.12, COPY . ., RUN pip install -r requirements.txt, CMD python app.py. Build, run, works. Note the image size.
  3. v2 — layer caching: reorder to COPY requirements first. Prove it: change one line of app code, rebuild, and time it vs a requirements change rebuild. Record both times. ✓ Code-only rebuild skips pip entirely (watch for CACHED lines).
  4. v3 — slim + non-root + .dockerignore: switch to -slim, add a user, add .dockerignore (.git, .venv, pycache). Compare sizes v1 → v3.
  5. v4 — gunicorn + HEALTHCHECK. docker ps should show (healthy). ✓ You have four Dockerfiles in Git showing the evolution — great portfolio material with a README table of sizes/build times.

Lab 2 — Multi-Stage Shrink Ray (45 min)

  1. Take any Go or Node sample app (Go's net/http hello world is perfect).
  2. Single-stage build first; note size (~1GB for Go toolchain images).
  3. Convert to multi-stage (builder → alpine or scratch). Note size (~10–20MB).
  4. Run dive on both images; find in the single-stage image at least 3 categories of files the app never needs at runtime. ✓ You can justify multi-stage in one sentence with your own numbers.

Lab 3 — Networks & Cross-Container DNS (45 min)

  1. Create network appnet. Run postgres:16 as db on it (env: POSTGRES_PASSWORD) — deliberately WITHOUT -p.
  2. Run alpine interactively on the same network; ping db; install postgresql-client and connect via hostname db. ✓ Name-based discovery worked with zero configuration.
  3. From the HOST, try psql -h localhost — fails. Explain why this failure is a security feature.
  4. Run a second alpine on the DEFAULT bridge network; try ping db — fails. What's different about user-defined networks?
  5. docker network inspect appnet — find both containers' IPs and relate the subnet to Module 4's private ranges.

Lab 4 — Volumes & the Data-Loss Demo (30 min)

  1. Run Postgres WITHOUT a volume; create a table with a row; docker rm -f it; run again — data gone. Feel it once, on purpose.
  2. Repeat WITH -v pgdata:/var/lib/postgresql/data; destroy and recreate; data survives.
  3. Bind-mount version of your Flask app (-v $(pwd):/app) with flask debug/reload — edit code on the host, watch it live-reload in the container. ✓ You can state when to use named volume vs bind mount vs nothing.

Lab 5 — Compose the Full Stack (90 min)

  1. Compose file: your Flask api (build:) + postgres (volume, healthcheck pg_isready) + redis. API endpoint increments a Redis counter and writes a row to Postgres.
  2. First run WITHOUT the healthcheck condition — restart the stack repeatedly until you catch the "connection refused" race (add a sleep 5 to postgres's entrypoint via command override to force it if needed). Document the failure.
  3. Fix with depends_on: condition: service_healthy AND a nc -z wait entrypoint (both belts).
  4. Drills: compose logs -f api while curling; compose exec db psql to verify rows; scale api to 3 (--scale api=3 — remove the host port or use a range) and curl through an added nginx service round-robining them. ✓ docker compose down && up -d from cold to healthy with zero manual steps — the reproducibility bar.

Lab 6 — Registry Round Trip (30 min)

  1. Tag your api image properly (yourname/counter-api:v0.1.0), push to Docker Hub.
  2. On a DIFFERENT machine (or after docker rmi locally), pull and run it with the compose stack.
  3. Push a v0.1.1 with a visible change; on the other machine pull ONLY by changing the tag in compose. ✓ You experienced image-as-artifact deployment — the core of every pipeline to come.

Part C — Challenges

C1 — Debug an unknown image. docker run -d --name mystery nginx:1.25 then, using only exec/inspect/logs: what user does the main process run as? What config file does it load? What signal does docker stop send it and how does nginx react (check STOPSIGNAL / docs)?

C2 — Build-arg versioning. Make your Flask / endpoint report an APP_VERSION baked at build time via --build-arg. Build v1 and v2 images from the same code, prove each reports correctly.

C3 — Entrypoint vs CMD. Build an image where docker run img prints usage, docker run img 5 sleeps 5s then exits 0 — using ENTRYPOINT+CMD interplay. Then override the entrypoint at runtime to get a shell.

C4 — The 100MB cut. Take any bloated public Dockerfile (search "awful dockerfile examples" or use your own v1) and cut ≥60% of its size without changing behavior. Document each technique used.

C5 — Compose profiles/overrides. One compose project where docker compose up starts dev mode (bind mount, debug) and docker compose -f compose.yml -f compose.prod.yml up starts prod mode (built image, gunicorn, no mounts).

C6 — Log driver taste. Run a chatty container with --log-opt max-size=10k --log-opt max-file=3; generate logs; find the rotated files under /var/lib/docker and explain why unbounded container logs are a classic disk-full cause (Module 2 callback!).


Part D — Break & Fix Scenarios

D1 — CrashLoop preview. Make your app crash on boot when DATABASE_URL is unset; run it without the env var under --restart unless-stopped. Watch docker ps cycle. Diagnose from docker logs alone, fix, and note this exact pattern returns as CrashLoopBackOff in K8s.

D2 — Port conflict. Two containers publishing the same host port — read the error, find the squatter (docker ps + ss), resolve two different ways.

D3 — The full disk (docker edition). Check docker system df. Build 20 junk image layers in a loop (script it!). Watch reclaimable space grow; prune safely; explain the difference between image prune and image prune -a.

D4 — OOM hunt. Run your api with --memory 64m under load (ab from Module 2's toolkit); catch the 137; fix by either raising the limit or finding the memory hog. Document like an incident: symptom → evidence → fix.

D5 — Wrong architecture. If you have access to both ARM and x86 (or use --platform linux/arm64 pull on x86): run a mismatched image and capture the exec format error. Fix with buildx multi-platform build; verify with docker manifest inspect.


Part E — Interview Rehearsal (out loud)

  1. Container vs VM — and what three kernel features make containers possible?
  2. Walk me through what happens layer-by-layer when you docker build this file, and why order matters.
  3. A container exits with 137. Investigate.
  4. How do two containers talk to each other? How does the outside world reach one?
  5. Multi-stage builds — why, and roughly how?
  6. Where should database data live and why? What happens without it?
  7. Why is :latest in production a mistake — give two concrete failure stories.

Done when

Drill 1 under 60s, Lab 1's size/time table exists in Git, Lab 5 passes the cold-start bar, and D1–D4 were solved from evidence, not memory.