Skip to content
Hands-on IT IT Drills

Appendix B: Final Exam

Goal: Apply all four parts of the book without instructions: eight practical exercises and a short knowledge section. · Duration: approx. 150 min · Prerequisite: Day 15

Rules of Play

  • Every exercise lists requirements and a Check made of individual commands. You pass it when every command shows what is expected. Read the solution only afterwards.
  • The exercises build on each other and all run in ~/docker-lab/anhb.
  • Allowed are Appendix A, docker … --help and the official docs, not Days 1–15.
  • You pass with eight passed checks and at least 8 of 10 points in the knowledge section.
source ~/docker-lab/setup/env.sh
mkdir -p ~/docker-lab/anhb && cd ~/docker-lab/anhb
cp -R "$LAB/code/notes/." .

Sizes, digests and times in the outputs will differ on your machine.

Exercise 1: notes-api small and correct

Parts A and B (Days 1–5). Write notes-api/Dockerfile and notes-api/.dockerignore:

  • Multi-stage, final image scratch, under 20 MB, /upstream works.
  • Runs as 65532:65532, ENTRYPOINT in exec form, docker stop under 2 s.
  • Healthcheck without a shell and without curl, “healthy” after at most 3 s.
  • Version via --build-arg VERSION=…, visible at /version.

Check: First build and start:

docker build -q --build-arg VERSION=1.0.0 -t notes-api:anhb notes-api
docker run -d --name notes-api -e NOTES_API_KEY=lab-api-key-123 \
  -p 127.0.0.1:8080:8080 notes-api:anhb
sleep 3

Expected: an image ID and a container ID.

Under 20 MB:

docker image ls notes-api:anhb

Expected (abbreviated, size differs):

IMAGE            ID             DISK USAGE   CONTENT SIZE   EXTRA
notes-api:anhb   e531785b5e1d       10.7MB         3.23MB   U

Runs as 65532:65532:

docker image inspect --format '{{.Config.User}}' notes-api:anhb

Expected:

65532:65532

Healthy:

docker ps --filter name=notes-api --format '{{.Status}}'

Expected (time differs):

Up 3 seconds (healthy)

Version and /upstream:

curl -s localhost:8080/version; echo
curl -s localhost:8080/upstream; echo

Expected (abbreviated):

1.0.0
{"status":200,"url":"https://example.com"}

docker stop under 2 s:

time docker stop notes-api
docker rm notes-api

Expected (times differ):

notes-api

real    0m0.436s
…
notes-api

Solution

cat > notes-api/Dockerfile <<'EOF'
# syntax=docker/dockerfile:1
ARG GO_VERSION=1.27
FROM golang:${GO_VERSION}-alpine AS build
WORKDIR /src
COPY go.mod go.sum ./
RUN --mount=type=cache,target=/go/pkg/mod go mod download
COPY . .
ARG VERSION=dev
RUN --mount=type=cache,target=/go/pkg/mod \
    --mount=type=cache,target=/root/.cache/go-build \
    CGO_ENABLED=0 go build -trimpath -ldflags="-s -w -X main.version=${VERSION}" \
    -o /out/notes-api .

FROM scratch
COPY --from=build /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/
COPY --from=build /out/notes-api /notes-api
USER 65532:65532
EXPOSE 8080
HEALTHCHECK --interval=10s --timeout=2s --start-period=5s --start-interval=1s \
    CMD ["/notes-api", "healthcheck"]
