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 … --helpand 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,/upstreamworks. - Runs as
65532:65532,ENTRYPOINTin exec form,docker stopunder 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 3Expected: an image ID and a container ID.
Under 20 MB:
docker image ls notes-api:anhbExpected (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:anhbExpected:
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; echoExpected (abbreviated):
1.0.0
{"status":200,"url":"https://example.com"}
docker stop under 2 s:
time docker stop notes-api
docker rm notes-apiExpected (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
EOFEvery 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-apicontains neither.envnor a Dockerfile. - After a change to
main.go,go mod downloadcomes 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 /ctxExpected: 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 CACHEDExpected (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: runtimepython:3.13-slim, nouvin the final image.notes-web: runtimenode:24-alpine, noesbuild, nosrc/, no.env.
Check:
docker build -q -t notes-worker:anhb notes-worker
docker build -q -t notes-web:anhb notes-webExpected: two image IDs.
Neither runs as root:
docker run --rm --entrypoint id notes-worker:anhb -u
docker run --rm notes-web:anhb id -uExpected:
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 distExpected:
.
..
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 esbuildExpected:
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:
uvcomes viaCOPY --from=ghcr.io/astral-sh/uv:0.13only into the build stage; only/app/.venvmoves into the final image;--no-editableinstalls the package itself into the.venv, sosrc/isn’t needed at runtime. - Web: the build stage needs
npm ciwith devDependencies foresbuild; the final stage usesnpm ci --omit=devand copies onlydist,publicandserver.js.
The .dockerignore for the worker:
cat > notes-worker/.dockerignore <<'EOF'
.venv
**/__pycache__
Dockerfile*
.dockerignore
*.md
.env*
EOFSave your progress? Sign up for free
Exercise 4: Test stage and multi-platform
Part B (Days 7, 8). Extend notes-api/Dockerfile:
- Stage
testwithgo vetandgo test, callable separately with--target test. - Cross-compile without emulation: one push delivers
linux/amd64andlinux/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 PlatformExpected (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/DockerfileExpected:
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"]
EOFA 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 --checkandtrivy 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-privilegesand 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 1as 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-apiExpected (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.typeExpected:
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-123Expected: 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.tardocker 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.
.envdoesn’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-artifactExpected: 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 -1Expected (abbreviated):
ERROR: failed to build: failed to solve: secret artifact_token: not found
.env doesn’t get into the context:
grep -x '.env\*' .dockerignoreExpected:
.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
EOFrequired=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, servicenotes-apifrom Exercise 4, imagenotes-api:anhb-compose, port only on127.0.0.1:8080. - The key arrives as a file under
/run/secrets/notes_api_key;notes-apilogssource=file. - Neither
docker compose confignordocker inspectshows 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.txtExpected:
.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-keyExpected:
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.
- Where does an
ARGbefore the firstFROMapply, where does one in a stage apply, and why is neitherARGnorENVsuitable for secrets? - Why does
docker stopoften take ten seconds withCMD notes-api(shell form)? - What does
COPY --linkgain you in the final stage? - You only change the value of a build secret. Does the
RUNstep rebuild? - What is the difference between
notes-api:tag14andnotes-api@sha256:…? - Why is
--platform=$BUILDPLATFORMon the build stage and not on the final stage? - What distinguishes the
.envnext tocompose.yamlfromenv_file:? - Why
USER 65532:65532instead ofUSER nonroot? - What does
--provenance=mode=maxreveal thatmode=mindoesn’t? - A colleague committed
.envwith a real key. Which three steps?
Solutions
- Before
FROMonly inFROMlines; 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). - PID 1 is
/bin/sh, which doesn’t pass SIGTERM on to the application; after the 10 s timeout comes SIGKILL (Day 2). - 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).
- No. Secrets aren’t part of the cache key; if you need to rebuild,
use
--no-cacheor change a real input (Day 13). - The tag is a mutable name, the digest the immutable checksum of the manifest (Day 1, Day 8).
- 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). - The
.envserves the interpolation of${VAR}incompose.yaml;env_file:sets variables in the container (Day 12). - With a numeric UID, the runtime (e.g. Kubernetes
runAsNonRoot) can check that it isn’t running as root, without needing/etc/passwdin the image (Day 9). - Among other things, the values of the build args;
mode=minleaves them out (Day 10). - Rotate the key,
git rm --cached .envplus.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 --forceExpected (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.