ENTRYPOINT ["/notes-api"]
EOF
cat > notes-api/.dockerignore <<'EOF'
Dockerfile*
.dockerignore
*.md
.git
.env*
**/*.test
EOF

Every requirement has one line: CA bundle for /upstream (Day 5), exec form for signals (Day 2), notes-api healthcheck instead of curl, -X main.version for the version.

Save your progress? Sign up for free

Exercise 2: Context and cache

Part A (Days 3, 4). Prove three things without changing the Dockerfile from Exercise 1:

  • The context of notes-api contains neither .env nor a Dockerfile.
  • After a change to main.go, go mod download comes from the cache.
  • A cache export to the local registry survives an emptied builder cache.

Check:

cat > spy.Dockerfile <<'EOF2'
# syntax=docker/dockerfile:1
FROM golang:1.27-alpine
COPY . /ctx
RUN find /ctx
EOF2
docker build --no-cache --progress=plain -f spy.Dockerfile notes-api 2>&1 | grep /ctx

Expected: main.go is in the context, no Dockerfile and no .env.

#8 [2/3] COPY . /ctx
#9 [3/3] RUN find /ctx
#9 0.529 /ctx
#9 0.529 /ctx/go.sum
#9 0.529 /ctx/main.go
#9 0.529 /ctx/go.mod

After a change to main.go, go mod download comes from the cache:

echo '// Prüfung' >> notes-api/main.go
docker build --progress=plain -t notes-api:anhb notes-api 2>&1 \
  | grep -A1 'go mod download'

Expected (abbreviated):

#10 [base 4/5] RUN --mount=type=cache,target=/go/pkg/mod go mod download
#10 CACHED

You check the third point yourself in the solution with grep -c CACHED.

Solution

Exercise 1 already fulfills the first two points: the .dockerignore and the order go.mod/go.sum before COPY . .. For the third, you export the cache with the builder docker-lab, empty it and build again from the registry only:

cache=type=registry,ref=localhost:5001/notes-api:anhb-cache
docker buildx build -q --builder docker-lab --cache-to "$cache,mode=max" \
  -t localhost:5001/notes-api:anhb --push notes-api
docker buildx prune --builder docker-lab --all --force >/dev/null
docker buildx build --builder docker-lab --cache-from "$cache" --progress=plain \
  -t localhost:5001/notes-api:anhb --push notes-api 2>&1 | grep -c CACHED

Expected (abbreviated, may vary by version):

sha256:c4d2…
6

mode=max also exports the layers of the build stage; otherwise only those of the final image would be in the cache (Day 4).

Save your progress? Sign up for free

Exercise 3: Worker and web

Part B (Day 6). Write Dockerfiles and .dockerignore for notes-worker and notes-web:

  • Neither final image runs as root.
  • notes-worker: runtime python:3.13-slim, no uv in the final image.
  • notes-web: runtime node:24-alpine, no esbuild, no src/, no .env.

Check:

docker build -q -t notes-worker:anhb notes-worker
docker build -q -t notes-web:anhb notes-web

Expected: two image IDs.

Neither runs as root:

docker run --rm --entrypoint id notes-worker:anhb -u
docker run --rm notes-web:anhb id -u

Expected:

65532
1000

No uv in the worker:

docker run --rm --entrypoint sh notes-worker:anhb -c 'command -v uv; echo "Exit: $?"'

Expected:

Exit: 127

In the web image no src/, no .env, but dist/app.js:

docker run --rm notes-web:anhb ls -a
docker run --rm notes-web:anhb ls dist

Expected:

.
..
dist
node_modules
package-lock.json
package.json
public
server.js
app.js

No esbuild:

docker run --rm notes-web:anhb ls node_modules | grep -c esbuild

Expected:

0

Solution

The Dockerfiles correspond to the solutions from Day 15, Round 4 (notes-web) and Round 5 (notes-worker). What matters are the boundaries between the stages:

  • Worker: uv comes via COPY --from=ghcr.io/astral-sh/uv:0.13 only into the build stage; only /app/.venv moves into the final image; --no-editable installs the package itself into the .venv, so src/ isn’t needed at runtime.
  • Web: the build stage needs npm ci with devDependencies for esbuild; the final stage uses npm ci --omit=dev and copies only dist, public and server.js.

The .dockerignore for the worker:

cat > notes-worker/.dockerignore <<'EOF'
.venv
**/__pycache__
Dockerfile*
.dockerignore
*.md
.env*
EOF

Save your progress? Sign up for free

Exercise 4: Test stage and multi-platform

Part B (Days 7, 8). Extend notes-api/Dockerfile:

  • Stage test with go vet and go test, callable separately with --target test.
  • Cross-compile without emulation: one push delivers linux/amd64 and linux/arm64.
  • A comment with the note about digest pinning on the base image, but no made-up digest.

Check:

docker build -q --target test notes-api >/dev/null; echo "Exit: $?"

Expected: the test stage runs.

Exit: 0
docker buildx build -q --builder docker-lab --platform linux/amd64,linux/arm64 \
  -t localhost:5001/notes-api:anhb-multi --push notes-api
docker buildx imagetools inspect localhost:5001/notes-api:anhb-multi | grep Platform

Expected (after the digest of the push):

sha256:78c54d198fe6…
  Platform:    linux/amd64
  Platform:    linux/arm64
  Platform:    unknown/unknown
  Platform:    unknown/unknown

The build stage runs on the build platform:

grep '^FROM --platform' notes-api/Dockerfile

Expected:

FROM --platform=$BUILDPLATFORM golang:${GO_VERSION}-alpine AS base

Solution

The model Dockerfile from Appendix A fulfills all points and already prepares Exercise 5:

cat > notes-api/Dockerfile <<'EOF'
# syntax=docker/dockerfile:1
# check=error=true
ARG GO_VERSION=1.27
# in production: pin @sha256:…, see Day 8
FROM --platform=$BUILDPLATFORM golang:${GO_VERSION}-alpine AS base
WORKDIR /src
COPY go.mod go.sum ./
RUN --mount=type=cache,target=/go/pkg/mod go mod download
COPY . .

FROM base AS test
RUN --mount=type=cache,target=/go/pkg/mod \
    --mount=type=cache,target=/root/.cache/go-build \
    go vet ./... && go test ./...

FROM base AS build
ARG TARGETOS TARGETARCH VERSION=dev
RUN --mount=type=cache,target=/go/pkg/mod \
    --mount=type=cache,target=/root/.cache/go-build \
    CGO_ENABLED=0 GOOS=$TARGETOS GOARCH=$TARGETARCH \
    go build -trimpath -ldflags="-s -w -X main.version=${VERSION}" -o /out/notes-api .

FROM scratch AS final
ARG VERSION=dev REVISION=unknown CREATED=unknown
LABEL org.opencontainers.image.title="notes-api" \
      org.opencontainers.image.version="${VERSION}" \
      org.opencontainers.image.revision="${REVISION}" \
      org.opencontainers.image.created="${CREATED}"
COPY --link --from=build /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/
COPY --link --from=build /out/notes-api /notes-api
USER 65532:65532
EXPOSE 8080
HEALTHCHECK --interval=10s --timeout=2s --start-period=5s --start-interval=1s \
    CMD ["/notes-api", "healthcheck"]
STOPSIGNAL SIGTERM
ENTRYPOINT ["/notes-api"]
EOF

A normal build without --target skips test, because final doesn’t depend on it (Day 7). Because base already runs on $BUILDPLATFORM, build inherits the native platform; only GOOS/GOARCH choose the target.

Save your progress? Sign up for free

Exercise 5: Harden and prove

Part C (Days 9, 10). With the Dockerfile from Exercise 4:

  • hadolint, docker build --check and trivy config (HIGH, CRITICAL) without findings.
  • dockle reports nothing at level WARN or above.
  • The container runs with --read-only --cap-drop ALL --security-opt no-new-privileges and becomes “healthy”.
  • Image in the registry with OCI labels for version, revision and timestamp, plus SBOM and provenance attestation.
  • A trivy scan with --severity HIGH,CRITICAL --exit-code 1 as a threshold whose result you can justify.

Check: The three checkers for the Dockerfile:

hadolint notes-api/Dockerfile; echo "Exit: $?"
docker build --check notes-api 2>&1 | tail -1
trivy config -q --exit-code 1 --severity HIGH,CRITICAL notes-api/Dockerfile
echo "Exit: $?"

Expected:

Exit: 0
Check complete, no warnings found.
Exit: 0

dockle at level WARN or above:

docker build -q -t notes-api:anhb notes-api
dockle --exit-code 1 --exit-level warn notes-api:anhb >/dev/null; echo "Exit: $?"

Expected:

sha256:73b5f9e07c8f…
Exit: 0

Hardened and healthy:

docker run -d --name notes-api --read-only --cap-drop ALL \
  --security-opt no-new-privileges -e NOTES_API_KEY=lab-api-key-123 notes-api:anhb
sleep 3
docker ps --filter name=notes-api --format '{{.Status}}'
docker rm -f notes-api

Expected (IDs and times differ):

5f0c…
Up 3 seconds (healthy)
notes-api

The version label in the registry:

docker buildx imagetools inspect localhost:5001/notes-api:anhb-1.0.0 \
  --format '{{json .Image}}' | jq '.config.Labels'

Expected (abbreviated):

{
  "org.opencontainers.image.created": "2026-11-02T18:04:13Z",
  "org.opencontainers.image.revision": "anhb-0001",
  "org.opencontainers.image.title": "notes-api",
  "org.opencontainers.image.version": "1.0.0"
}

SBOM and provenance hang on the index as an attestation:

docker buildx imagetools inspect localhost:5001/notes-api:anhb-1.0.0 \
  | grep reference.type

Expected:

    vnd.docker.reference.type:   attestation-manifest

Solution

The Dockerfile from Exercise 4 fulfills the first three points. For the registry you build with the builder docker-lab and pass the label values as build args:

docker buildx build -q --builder docker-lab \
  --build-arg VERSION=1.0.0 --build-arg REVISION=anhb-0001 \
  --build-arg CREATED="$(date -u +%Y-%m-%dT%H:%M:%SZ)" \
  --sbom=true --provenance=mode=max \
  -t localhost:5001/notes-api:anhb-1.0.0 --push notes-api
docker buildx imagetools inspect localhost:5001/notes-api:anhb-1.0.0 \
  --format '{{json .SBOM}}' | jq -r '.SPDX.packages[].name' | sort | head -5
trivy image --severity HIGH,CRITICAL --exit-code 1 notes-api:anhb; echo "Exit $?"

Expected (abbreviated, may vary by version):

sha256:7f20…
example.com/notes-api
github.com/google/uuid
stdlib
…
notes-api (gobinary)
Total: 0 (HIGH: 0, CRITICAL: 0)
Exit 0

If trivy reports findings in stdlib, it’s due to the Go version in the build stage: pull a new golang:1.27-alpine (--pull) and rebuild; don’t lower the threshold. mode=max contains the values of all build args – one more reason never to pass a secret via --build-arg.

Save your progress? Sign up for free

Exercise 6: Leak forensics

Part D (Day 11). First play game master: build the image without looking at leak.Dockerfile again afterwards.

cat > leak.Dockerfile <<'EOF'
# syntax=docker/dockerfile:1
FROM golang:1.27-alpine
ARG ARTIFACT_TOKEN
RUN echo "$ARTIFACT_TOKEN" > /tmp/token && wc -c /tmp/token && rm /tmp/token
COPY .env /app/.env
RUN rm /app/.env
EOF
docker build -q -f leak.Dockerfile --build-arg ARTIFACT_TOKEN=lab-artifact-token-123 \
  -t notes-leak:anhb .

Task: find both secrets in the image notes-leak:anhb, each with a different tool. docker run … ls doesn’t count, because the files are deleted.

Check: You have two commands whose output contains lab-artifact-token-123 and lab-api-key-123 respectively. Control for the first:

docker history --no-trunc notes-leak:anhb | grep -c lab-artifact-token-123

Expected: at least one match.

3

Solution

The token is in the history, because an ARG used in a RUN is recorded as the environment of the step. The .env sits in the COPY layer; the later rm only places a deletion marker over it:

docker history --no-trunc --format '{{.CreatedBy}}' notes-leak:anhb \
  | grep -o 'ARTI.*123'
docker save notes-leak:anhb -o leak.tar
mkdir -p leak && tar -xf leak.tar -C leak
for b in leak/blobs/sha256/*; do
  tar -xOf "$b" 2>/dev/null | grep -a lab-api-key && echo "→ Layer ${b##*/}"
done
rm -rf leak leak.tar

docker save writes the whole image including the golang base; expect a few hundred MB that you delete again right away.

Expected (abbreviated, may vary by version):

ARTIFACT_TOKEN=lab-artifact-token-123
NOTES_API_KEY=lab-api-key-123
→ Layer 1c7e…

tar reads compressed and uncompressed layers alike; 2>/dev/null discards blobs that aren’t layers. Both values count as burned (Day 15, Round 3).

Save your progress? Sign up for free

Exercise 7: Build secret done right

Part D (Day 13). Write secret.Dockerfile, which does the same work as leak.Dockerfile (count the token length), but:

  • The token comes via a secret mount as an environment variable and is never missing unnoticed.
  • .env doesn’t even get into the context.
  • Neither token nor key appear in the history or layers of the image notes-leak:anhb-fix.

Check:

export ARTIFACT_TOKEN=lab-artifact-token-123
docker build -q -f secret.Dockerfile --secret id=artifact_token,env=ARTIFACT_TOKEN \
  -t notes-leak:anhb-fix .
docker history --no-trunc notes-leak:anhb-fix | grep -c lab-artifact

Expected: no token in the history.

sha256:596c6fd63a21…
0

Without the secret, the build aborts:

docker build -q --no-cache -f secret.Dockerfile -t notes-leak:anhb-nosecret . \
  2>&1 | tail -1

Expected (abbreviated):

ERROR: failed to build: failed to solve: secret artifact_token: not found

.env doesn’t get into the context:

grep -x '.env\*' .dockerignore

Expected:

.env*

Solution

cat > secret.Dockerfile <<'EOF'
# syntax=docker/dockerfile:1
FROM golang:1.27-alpine
RUN --mount=type=secret,id=artifact_token,env=ARTIFACT_TOKEN,required=true \
    echo "Token-Länge: ${#ARTIFACT_TOKEN}"
EOF
cat > .dockerignore <<'EOF'
.git
.env*
!.env.example
secrets/
**/node_modules
**/.venv
*.Dockerfile
EOF

required=true makes the build fail without --secret instead of silently continuing with an empty value. The project .dockerignore applies to builds with . as the context; the service folder notes-api has its own. By the way, a new token value doesn’t rebuild the step: secrets aren’t part of the cache key (Day 13).

Save your progress? Sign up for free

Exercise 8: Runtime secret with Compose

Part D (Days 12, 14). Create .gitignore, secrets/notes_api_key.txt and compose.yaml:

  • Project name notes-anhb, service notes-api from Exercise 4, image notes-api:anhb-compose, port only on 127.0.0.1:8080.
  • The key arrives as a file under /run/secrets/notes_api_key; notes-api logs source=file.
  • Neither docker compose config nor docker inspect shows the key value.
  • Rotation to lab-api-key-456 (lab value) without a rebuild; the old key is rejected afterwards.

Check (after the rotation):

git init -q
git check-ignore -v .env secrets/notes_api_key.txt

Expected:

.gitignore:1:.env   .env
.gitignore:2:secrets/   secrets/notes_api_key.txt

notes-api reads the key from the file:

docker compose logs notes-api | grep -o 'source=[a-z]*'

Expected:

source=file

Neither config nor inspect shows a key value:

docker compose config | grep -c lab-api-key
docker inspect notes-anhb-notes-api-1 | grep -c lab-api-key

Expected:

0
0

The old key is rejected, the new one accepted:

curl -s -X POST localhost:8080/notes -H 'X-API-Key: lab-api-key-123' -d '{"text":"x"}'
curl -s -X POST localhost:8080/notes -H 'X-API-Key: lab-api-key-456' -d '{"text":"x"}'

Expected (abbreviated, ID differs):

{"error":"invalid api key"}
{"id":"d35dac68-…","text":"x"}

Solution

cat > .gitignore <<'EOF'
.env
secrets/
EOF
mkdir -p secrets
printf '%s\n' lab-api-key-123 > secrets/notes_api_key.txt
chmod 0644 secrets/notes_api_key.txt
cat > compose.yaml <<'EOF'
name: notes-anhb
services:
  notes-api:
    build:
      context: notes-api
    image: notes-api:anhb-compose
    environment:
      NOTES_API_KEY_FILE: /run/secrets/notes_api_key
    secrets:
      - notes_api_key
    ports:
      - "127.0.0.1:8080:8080"
secrets:
  notes_api_key:
    file: ./secrets/notes_api_key.txt
EOF
docker compose up -d --build
printf '%s\n' lab-api-key-456 > secrets/notes_api_key.txt
docker compose up -d --force-recreate notes-api
docker compose logs notes-api | grep 'api key loaded'

Expected (abbreviated, may vary by version):

notes-api-1  | time=… level=INFO msg="api key loaded" source=file

The container user 65532 must be able to read the file, hence 0644 in the lab (Day 14). docker compose config only shows the path to the file, docker inspect only NOTES_API_KEY_FILE. The rotation needs no new build, only a new container, because notes-api reads the key at startup.

Save your progress? Sign up for free

Knowledge section

One point per question; answer in one or two sentences.

  1. Where does an ARG before the first FROM apply, where does one in a stage apply, and why is neither ARG nor ENV suitable for secrets?
  2. Why does docker stop often take ten seconds with CMD notes-api (shell form)?
  3. What does COPY --link gain you in the final stage?
  4. You only change the value of a build secret. Does the RUN step rebuild?
  5. What is the difference between notes-api:tag14 and notes-api@sha256:…?
  6. Why is --platform=$BUILDPLATFORM on the build stage and not on the final stage?
  7. What distinguishes the .env next to compose.yaml from env_file:?
  8. Why USER 65532:65532 instead of USER nonroot?
  9. What does --provenance=mode=max reveal that mode=min doesn’t?
  10. A colleague committed .env with a real key. Which three steps?

Solutions

  1. Before FROM only in FROM lines; in a stage from the declaration to the end of the stage. Both end up visibly in the history, config or provenance (Day 2, Day 11).
  2. PID 1 is /bin/sh, which doesn’t pass SIGTERM on to the application; after the 10 s timeout comes SIGKILL (Day 2).
  3. The layer doesn’t depend on the content of the layers before it and can be reused with a new base image instead of being copied again (Day 7).
  4. No. Secrets aren’t part of the cache key; if you need to rebuild, use --no-cache or change a real input (Day 13).
  5. The tag is a mutable name, the digest the immutable checksum of the manifest (Day 1, Day 8).
  6. The compiler should run natively and fast and only produce the binary for TARGETARCH; the final image, on the other hand, must have the target platform (Day 7).
  7. The .env serves the interpolation of ${VAR} in compose.yaml; env_file: sets variables in the container (Day 12).
  8. With a numeric UID, the runtime (e.g. Kubernetes runAsNonRoot) can check that it isn’t running as root, without needing /etc/passwd in the image (Day 9).
  9. Among other things, the values of the build args; mode=min leaves them out (Day 10).
  10. Rotate the key, git rm --cached .env plus .gitignore, clean up the history (e.g. git filter-repo) – rotation first, because the history stays in every clone (Day 12).

Finally, clean up:

docker compose down
docker ps -a --filter name=^notes- --format '{{.Names}}' | xargs -r docker rm -f
docker image ls --format '{{.Repository}}:{{.Tag}}' \
  | grep -E '^(notes-|localhost:5001/)' | xargs -r docker rmi
docker buildx prune --builder docker-lab --all --force

Expected (abbreviated, names, IDs and sizes differ):

Untagged: notes-api:anhb
Deleted: sha256:…
…
Total:  …

Passed? Then you write Dockerfiles that are small, fast, traceable and secure – and you find the mistakes in other people’s.