English translation of the Chinese courseware. Check linked official documentation for version-sensitive details.

Docker Hour 2: from "it runs" to "production-ready"

Picking up where hour 1 left off: smaller and safer images, controllable and observable containers, automated builds and releases
Docker Engine 29.9.3Compose v5.x · Buildx/BakeUbuntu 24.04 / 26.04 LTSVerified against official docs · 2026-11
Overall learning objectives
  • Build images that shut down gracefully: understand the ENTRYPOINT/CMD combination rules, PID 1, STOPSIGNAL and the stop timeout.
  • Master advanced Dockerfile features: ARG/ENV scope, secret/ssh mounts, heredoc, COPY --link/--chmod and build checks.
  • Use a multi-stage build to turn a Go service into a ~10 MB distroless non-root image, with a test stage inside the build.
  • Configure resource limits, health checks (including start-interval), log rotation and Prometheus metrics for containers.
  • Separate development and production with Compose .env, override files, include, profiles and secrets.
  • Design an image tagging strategy, and use Bake and GitHub Actions to build multi-arch images with SBOM/provenance.
  • Apply runtime security hardening, rootless mode and vulnerability scanning, and pass a production readiness review.

1-hour schedule

#TimeModuleCore contentAnimation / interactiveLab (Azure VM)
0Before classRecap and warm-upRebuild myapp from memory; production readiness self-assessment12-item self-assessment scorecompose up recap
100–07ENTRYPOINT/CMD and graceful shutdownCombination rules, exec form, entrypoint script exec "$@", STOPSIGNAL, stop timeoutENTRYPOINT × CMD × run-argument calculator; shutdown timeline animationTiming exec vs shell; changing the worker count
207–14Advanced DockerfileARG/ENV scope, secret/ssh mounts, heredoc, COPY options, build checks"Where does the token end up?" comparerSecret-leak demo + --check warnings
314–23Multi-stage builds in practiceGo + distroless, test stage, --target, Java/Node patterns, debugging shell-less imagesStage execution diagram + size comparisongoapp: 800 MB → ~10 MB
423–31Resources, health checks and observabilitycgroup limit details, HEALTHCHECK parameters, events, logging drivers, Engine metricsHealth-check timeline simulatorHealth status events + metrics scraping
531–39Advanced ComposeVariable precedence, override-file merge rules, !reset, include, profiles, secretsMerge result visualizerDevelopment/production dual mode
639–47Versioning, multi-arch and CI/CDSHA/semver tags, Bake, GitHub Actions (v7), caching, attestationsTag generator + pipeline animationBake multi-platform build
747–54Security hardeningLeast privilege at runtime, seccomp/AppArmor, rootless, scanning and supply-chain lessonsSecurity scorer (generates commands live)Hardened run + vulnerability scan
854–60Production readiness review and failure drillsReview checklist, 5 failure scenarios, mapping to KubernetesFailure drill cardsReview your own myapp
—After classCheat sheet · Capstone labTurn myapp into a production-grade service: multi-stage, hardening, CI, reviewFinal examCapstone lab

How this relates to Hour 1

No repetition
Docker architecture, image layering, networking and storage basics, and ACR authentication were covered in Hour 1; this lesson links back only when needed.
One level deeper
Lesson 1 only touched on exit codes, multi-stage builds, Compose healthchecks and hardening flags; this lesson gives the complete rules, interactive demos and troubleshooting methods.
Same project
We keep using ~/myapp (Flask + Redis) from Labs 5B/7B of Lesson 1 and add ~/goapp (a Go service).
Version notesThis lesson is based on docker-hour2-production-ready.ch.md and updated to the official documentation as of 2026-11: GitHub Actions now use docker/build-push-action@v7, login/setup-buildx/setup-qemu@v4, metadata-action@v6 and actions/checkout@v6; Go moves to 1.27 (released 2026-08-19) and distroless to static-debian13. See Sources and versions.

Module 0 · Recap and warm-up (before class)

Get Lesson 1's myapp running from memory, then score your own "production readiness"
Before class ≈ 5 min
Prerequisites
  • You have completed hour 1 (at least Modules 0, 4, 5B and 7B) and the VM already has ~/myapp (app.py, requirements.txt, Dockerfile, compose.yaml).
  • If not, copy the files from Lesson 1, Module 5 → Lab 5B to rebuild it quickly.
  • Module 6 needs a GitHub account (uses GHCR, no extra secrets needed); the rootless lab in Module 7 is best done on a separate VM.

Warm-up: rebuild the environment without looking at your notes

cd ~/myapp
docker compose up -d --build --wait
curl localhost:5000
docker compose logs web
docker compose down
Hello from 3c4d5e6f7a8b, hits=1

If you get stuck on any step, go back to the matching module in Lesson 1, review it, and continue.

Production readiness self-assessment (12 items)

Tick the items your myapp already does today. Come back after this lesson, tick again and compare the scores.

Module 1 · ENTRYPOINT/CMD, PID 1 and graceful shutdown

00:00 – 07:00 · Decide how a container starts and how it exits cleanly
7 minDockerfile referenceEssential for rolling releases
Learning objectives
  • Memorize the combination rules for ENTRYPOINT × CMD × docker run arguments and predict the final command.
  • Write a correct entrypoint script (exec "$@") so the application becomes PID 1 and receives SIGTERM.
  • Ensure application graceful shutdown time < stop timeout < load balancer draining time so releases don't drop requests.

What: how the two instructions divide the work

InstructionRoleWith docker run IMAGE xxxHow to override at run time
CMDDefault command or default argumentsThe whole CMD is replaced by xxxWrite arguments after the image name
ENTRYPOINTFixed main programNot replaced; xxx is appended as arguments (exec form)--entrypoint

Official combination rules (ENTRYPOINT × CMD)

No ENTRYPOINTENTRYPOINT e p (shell form)ENTRYPOINT ["e","p"] (exec form)
No CMDError, not allowed (the base image's CMD is inherited)/bin/sh -c e pe p
CMD ["c","x"]c x/bin/sh -c e p (CMD ignored)e p c x
CMD c x (shell form)/bin/sh -c c x/bin/sh -c e p (CMD ignored)e p /bin/sh -c c x

Source: Dockerfile reference, "Understand how CMD and ENTRYPOINT interact". Recommended combination: ENTRYPOINT in exec form fixes the program, CMD in exec form supplies default arguments. Also note that setting ENTRYPOINT in a Dockerfile clears the CMD inherited from the base image.

Why: PID 1 decides whether signals get through

  • docker stop sends STOPSIGNAL (SIGTERM by default) to PID 1, waits for the stop timeout (10 seconds by default), then sends SIGKILL.
  • The kernel does not deliver signals with "default disposition" to PID 1. When PID 1 is /bin/sh, SIGTERM neither terminates sh nor gets forwarded to the application.
  • The "coincidence" of modern shells: when dash/bash runs sh -c "single command", it execs the command directly, so PID 1 happens to be the application. But as soon as the command contains ;, a following && command, a pipe or variable handling, sh stays around. Don't rely on coincidence; check PID 1 with docker top.

How: writing the entrypoint script correctly

#!/bin/sh
set -eu
# Pre-start preparation: render config, wait for dependencies, run migrations...
echo "[entrypoint] APP_ENV=${APP_ENV:-dev}, starting: $*"
# Key point: exec makes the application "replace" the current shell and become PID 1
exec "$@"
COPY --chmod=0755 docker-entrypoint.sh /usr/local/bin/
ENTRYPOINT ["docker-entrypoint.sh"]
CMD ["gunicorn", "-b", "0.0.0.0:5000", "-w", "2", "app:app"]

This is the pattern used by official images (postgres, nginx, redis): the script does the preparation and exec "$@" runs CMD as the real main process. When you run docker run myapp sh, CMD is replaced with sh, which still goes through the entrypoint script first.

When: the three shutdown numbers must line up

ParameterDefaultWhere to set it
Stop signalSIGTERMDockerfile STOPSIGNAL, docker run --stop-signal, Compose stop_signal (nginx uses SIGQUIT for graceful shutdown)
Stop timeout10 secondsdocker stop -t, docker run --stop-timeout, Compose stop_grace_period, K8s terminationGracePeriodSeconds (default 30 seconds)
Application graceful shutdown timegunicorn --graceful-timeout defaults to 30 secondsApplication config
A common mismatchBy default gunicorn waits up to 30 seconds for workers to finish their requests, but Docker sends SIGKILL after 10 seconds. Either set stop_grace_period to 35s, or set --graceful-timeout to 8 seconds.

exec form vs shell form: process tree and signal path

✓ exec form: CMD ["gunicorn", …] docker stop → SIGTERM PID 1: gunicorn master workers exit after finishing requests → exit 0 ✗ shell form: CMD gunicorn …; echo done docker stop → SIGTERM PID 1: /bin/sh -c "…" (ignores signals) gunicorn never gets the signal → SIGKILL after 10 s → 137 Use docker top / docker exec CTR ps to see who PID 1 is

Shutdown sequence in a rolling release

① Drain from the load balancer ② SIGTERM ③ Stop accepting requests, finish in-flight ones ④ SIGKILL on timeout Rule: app graceful shutdown time < stop timeout (stop_grace_period / terminationGracePeriodSeconds) K8s often adds a preStop sleep so endpoint removal takes effect before SIGTERM

Interactive calculator: which command actually runs?

Shutdown timeline animation

Pick a scenario.

Related commands and flags

Command / flagDescription
docker run --entrypoint sh -it IMGOverride ENTRYPOINT (to get into the image when troubleshooting)
docker run IMG -w 4With an exec-form ENTRYPOINT, replaces only CMD (the default arguments)
docker image inspect -f '{{json .Config.Entrypoint}} {{json .Config.Cmd}}' IMGShow the image's entrypoint and default command
docker top CTR / docker exec CTR ps -o pid,commFind out who PID 1 is
docker stop -t 30 CTR / docker run --stop-timeout 30Stop timeout
docker run --stop-signal SIGQUITOverride the stop signal
docker run --inittini as PID 1: forwards signals and reaps zombie processes
docker kill -s HUP CTRSend any signal (for example, to make nginx/gunicorn reload config)
Compose: stop_signal, stop_grace_period, init: true, entrypoint, commandThe corresponding Compose fields

Lab 1: exec vs shell, argument overrides, entrypoint script (about 6 min)

Build two versions
cd ~/myapp
grep '^CMD' Dockerfile        # should be exec form: CMD ["gunicorn", "-b", "0.0.0.0:5000", "app:app"]
sed 's#^CMD .*#CMD gunicorn -b 0.0.0.0:5000 app:app; echo "gunicorn exited"#' Dockerfile > Dockerfile.shell
docker build -q -t myapp:exec .
docker build -q -t myapp:shell -f Dockerfile.shell .
Check PID 1 and time the stop
docker run -d --name t1 myapp:exec
docker run -d --name t2 myapp:shell
sleep 2
docker exec t1 sh -c 'cat /proc/1/cmdline | tr "\0" " "'; echo
docker exec t2 sh -c 'cat /proc/1/cmdline | tr "\0" " "'; echo
time docker stop t1
time docker stop t2
docker inspect -f '{{.Name}} exit={{.State.ExitCode}}' t1 t2
docker rm t1 t2
/usr/local/bin/python3.13 /usr/local/bin/gunicorn -b 0.0.0.0:5000 app:app
/bin/sh -c gunicorn -b 0.0.0.0:5000 app:app; echo "gunicorn exited"
real    0m0.6s
real    0m10.4s
/t1 exit=0
/t2 exit=137

The slim image has no ps, so read /proc/1/cmdline directly.

ENTRYPOINT + CMD: change only the arguments
cat > Dockerfile.ep <<'EOF'
FROM myapp:exec
ENTRYPOINT ["gunicorn", "app:app"]
CMD ["-b", "0.0.0.0:5000", "-w", "2"]
EOF
docker build -q -t myapp:ep -f Dockerfile.ep .
docker run -d --name ep myapp:ep -b 0.0.0.0:5000 -w 4
sleep 2; docker top ep | grep -c gunicorn       # 1 master + 4 workers = 5
docker rm -f ep
Entrypoint script + exec "$@"
cat > docker-entrypoint.sh <<'EOF'
#!/bin/sh
set -eu
echo "[entrypoint] APP_ENV=${APP_ENV:-dev}, starting: $*"
exec "$@"
EOF
cat > Dockerfile.script <<'EOF'
# syntax=docker/dockerfile:1
FROM myapp:exec
COPY --chmod=0755 docker-entrypoint.sh /usr/local/bin/
ENTRYPOINT ["docker-entrypoint.sh"]
CMD ["gunicorn", "-b", "0.0.0.0:5000", "app:app"]
EOF
docker build -q -t myapp:script -f Dockerfile.script .
docker run -d --name s1 -e APP_ENV=prod myapp:script
docker logs s1 | head -2
docker exec s1 sh -c 'cat /proc/1/cmdline | tr "\0" " "'; echo
time docker stop s1; docker rm s1
docker run --rm myapp:script python -c 'print("one-off tasks also go through the entrypoint script")'
[entrypoint] APP_ENV=prod, starting: gunicorn -b 0.0.0.0:5000 app:app
[2026-11-14 …] [1] [INFO] Starting gunicorn 23.0.0
/usr/local/bin/python3.13 /usr/local/bin/gunicorn -b 0.0.0.0:5000 app:app
real    0m0.6s
Align the stop timeout (in Compose)
services:
  web:
    stop_grace_period: 35s      # longer than gunicorn's default --graceful-timeout 30

Case 1: every release produces a burst of 502s

During rolling releases on Container Apps / AKS, old replicas were force-killed 10 seconds after SIGTERM, and the logs never showed "shutting down". Investigation found the Dockerfile used CMD ./start.sh, and the last line of start.sh was python app.py (no exec). Fix: change the script to exec python app.py and handle SIGTERM in the app; in K8s, also add preStop: sleep 5 so endpoint removal takes effect before SIGTERM.

Case 2: graceful nginx shutdown

The official nginx image sets STOPSIGNAL SIGQUIT in its Dockerfile (SIGQUIT is nginx's "graceful shutdown" signal; SIGTERM is "fast shutdown"). If you build your own nginx image on another base without knowing this, long-lived connections get cut off abruptly.

Case 3: database migrations in the entrypoint script

The entrypoint script ran alembic upgrade head before starting; with 3 replicas, all three containers migrated at once and hit lock conflicts. Better: run migrations as a separate one-off task (in Compose with depends_on: condition: service_completed_successfully, in K8s with a Job / initContainer) and keep the entrypoint script for lightweight preparation only.

Common errors and fixes

docker stop always takes 10 seconds, exit code 137

PID 1 is not the application (sh, or a script without exec), or the application doesn't handle SIGTERM. Check cat /proc/1/cmdline; switch to exec form / exec "$@" / --init.

After docker run IMG bash, the app fails with "unrecognized arguments: bash"

The image uses an exec-form ENTRYPOINT, so bash is appended to the main program as an argument. To get a shell, use --entrypoint sh.

exec ./docker-entrypoint.sh: permission denied / no such file or directory

The script isn't executable (use COPY --chmod=0755), has CRLF line endings (the shebang becomes /bin/sh\r), or the interpreter named in the shebang doesn't exist in the image (distroless has no sh).

Changing CMD has no effect

When ENTRYPOINT is in shell form, CMD and run-time arguments are ignored; or a child image reset ENTRYPOINT, which cleared the inherited CMD. Check the final configuration with docker image inspect.

Learning resources

▶
100+ Docker Concepts you Need to Know — Fireship
8:28 · 2024-03-12 · English · includes a quick overview of CMD/ENTRYPOINT
NoteWe could not find a verifiable, high-quality video dedicated to PID 1 signal handling and graceful shutdown, so this module relies on the official documentation.

Official documentation

or score ≥ 70% on the Quiz

Module 2 · Advanced Dockerfile: variable scope, build-time secrets and build checks

07:00 – 14:00 · Write Dockerfiles that don't leak secrets, are reusable and can be checked automatically
7 min# syntax=docker/dockerfile:1BuildKit
Learning objectives
  • Explain the scope of ARG and ENV, including "ARG before FROM" and BuildKit's predefined platform variables.
  • Handle build-time credentials with secret mounts / ssh mounts, and prove they did not stay in the image.
  • Write tidy Dockerfiles with heredoc and COPY --chmod/--link, and catch problems automatically with docker build --check.
Lesson 1 recapInstructions and caching, multi-stage basics and CMD vs ENTRYPOINT were covered in Lesson 1, Module 4; this module covers only the advanced parts.

What: scope of ARG and ENV

ARGENV
LifetimeBuild time onlyBuild time + run time (written to the image config)
ScopeFrom the declaration to the end of the current stage; every FROM starts a new stage, so redeclare itThe current stage plus stages and child images based on it
Declared before FROMUsable only in FROM lines; to use it inside a stage, write ARG NAME again (without a value it inherits the default)Not allowed
How it is passed--build-arg K=Vdocker run -e can override it at run time
Is it visible?ARG values used by RUN show up in docker history; provenance mode=max also records build argsVisible in docker inspect; present in every container's environment
ARG PYTHON_VERSION=3.13           # before FROM: usable only in FROM
FROM python:${PYTHON_VERSION}-slim
ARG PYTHON_VERSION                # redeclare inside the stage before using it in RUN
RUN echo "building with Python ${PYTHON_VERSION}"
ARG TARGETARCH                    # predefined by BuildKit: amd64 / arm64 …
RUN echo "target arch: ${TARGETARCH}"
ENV PYTHONUNBUFFERED=1

Platform ARGs provided automatically by BuildKit: TARGETPLATFORM, TARGETOS, TARGETARCH, TARGETVARIANT, BUILDPLATFORM, BUILDOS, BUILDARCH... They are very useful in multi-platform builds (Modules 3 and 6).

Why: the right way to handle build-time secrets

MethodSyntaxVerdict
ARGARG TOKEN + --build-arg TOKEN=…✗ Shows up in history and provenance
ENVENV TOKEN=…✗ Permanently written to the image and every container
COPY, then deleteCOPY .npmrc . → RUN rm .npmrc✗ The file is still in the COPY layer
secret mountRUN --mount=type=secret,id=npmrc,target=/root/.npmrc npm ci✓ Appears only during this step as a tmpfs file; never enters any layer
secret as an environment variableRUN --mount=type=secret,id=token,env=TOKEN …✓ Same as above (needs a recent Dockerfile frontend; # syntax=docker/dockerfile:1 automatically uses the latest stable one)
ssh mountRUN --mount=type=ssh git clone git@github.com:org/private.git + docker build --ssh default✓ Forwards the build machine's SSH agent; the private key never enters the image

How: syntax for tidier Dockerfiles

  • Heredoc: multi-line RUN no longer needs && \: RUN <<EOF … EOF; you can also generate files directly with COPY <<EOF /path.
  • COPY --chmod=0755 / --chown=10001:10001: set permissions and ownership while copying, avoiding an extra RUN chmod layer (which would copy the file again).
  • COPY --link: makes the layer independent of earlier layers, so it can be reused (rebased) when the base image changes, improving remote cache hit rates.
  • Install and clean up in the same RUN: apt-get update && apt-get install -y --no-install-recommends … && rm -rf /var/lib/apt/lists/*.

When: build checks

docker build --check . only runs the static checks without building; a normal build also shows check results as warnings. Common rules:

RuleTriggered when
JSONArgsRecommendedCMD/ENTRYPOINT uses shell form (the signal problem from Module 1)
SecretsUsedInArgOrEnvAn ARG/ENV name looks like a secret (TOKEN, PASSWORD, SECRET...)
UndefinedVarAn undefined variable is referenced (often a forgotten ARG redeclaration inside a stage)
FromAsCasingInconsistent casing in FROM … as builder

Put # check=error=true at the top of the Dockerfile to fail the build when a check fails (good for CI); use # check=skip=RuleName to skip specific rules.

ARG scope illustrated

Global scope (before FROM): ARG PYTHON_VERSION=3.13 → usable only in FROM lines Stage builder FROM python:${PYTHON_VERSION}-slim AS builder ✓ RUN echo $PYTHON_VERSION → empty ✗ (not redeclared) ARG PYTHON_VERSION ← redeclared RUN echo $PYTHON_VERSION → 3.13 ✓ ARG TOKEN (this stage only) Stage runtime FROM python:${PYTHON_VERSION}-slim ✓ RUN echo $TOKEN → empty (builder's ARG doesn't cross stages) ENV APP_ENV=prod → written to the image config docker run -e APP_ENV=dev can override it

Secret mount data flow

token.txt / $GH_TOKENLocal to the build machine --secret BuildKitSent over the session, never cached While RUN executes/run/secrets/id (tmpfs) Image layerNo secret ✓

Comparer: where does the token end up?

Build-related flags

Command / flagDescription
docker build --build-arg PYTHON_VERSION=3.12 .Override an ARG default
docker build --secret id=token,src=./token.txt .Provide a secret from a file
docker build --secret id=token,env=GH_TOKEN .Provide a secret from a build-machine environment variable
docker build --ssh default .Forward the SSH agent (with --mount=type=ssh)
docker build --check .Run build checks only
docker build --progress=plain --no-cache .Full logs, no cache (debug RUN output)
docker history --no-trunc --format '{{.Size}}\t{{.CreatedBy}}' IMGShow each layer's size and creating instruction
docker image inspect -f '{{json .Config.Env}}' IMGShow the ENV written to the image

Lab 2: scope, leaks and fixes (about 6 min)

ARG scope
mkdir -p ~/lab2b && cd ~/lab2b
cat > Dockerfile.scope <<'EOF'
# syntax=docker/dockerfile:1
ARG ALPINE_VERSION=3.22
FROM alpine:${ALPINE_VERSION}
RUN echo "before redeclare: [${ALPINE_VERSION}]"
ARG ALPINE_VERSION
RUN echo "after redeclare:  [${ALPINE_VERSION}]"
ARG TARGETARCH
RUN echo "target arch: ${TARGETARCH}"
EOF
docker build --no-cache --progress=plain -f Dockerfile.scope . 2>&1 | grep -E "redeclare|target arch|WARN"
#5 0.2 before redeclare: []
#6 0.2 after redeclare:  [3.22]
#7 0.2 target arch: amd64

Note: docker build --check -f Dockerfile.scope . does not catch this mistake (it prints Check complete, no warnings found.), because BuildKit treats the global ARG as declared. The only clue is the empty [] in the output above.

Passing a token with ARG: leak demo
cat > Dockerfile.leak <<'EOF'
FROM alpine:3.22
ARG TOKEN
RUN test -n "$TOKEN" && echo "downloading private package…"
EOF
docker build --check -f Dockerfile.leak .
docker build -q --build-arg TOKEN=supersecret123 -t leak -f Dockerfile.leak .
docker history --no-trunc leak | grep -o "TOKEN=[a-z0-9]*"
WARNING: SecretsUsedInArgOrEnv - https://docs.docker.com/go/dockerfile/rule/secrets-used-in-arg-or-env/
Do not use ARG or ENV instructions for sensitive data (ARG "TOKEN")
…
TOKEN=supersecret123          ← visible to anyone who can pull the image
Switch to a secret mount
cat > Dockerfile.secret <<'EOF'
# syntax=docker/dockerfile:1
FROM alpine:3.22
RUN --mount=type=secret,id=token,env=TOKEN \
    test -n "$TOKEN" && echo "token length: ${#TOKEN}"
EOF
printf 'supersecret123' > token.txt
docker build --no-cache --progress=plain --secret id=token,src=token.txt \
  -t nosecret -f Dockerfile.secret . 2>&1 | grep "token length"
docker history --no-trunc nosecret | grep -c supersecret || echo "no token in history ✓"
rm token.txt
#6 0.15 token length: 14
0
no token in history ✓
Heredoc + same-layer cleanup: compare sizes
cat > Dockerfile.apt-bad <<'EOF'
FROM debian:13-slim
RUN apt-get update
RUN apt-get install -y curl
RUN rm -rf /var/lib/apt/lists/*
EOF
cat > Dockerfile.apt-good <<'DOCKERFILE'
# syntax=docker/dockerfile:1
FROM debian:13-slim
RUN <<EOF
set -eux
apt-get update
apt-get install -y --no-install-recommends curl ca-certificates
rm -rf /var/lib/apt/lists/*
EOF
DOCKERFILE
docker build -q -t apt:bad  -f Dockerfile.apt-bad .
docker build -q -t apt:good -f Dockerfile.apt-good .
docker image ls apt

Expected: apt:bad is noticeably larger (the apt index stays in the first layer and recommended packages are installed). Note that the outer bash heredoc terminator is DOCKERFILE; it cannot also be EOF, or bash would end early at the inner EOF. The inner <<EOF is handled by the Dockerfile parser. debian:13-slim is Debian 13 "trixie".

Fail the build when a check fails (recommended for CI)
sed -i '1i # check=error=true' Dockerfile.leak
docker build --build-arg TOKEN=x -f Dockerfile.leak . ; echo "exit=$?"
ERROR: failed to build: failed to solve: lint violation found for rules: SecretsUsedInArgOrEnv
exit=1

Case 1: private PyPI / npm registries

RUN --mount=type=secret,id=pipconf,target=/etc/pip.conf \
    --mount=type=cache,target=/root/.cache/pip \
    pip install -r requirements.txt
docker build --secret id=pipconf,src="$PIP_CONF_PATH" -t app .
# GitHub Actions: the secrets: or secret-files: inputs of docker/build-push-action

Case 2: the build needs access to a private Git repository

RUN --mount=type=ssh \
    mkdir -p -m 0700 ~/.ssh && ssh-keyscan github.com >> ~/.ssh/known_hosts && \
    git clone git@github.com:yourorg/private-lib.git /src/private-lib
eval "$(ssh-agent)"; ssh-add ~/.ssh/id_ed25519
docker build --ssh default -t app .

Case 3: provenance leaked build args

The team had stopped passing tokens with ARG, yet still used --build-arg BUILD_TOKEN to call an internal API for the version number. After enabling --provenance=mode=max, the token was written into the provenance attestation pushed to the registry. Rule: every secret goes through a secret mount, no exceptions; # check=error=true plus the SecretsUsedInArgOrEnv rule catches this early in CI.

Common errors and fixes

Variables in RUN are empty (even though the ARG has a default)

The ARG was declared before FROM, or in another stage. Write ARG NAME again inside the current stage. Note that docker build --check does not flag this (the global ARG counts as declared); you only notice it from the empty value.

cat: can't open '/run/secrets/token': No such file or directory

The build command didn't provide a --secret with the matching id, or the id is spelled differently. By default a missing secret is not an error; add required=true: --mount=type=secret,id=token,required=true.

Secret content changed, but the build hit the cache

Secret content is not part of the cache key. To force a refresh, use --no-cache-filter STAGE, or pass a non-sensitive version number as an ARG to invalidate that step.

Host key verification failed (ssh mount)

The image has no known_hosts. Run ssh-keyscan in the same RUN, or COPY in a verified known_hosts file.

A command in a heredoc failed, but the build continued

Heredocs don't exit on error by default. Add set -eux as the first line.

Learning resources

NoteWe could not find a verifiable video covering newer features such as secret mounts and build checks. The official documentation below is the authoritative source for this module.
or score ≥ 70% on the Quiz

Module 3 · Multi-stage builds in practice: from 800 MB to 10 MB

14:00 – 23:00 · Go + distroless, tests inside the build, cross-compilation, debugging shell-less images
9 minGo 1.27 · distroless static-debian13Key module ⭐
Learning objectives
  • Package a compiled service as a distroless non-root image containing a single static binary.
  • Understand that BuildKit builds only the stages the target depends on, and design test / lint stages accordingly.
  • Cross-compile with --platform=$BUILDPLATFORM + TARGETARCH (no QEMU needed).
  • Troubleshoot images without a shell: health-check subcommands and debug containers that share namespaces.

What: multi-stage build = several build pipelines in one Dockerfile

Each FROM starts a stage; the final image contains only the filesystem of the last stage (or the stage named by --target). Compilers, source code and caches from earlier stages are discarded; only artifacts copied with COPY --from=STAGE reach the final image.

Why: the benefits go beyond size

BenefitDescription
SizeA golang build image is 800 MB or more; distroless static + a static binary is about 10 MB (illustrative; check with docker image ls)
Attack surfaceNo shell, package manager or compiler: far fewer vulnerability findings, and lateral movement is hard even after a compromise
ReproducibilityThe build environment is pinned by the Dockerfile, so CI matches local builds
Parallelism and skippingBuildKit builds independent stages in parallel from the dependency graph and skips stages the target doesn't depend on

How: key techniques

  • Static compilation: with CGO_ENABLED=0 the binary doesn't depend on libc, so it can run on distroless/static or scratch.
  • Cross-compilation: FROM --platform=$BUILDPLATFORM golang:1.27 AS builder runs the compiler natively on the build machine's architecture, then GOOS=$TARGETOS GOARCH=$TARGETARCH cross-compiles, which is much faster than QEMU emulation.
  • Caching: --mount=type=cache,target=/go/pkg/mod and /root/.cache/go-build.
  • Test stage: FROM builder AS test + RUN go test ./...; a default build of runtime does not run it, so you need --target test (or make runtime depend on it).
  • Health checks: distroless has no curl/sh, so give the binary its own -healthcheck subcommand.

When: choosing a base image

Base imageContentsBest forWatch out
scratchEmptyFully static binariesNo CA certificates, timezone data or /etc/passwd; you must copy them yourself
gcr.io/distroless/static-debian13:nonrootCA certificates, tzdata, nonroot user (UID 65532)Go and Rust static binariesNo shell; the :debug variant includes busybox, for troubleshooting only
distroless/base, /cc, /java, /python3glibc / libstdc++ / runtimePrograms that need libcLimited language versions; see the project README
alpinemusl + busybox + apkWhen you need a few toolsmusl vs glibc behavior differences (DNS, native extensions)
*-slim (Debian)glibc + trimmed package setInterpreted languages such as Python and NodeLarger, but the best compatibility

goapp stage dependency graph

golang:1.27--platform=$BUILDPLATFORM buildergo mod downloadgo build (cross-compiled) testgo test ./... runtime (default target)distroless staticCOPY --from=builder /out/hello Final image≈ 10 MB A default build skips test

Multi-stage patterns for common languages

Javamaven:3.9-eclipse-temurin-21: mvn package→eclipse-temurin:21-jre: COPY app.jar Node front endnode:24-alpine: npm ci && npm run build→nginx:alpine: COPY dist/ → html Pythonpython:3.13-slim: venv + pip install→python:3.13-slim: COPY /opt/venv (Lesson 1, Module 4)

Stage execution simulator: pick a build target

Image size comparison (illustrative)

Multi-stage commands

CommandDescription
docker build --target builder -t goapp:fat .Build only up to the given stage
docker build --target test .Run the test stage (the build fails if tests fail)
docker build --build-arg GO_VERSION=1.26 .Switch the toolchain version
docker buildx build --platform linux/amd64,linux/arm64 .Multi-platform: builder runs natively and cross-compiles
COPY --from=nginx:alpine /etc/nginx/nginx.conf .Copy files from any image (not just a stage)
docker run --rm -it --pid container:go --network container:go busybox:1.37 shDebug distroless: share the PID and network namespaces
docker cp go:/hello ./helloCopy files out of a container (works with distroless too)

Lab 3: a production-grade multi-stage image for a Go service (about 8 min)

Create the project (with graceful shutdown, /healthz, a health-check subcommand and unit tests)
mkdir -p ~/goapp && cd ~/goapp
cat > go.mod <<'EOF'
module hello

go 1.27
EOF

cat > main.go <<'EOF'
package main

import (
	"context"
	"fmt"
	"log"
	"net/http"
	"os"
	"os/signal"
	"syscall"
	"time"
)

func handler(w http.ResponseWriter, r *http.Request) {
	h, _ := os.Hostname()
	fmt.Fprintf(w, "Hello from Go on %s\n", h)
}

func main() {
	// distroless has no curl: the binary ships its own health-check subcommand
	if len(os.Args) > 1 && os.Args[1] == "-healthcheck" {
		resp, err := http.Get("http://127.0.0.1:8080/healthz")
		if err != nil || resp.StatusCode != http.StatusOK {
			os.Exit(1)
		}
		os.Exit(0)
	}

	mux := http.NewServeMux()
	mux.HandleFunc("/", handler)
	mux.HandleFunc("/healthz", func(w http.ResponseWriter, r *http.Request) { w.Write([]byte("ok")) })
	srv := &http.Server{Addr: ":8080", Handler: mux}

	ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGTERM, os.Interrupt)
	defer stop()
	go func() {
		if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
			log.Fatal(err)
		}
	}()
	log.Println("listening on :8080")
	<-ctx.Done()
	log.Println("SIGTERM received, shutting down gracefully")
	shutdownCtx, cancel := context.WithTimeout(context.Background(), 8*time.Second)
	defer cancel()
	_ = srv.Shutdown(shutdownCtx)
}
EOF

cat > main_test.go <<'EOF'
package main

import (
	"net/http/httptest"
	"strings"
	"testing"
)

func TestHandler(t *testing.T) {
	rec := httptest.NewRecorder()
	handler(rec, httptest.NewRequest("GET", "/", nil))
	if !strings.HasPrefix(rec.Body.String(), "Hello from Go") {
		t.Fatalf("unexpected body: %q", rec.Body.String())
	}
}
EOF
printf '.git\n*.md\nDockerfile*\n' > .dockerignore
Write the Dockerfile
# syntax=docker/dockerfile:1
ARG GO_VERSION=1.27

# ---------- builder: runs natively on the build machine, cross-compiles ----------
FROM --platform=$BUILDPLATFORM golang:${GO_VERSION} AS builder
WORKDIR /src
COPY go.mod ./
RUN --mount=type=cache,target=/go/pkg/mod go mod download
COPY . .
ARG TARGETOS TARGETARCH
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" -o /out/hello .

# ---------- test: runs only with --target test ----------
FROM builder AS test
RUN --mount=type=cache,target=/root/.cache/go-build go test -v ./...

# ---------- runtime: the final image ----------
FROM gcr.io/distroless/static-debian13:nonroot AS runtime
COPY --from=builder /out/hello /hello
USER nonroot:nonroot
EXPOSE 8080
HEALTHCHECK --interval=10s --timeout=2s --start-period=5s --start-interval=1s \
  CMD ["/hello", "-healthcheck"]
ENTRYPOINT ["/hello"]
cat > Dockerfile     # paste the content above, end with Ctrl+D
docker build --check .
Test, build and compare sizes
docker build --target test --progress=plain . 2>&1 | grep -E "RUN|PASS|ok"
docker build -q --target builder -t goapp:fat .
docker build -q -t goapp:slim .
docker image ls goapp
=== RUN   TestHandler
--- PASS: TestHandler (0.00s)
ok      hello   0.004s
REPOSITORY   TAG    …   DISK USAGE   CONTENT SIZE
goapp        fat    …   1.31GB       319MB
goapp        slim   …   15.8MB       3.62MB
Run, health check, graceful shutdown
docker run -d --name go -p 127.0.0.1:8080:8080 goapp:slim
sleep 3; curl -s localhost:8080
docker inspect -f '{{.State.Health.Status}} user={{.Config.User}}' go
docker exec go sh || echo "no sh in distroless (as expected)"
time docker stop go; docker logs go | tail -2
Hello from Go on 7d1e2f3a4b5c
healthy user=nonroot:nonroot
OCI runtime exec failed: exec failed: … exec: "sh": executable file not found in $PATH
no sh in distroless (as expected)
real    0m0.4s
… SIGTERM received, shutting down gracefully
Debug a container without a shell
docker start go
docker run --rm -it --pid container:go --network container:go busybox:1.37 sh -c 'ps; wget -qO- localhost:8080/healthz; echo'
docker rm -f go
PID   USER     TIME  COMMAND
    1 65532     0:00 /hello
   12 root      0:00 ps
ok
(Optional) cross-compilation
docker buildx build --platform linux/amd64,linux/arm64 -t goapp:multi .
docker image ls --tree goapp 2>/dev/null || docker image ls goapp

The builder stage runs natively on amd64 and simply cross-compiles an arm64 binary, so no QEMU is needed and it is fast.

Case 1: vulnerability scan alerts dropped from 200 to 0

A Go microservice originally ran directly on golang:1.2x; scans found over 200 OS package vulnerabilities and base image updates had to be handled every week. After switching to multi-stage + distroless/static:nonroot, the image contained only the binary and CA certificates, OS-level vulnerabilities essentially dropped to zero, and what remained related only to the Go standard library and dependencies (handled with govulncheck).

Case 2: the test stage was "quietly skipped"

The team added FROM builder AS test to the Dockerfile and assumed CI would run the tests. In fact the default target is the last stage, so BuildKit skipped test. Fix: run docker build --target test . first in CI, or add an explicit dependency in the runtime stage such as COPY --from=test /tmp/test-passed /dev/null (the test stage must create that file).

Case 3: layered jars for a Java service

A Spring Boot fat jar produces a new layer of tens of MB on every code change. Use java -Djarmode=tools -jar app.jar extract --layers (newer Spring Boot) to split dependencies and application code into separate directories and COPY them separately in the runtime stage; when code changes, only the last layer changes and pushes and pulls are much faster. Check the documentation for your Spring Boot version for the exact command.

Common errors and fixes

exec /hello: no such file or directory (even though the file exists)

The binary is dynamically linked (CGO_ENABLED=0 not set), and distroless static / scratch has no dynamic linker or libc. Set CGO_ENABLED=0, or switch to distroless/base. Use file hello to check that it is "statically linked".

x509: certificate signed by unknown authority (calling HTTPS from a scratch image)

scratch has no CA certificates. Use distroless static (which includes them), or copy them from the builder: COPY --from=builder /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/.

COPY --from=builder: "/out/hello": not found

The path doesn't match, the stage name is misspelled, or the build command in builder failed but was masked by || true. Build it on its own with docker build --target builder and check.

open /tmp/xxx: permission denied (running as nonroot)

UID 65532 can't write to the target directory. Write to a mounted volume or tmpfs instead, or prepare the directory in builder and use COPY --chown=65532:65532.

Multi-platform builds are extremely slow

The compile stage is being emulated in QEMU. For Go/Rust use --platform=$BUILDPLATFORM + cross-compilation; for other languages use native arm64 runners (GitHub offers hosted arm64 runners) or a remote builder.

or score ≥ 70% on the Quiz

Module 4 · Resource limits, health checks and observability

23:00 – 31:00 · Keep containers under control (they can't take down the host) and observable (you see problems when they happen)
8 mincgroup v2HEALTHCHECK start-interval needs Engine 25+
Learning objectives
  • Distinguish hard limits from soft reservations (limit vs reservation) and know which cgroup v2 file each flag maps to.
  • Design a sensible HEALTHCHECK: parameter meanings, state transitions, and checking only the service itself, not its dependencies.
  • Build basic observability with events, logging drivers and Engine Prometheus metrics.
Lesson 1 recapFor --memory/--cpus/--pids-limit, the exit-code table and reproducing an OOM, see Lesson 1, Module 3. This module covers the details and observability tools beyond those flags.

What: the full picture of resource flags (cgroup v2)

Flagcgroup v2 fileTypeDescription
--memory 512mmemory.maxHard limitExceeding it triggers an OOM kill (exit code 137)
--memory-reservation 256mmemory.lowSoft reservationKept as far as possible when the host is short of memory
--memory-swapmemory.swap.maxHard limitTotal of memory + swap; setting it equal to --memory disables swap
--cpus 1.5cpu.maxHard quotaExceeding it causes throttling, not a kill
--cpu-shares 512cpu.weightRelative weightOnly takes effect under CPU contention
--cpuset-cpus 0,1cpuset.cpusCPU pinningLatency-sensitive and NUMA workloads
--pids-limit 200pids.maxHard limitGuards against fork bombs and thread leaks
--device-read-bps, etc.io.maxHard limitLimits disk throughput
--ulimit nofile=65536:65536(rlimit, not cgroup)Process limitFile handle count for high-concurrency services

In Compose these go under deploy.resources.limits (hard limits: cpus, memory, pids) and deploy.resources.reservations (reservations: cpus, memory). Most of them can be changed on a running container with docker update.

Why: the health-check state machine

ParameterDefaultMeaning
--interval30sInterval between two checks in the normal phase
--timeout30sA single check that exceeds this is a failure
--start-period0sStart-up grace period: failures don't count; the first success marks the container healthy
--start-interval5sCheck interval during the grace period (Engine 25.0+), so readiness is detected sooner
--retries3Consecutive failures after the grace period before the container is marked unhealthy

States: starting → healthy ⇄ unhealthy. A check command returning 0 means success, 1 means failure; the last 5 results are kept in .State.Health.Log. Standalone Docker does not restart a container because it is unhealthy (as stressed in Lesson 1), but Compose's depends_on: condition: service_healthy, docker compose up --wait and external monitoring all rely on it.

How: health-check design principles

  • Check only yourself: check whether the process responds (/healthz). Don't check the database in liveness-style checks, or a database blip will mark every replica unhealthy at once (cascading failure). Put dependency checks in readiness (K8s) or in the application's own degradation logic.
  • Keep it cheap: no heavy queries; the timeout shorter than the interval.
  • The check tool must exist in the image: slim has no curl, so use python -c, wget (alpine/busybox) or a subcommand built into the binary (Module 3).

When: logs and metrics

Logging driverCharacteristicsRecommendation
json-file (default)No rotation by defaultYou must configure max-size/max-file
localBinary format, compressed, rotated by defaultFirst choice on a single host
journald / syslogHands off to the system logWhen central collection already exists (e.g. Azure Monitor Agent collecting journald/syslog)
fluentd / gelf / awslogs / gcplogs / splunkSends directly to the backendWatch out for blocking when the backend is down; use mode=non-blocking

Engine metrics: set "metrics-addr": "127.0.0.1:9323" in daemon.json to expose daemon metrics in Prometheus format at /metrics. Official note: metric names are still under active development and may change. Per-container CPU/memory time series are usually collected with cAdvisor or Azure Monitor / the OpenTelemetry Collector.

Observability data flow (single host)

Container stdout / stderrHEALTHCHECKcgroup stats/metrics (the app itself) dockerd / containerd Logging driver (local / journald …)health_status eventsdocker stats / eventsmetrics-addr :9323 Collection and alerting Azure Monitor Agent / Fluent BitLog Analytics (KQL)Prometheus / Managed PrometheusGrafana dashboardAlerts: unhealthy / OOM / restart count
Figure 4-1 Hours 3 and 4 configure logging and alerting on Azure and AWS; here we establish the single-host concepts first

Health-check timeline simulator

Assume the app becomes ready only at 12 seconds and hangs at 45 seconds. Adjust the parameters and watch when each check runs (the number in each cell is the second) and the container status.

SuccessFailure (in grace period, not counted)Failure (counted)

Runtime operations commands

CommandDescription
docker stats --no-stream --format 'table {{.Name}}\t{{.CPUPerc}}\t{{.MemUsage}}\t{{.PIDs}}'Resource snapshot
docker update --cpus 1 --memory 512m --memory-swap 512m CTRChange limits on the fly
docker inspect -f '{{json .State.Health}}' CTRHealth status and output of the last 5 checks
docker ps --filter health=unhealthyList unhealthy containers
docker events --filter container=CTR --since 10mEvent stream: create, start, health_status, oom, die, kill
docker events --format '{{json .}}'JSON output, easy to feed into scripts
docker logs --since 10m --timestamps CTRLogs with timestamps
docker run --log-driver local --log-opt max-size=10m --log-opt max-file=3Per-container logging configuration
docker run --log-opt mode=non-blocking --log-opt max-buffer-size=4mDon't block the app when the log backend is slow (logs are dropped when the buffer is full)
docker top CTR / docker cp / docker diffProcesses, files and filesystem changes
curl -s 127.0.0.1:9323/metricsEngine Prometheus metrics (requires metrics-addr)

Lab 4: limits, health events, logs and metrics (about 7 min)

Hard limit + soft reservation, adjusted on the fly
docker run -d --name app --memory 256m --memory-reservation 128m --cpus 0.5 \
  --pids-limit 100 --restart unless-stopped -p 127.0.0.1:5000:5000 myapp:exec
CG=/sys/fs/cgroup/system.slice/docker-$(docker inspect -f '{{.Id}}' app).scope
cat $CG/memory.max $CG/memory.low $CG/cpu.max $CG/pids.max
docker update --cpus 1 app && cat $CG/cpu.max
docker rm -f app
268435456
134217728
50000 100000
100
app
100000 100000
Health checks and events (events are easier to follow in a second SSH window)
docker run -d --name hc \
  --health-cmd 'test -f /tmp/healthy' --health-interval 3s --health-retries 2 \
  --health-start-period 10s --health-start-interval 1s \
  alpine:3.22 sh -c 'sleep 4; touch /tmp/healthy; sleep 3600'
timeout 25 docker events --filter container=hc --format '{{.Time}} {{.Action}}' &
sleep 8;  docker exec hc rm /tmp/healthy
sleep 12; docker inspect -f '{{.State.Health.Status}} failing={{.State.Health.FailingStreak}}' hc
wait; docker rm -f hc
1794700001 exec_create: test -f /tmp/healthy
…
1794700005 health_status: healthy
…
1794700014 health_status: unhealthy
unhealthy failing=4

For the first 4 seconds the file doesn't exist yet, but we are inside the 10-second grace period, so failures don't count; the first success immediately marks it healthy; after the file is deleted, 2 consecutive failures make it unhealthy.

Logging driver and rotation
docker run -d --name noisy --log-driver local --log-opt max-size=1m --log-opt max-file=2 \
  alpine:3.22 sh -c 'while true; do echo "$(date) $(head -c 200 /dev/urandom | base64 -w0)"; done'
sleep 10
docker inspect -f '{{.HostConfig.LogConfig.Type}} {{.HostConfig.LogConfig.Config}}' noisy
sudo du -sh /var/lib/docker/containers/$(docker inspect -f '{{.Id}}' noisy)/local-logs
docker logs --tail 2 noisy | cut -c1-80
docker rm -f noisy
local map[max-file:2 max-size:1m]
840K    /var/lib/docker/containers/…/local-logs

Logs are capped at max-size × max-file ≈ 2 MB; the local driver compresses rotated files, so actual usage is usually much lower (about 840K above). json-file without rotation grows without limit.

Enable Engine Prometheus metrics
sudo python3 - <<'EOF'
import json, os
p = "/etc/docker/daemon.json"
d = json.load(open(p)) if os.path.exists(p) else {}
d["metrics-addr"] = "127.0.0.1:9323"
json.dump(d, open(p, "w"), indent=2)
EOF
sudo dockerd --validate --config-file /etc/docker/daemon.json && sudo systemctl restart docker
curl -s 127.0.0.1:9323/metrics | grep -E "^engine_daemon_(engine_info|container_states)" | head
engine_daemon_container_states_containers{state="paused"} 0
engine_daemon_container_states_containers{state="running"} 0
engine_daemon_container_states_containers{state="stopped"} 2
engine_daemon_engine_info{architecture="x86_64",…,version="29.9.3"} 1

Restarting Docker restarts the containers (unless live-restore is enabled). Bind the metrics port to 127.0.0.1 only; never expose it to the internet.

Case 1: a database blip caused every replica to be restarted

The health check hit /health, which queried the database. During a 30-second database failover, the orchestrator marked every API replica unhealthy and restarted them; the cold starts added even more load on the database, and the outage lasted 10 minutes. Fix: /healthz (liveness) checks only the process itself; /ready (readiness) checks dependencies and on failure only removes the replica from traffic, without restarting it.

Case 2: CPU limits caused latency spikes

A service with --cpus 0.5 averaged only 30% CPU, yet its P99 latency was high. Bursts of requests used up the 50 ms quota within a 100 ms period and were throttled. Confirm via nr_throttled/throttled_usec in cpu.stat. Remedy: raise the quota, or set only --cpu-shares (a weight) without a hard quota, while keeping a hard memory limit.

Case 3: a log backend outage took down the application

With the fluentd logging driver, when the fluentd service went down, the default blocking mode made the app block on writes to stdout and every request timed out. Fix: mode=non-blocking + a sensible max-buffer-size, accepting that some logs may be dropped in extreme cases; or switch to local/journald and let a node-level agent ship logs asynchronously.

Common errors and fixes

The container stays at health: starting

The check command keeps failing but is still within the grace period, or a long interval delays the first check. Look at the output in .State.Health.Log; confirm the check tool exists in the image; set --start-interval to detect readiness sooner.

Unhealthy, but a manual curl works

The check command runs inside the container: it uses the container's localhost and port, not the host port; the timeout may be too short; or a non-root user lacks permission. Reproduce with docker exec CTR CHECK_COMMAND; echo $?.

docker logs: configured logging driver does not support reading

In older versions, or with dual logging disabled, drivers such as syslog/fluentd don't support docker logs. Switch to local/json-file/journald, or read the logs in the backend.

docker update error: Memory limit should be smaller than already set memoryswap limit

When raising --memory, raise --memory-swap too: docker update --memory 1g --memory-swap 1g CTR.

curl 127.0.0.1:9323: connection refused

The daemon wasn't restarted after editing daemon.json, or a JSON syntax error kept the daemon from loading it (check first with dockerd --validate).

Learning resources

NoteWe could not find a verifiable video covering cgroup v2 and newer parameters such as start-interval, so this module relies on the official documentation.
or score ≥ 70% on the Quiz

Module 5 · Advanced Compose: variables, override merging, profiles and secrets

31:00 – 39:00 · One set of Compose files serving development, testing and single-host production
8 minCompose v5.xCompose Specification
Learning objectives
  • Tell .env (variable interpolation) apart from env_file/environment (container environment variables), and know their precedence.
  • Master the override-file merge rules and how to use !reset and !override; split large projects with include.
  • Manage optional services with profiles and inject sensitive data as files with secrets.
Lesson 1 recapFor naming rules, the three depends_on conditions, healthcheck dependencies, watch and scaling, see Lesson 1, Module 7.

What: don't confuse the two kinds of "variables"

Interpolation variables ${VAR}Container environment variables
RoleReplace text while Compose parses the YAML (ports, tags, image versions...)Become part of the container process's environment
Sources and precedence① current shell environment → ② the file given by --env-file → ③ .env in the project directory① docker compose run -e → ② environment: → ③ env_file: → ④ ENV in the image
Common syntax${PORT:-5000} default value; ${TAG:?TAG must be set} errors when missing; $$ is a literal $environment: {KEY: value} or list form

Don't commit the .env file to Git (add it to .gitignore); commit a .env.example as a template instead.

Why: override-file merge rules (official)

FieldHow it merges
compose.override.yamlLoaded automatically when in the same directory as compose.yaml; not loaded automatically once you use -f explicitly
Single-value fields such as image, command, restartLater files replace earlier ones
Lists such as ports, expose, dnsAppended (easily leads to ports being published twice)
environment, labelsMerged by key; on the same key the later file wins
volumes, devicesMerged by mount path in the container; on the same path the later file wins
!reset tagRemoves the field defined in earlier files, e.g. ports: !reset [], build: !reset null
!override tagReplaces entirely instead of merging, e.g. ports: !override ["127.0.0.1:5000:5000"]

How: splitting and reuse

  • include: (top level): pulls in another Compose file (e.g. a monitoring stack shared by a team); relative paths in the included file resolve against its own directory, which suits multi-team maintenance.
  • extends: (service level): reuses another service's configuration.
  • profiles:: services with a profile don't start by default; enable them with --profile debug or COMPOSE_PROFILES=debug.
  • secrets:: mounted as files at /run/secrets/<name> and never shown among the environment variables in docker inspect. Many official images support *_FILE variables (such as POSTGRES_PASSWORD_FILE).
  • COMPOSE_FILE environment variable: e.g. COMPOSE_FILE=compose.yaml:compose.prod.yaml, so you don't have to type several -f flags every time.

When: separating development from production

DevelopmentSingle-host production
Filescompose.yaml + the auto-loaded compose.override.yaml-f compose.yaml -f compose.prod.yaml
Imagebuild: .Immutable tag or digest from the registry (build: !reset null)
Code updatesBind-mount hot reload, or develop.watch (recommended)Pull the new image, up -d --wait
PortsPublished directlyBound to 127.0.0.1 only, behind a reverse proxy
SecretsLocal filesThe deployment process fetches them from Key Vault and writes the secrets files

Configuration loading and merge flow

shell environment .env / --env-file ① Variable interpolation${APP_PORT:-5000} compose.yaml compose.override / prod.yaml ② MergeSingle values replaced / lists appendedenvironment merged by keyvolumes merged by target path!reset / !overrideinclude / extends / profiles ③ Final modeldocker compose config
Figure 5-1 When troubleshooting, always start with the output of docker compose config

Merge result visualizer

compose.yaml
Override file
docker compose config (merged result)

Advanced Compose commands

CommandDescription
docker compose config / --services / --profiles / --variablesFinal config / service list / profile list / variables in use
docker compose --env-file .env.prod up -dSpecify the interpolation variable file
docker compose -f compose.yaml -f compose.prod.yaml up -dExplicit merge (override is no longer auto-loaded)
COMPOSE_FILE=compose.yaml:compose.prod.yaml docker compose up -dSpecify the file list with an environment variable
docker compose --profile debug up -d / COMPOSE_PROFILES=debugEnable a profile
docker compose up -d --no-deps webRebuild one service only, leaving its dependencies alone
docker compose up -d --force-recreate --waitForce recreate and wait until healthy
docker compose run --rm -e DEBUG=1 web python -VOne-off task (-e has the highest precedence)
docker compose lsList all Compose projects on the host

Lab 5: development / production dual mode (about 7 min)

.env and the upgraded compose.yaml
cd ~/myapp
cat > .env <<'EOF'
APP_PORT=5000
REDIS_TAG=7-alpine
EOF
printf '.env\nsecrets/\n' >> .gitignore
printf 'secrets/\ncompose*.yaml\n' >> .dockerignore     # key point: otherwise COPY . . bakes the secret files into the image
mkdir -p secrets && printf 'dev-api-key-123' > secrets/api_key.txt

cat > compose.yaml <<'EOF'
services:
  web:
    build: .
    image: myapp:dev
    ports:
      - "${APP_PORT:-5000}:5000"
    environment:
      REDIS_HOST: redis
    secrets:
      - api_key
    depends_on:
      redis:
        condition: service_healthy
    deploy:
      resources:
        limits:
          memory: 256M
          cpus: "0.5"
    stop_grace_period: 35s
    restart: unless-stopped

  redis:
    image: redis:${REDIS_TAG:?Please set REDIS_TAG in .env}
    volumes:
      - redis-data:/data
    healthcheck:
      test: ["CMD", "redis-cli", "ping"]
      interval: 5s
      timeout: 3s
      retries: 5
      start_period: 5s
      start_interval: 1s

  redis-monitor:
    image: redis:${REDIS_TAG}
    command: ["redis-cli", "-h", "redis", "monitor"]
    profiles: [debug]
    depends_on: [redis]

secrets:
  api_key:
    file: ./secrets/api_key.txt

volumes:
  redis-data:
EOF
Development override file (auto-loaded)
cat > compose.override.yaml <<'EOF'
services:
  web:
    volumes:
      - .:/app
    environment:
      FLASK_DEBUG: "1"
    command: ["flask", "--app", "app", "run", "--host=0.0.0.0", "--port=5000", "--debug"]
EOF
docker compose config | sed -n '/^  web:/,/^  [a-z]/p' | head -40
docker compose up -d --build --wait
curl localhost:5000
sed -i 's/Hello from/Hi from/' app.py; sleep 2; curl localhost:5000     # hot reload takes effect
docker compose exec web cat /run/secrets/api_key; echo
Hello from 9a8b7c6d5e4f, hits=1
Hi from 9a8b7c6d5e4f, hits=2
dev-api-key-123
profile: start a debug service on demand
docker compose --profile debug up -d
curl -s localhost:5000 >/dev/null
docker compose logs redis-monitor | tail -3      # you should see INCR hits
docker compose --profile debug stop redis-monitor
Production override file: !reset and !override
sed -i 's/Hi from/Hello from/' app.py
docker build -q -t myapp:1.1 .
cat > compose.prod.yaml <<'EOF'
services:
  web:
    build: !reset null
    image: myapp:1.1
    ports: !override
      - "127.0.0.1:5000:5000"
    environment:
      APP_ENV: prod
EOF
docker compose down
docker compose -f compose.yaml -f compose.prod.yaml config | grep -E "image:|published|host_ip|command|/app"
docker compose -f compose.yaml -f compose.prod.yaml up -d --wait
curl localhost:5000

Production mode doesn't load compose.override.yaml, so there is no bind mount and no flask debug; the ports are replaced entirely and bound only to 127.0.0.1.

Error when an interpolation variable is missing
REDIS_TAG= docker compose config >/dev/null; echo "exit=$?"
error while interpolating services.redis.image: required variable REDIS_TAG is missing a value: Please set REDIS_TAG in .env
exit=1

An empty value set in the shell (REDIS_TAG=) takes precedence over .env, and :? treats an empty value as missing too.

Clean up
docker compose -f compose.yaml -f compose.prod.yaml --profile debug down

Case 1: an override file "accidentally exposed" a port

An operator wrote ports: ["127.0.0.1:5000:5000"] in compose.prod.yaml, believing it replaced "5000:5000" from the base file. Because lists are appended, both publishing rules ended up in effect and the service was still open on 0.0.0.0. Fix: use ports: !override [...], and in CI check host_ip in the output of docker compose config.

Case 2: a monitoring stack shared by the platform team

The platform team maintains platform/observability.yaml (otel-collector, cAdvisor), and each product team adds include: [../platform/observability.yaml] at the top of its own compose.yaml. Platform upgrades change one place, and product teams' files stay clean.

Case 3: a password visible in docker inspect

An audit found the database password visible in docker inspect (it came from environment:). The team switched to Compose secrets + POSTGRES_PASSWORD_FILE=/run/secrets/db_password; the deployment pipeline reads the password from Azure Key Vault and writes it to the secrets file (mode 0400), and the file never goes into Git.

Common errors and fixes

WARN: The "APP_PORT" variable is not set. Defaulting to a blank string.

The variable is not defined and has no default. Provide a default with ${APP_PORT:-5000}, or fail immediately when missing with ${APP_PORT:?msg}. Note that .env must be in the project directory (the directory containing compose.yaml, or --project-directory).

Changed .env, but the container's environment variables didn't change

.env is only used for interpolation; only values referenced via ${VAR} in compose.yaml and written under environment reach the container. After changing it, run up -d so the container is recreated.

Debug mode was accidentally enabled in production

Someone ran docker compose up without -f on the production host, so compose.override.yaml was loaded automatically. Don't keep override files on production hosts, or always use COMPOSE_FILE.

service "web" refers to undefined secret api_key

The service references a secret that isn't defined under top-level secrets:, or the file: path doesn't exist.

port is already allocated (after adding an override file)

The ports list was appended, so the same host port is published twice. Use !override or !reset.

Learning resources

NoteMost Compose videos still use v1 docker-compose and the version: field, and don't cover !reset or include. This module relies on the official documentation.
or score ≥ 70% on the Quiz

Module 6 · Versioning strategy, multi-arch and CI/CD automation

39:00 – 47:00 · Every image traces back to a commit; every push is built, tagged and attested automatically
8 minbuild-push-action@v7 · metadata-action@v6Buildx Bake
Learning objectives
  • Design a tagging strategy: Git SHAs for deployment, semantic versions for releases, latest as just an alias; production deployments reference digests.
  • Use Bake (docker-bake.hcl) to write multi-image, multi-platform build parameters as code.
  • Write a current GitHub Actions workflow: automatic tags, multi-arch, caching, SBOM/provenance, with third-party Actions pinned by commit SHA.

What: tagging strategy

Tag typeExampleMutable?Purpose
Git commit SHAmyapp:sha-3f9a2c1Immutable (by convention)Deployment: each image maps to one commit; rolling back means switching to the old SHA
Semantic versionmyapp:1.4.2, 1.4, 11.4.2 is immutable; 1.4 / 1 movePublic releases, letting users choose their update granularity
Branch / PRmyapp:main, pr-12MutableTest environments
latestmyapp:latestMutableOnly a convenient alias for local pulls; never use it for deployment
digestmyapp@sha256:…Immutable (content hash)The final reference in deployment manifests (Lesson 1, Modules 2 and 8)

Anti-pattern: "environment tags" such as myapp:prod and myapp:stable: there is no way to know which version is actually live. ACR can lock tags (az acr repository update --write-enabled false) so they can't be overwritten.

Why: Bake, build parameters as code

Bake is part of Buildx. It describes several build targets (context, Dockerfile, tags, platforms, cache, args) in an HCL/JSON/Compose file and builds them in parallel with docker buildx bake. Compose v5 builds are also executed by Bake. Benefits: local and CI use the same definition; CI needs only one command; --print lets you review the final parameters.

How: three ways to build multi-arch

MethodHow it worksSpeedBest for
QEMU emulationsetup-qemu-action registers binfmt; arm64 steps run in the emulatorSlow (compile-heavy projects can be an order of magnitude slower)Interpreted languages, simple projects
Cross-compilationFROM --platform=$BUILDPLATFORM + TARGETARCH (Module 3)FastLanguages that support cross-compilation, such as Go, Rust and .NET
Native nodesarm64 runners / remote builder nodes build each platform separately, then the manifests are mergedFastLarge projects (GitHub offers hosted arm64 runners)

When: key decisions for CI workflows

  • Registry credentials: when pushing to GHCR, use the built-in GITHUB_TOKEN (with permissions: packages: write), no extra secrets needed; for Docker Hub use an access token, never a password; for ACR / ECR use OIDC federated identity (hour 5 shows the minimal setup; the GitHub course, hours 3–4, goes deeper).
  • PRs build but don't push: push: ${{ github.event_name != 'pull_request' }}.
  • Caching: cache-from/to: type=gha (GitHub Actions cache) or type=registry.
  • Supply-chain attestations: sbom: true, provenance: mode=max (note: mode=max records build args, see Module 2).
  • Pin third-party Actions: in the March 2026 Trivy supply-chain incident, attackers force-rewrote most version tags of aquasecurity/trivy-action (official advisory: 76 of 77 tags affected). Official advice: "Pinning to full commit SHAs remains the only truly immutable protection." Production workflows should pin Actions to full commit SHAs (Dependabot/Renovate can maintain them).

Pipeline from commit to image

git pushmain / tag / PR metadataGenerate tags and labels QEMU + BuildxPrepare the builder linux/amd64 linux/arm64 GHCR / Docker Hub / ACRimage index (multi-platform)+ SBOM + provenance GHA cache PR: build + test only, no push · main: sha-xxxx + main · tag v1.4.2: 1.4.2 / 1.4 / latest

Tag generator (simulates docker/metadata-action rules)

tags: |
  type=ref,event=branch
  type=ref,event=pr
  type=semver,pattern={{version}}
  type=semver,pattern={{major}}.{{minor}}
  type=sha

Pipeline animation

Buildx / Bake commands

CommandDescription
docker buildx bakeBuild all targets in the default group
docker buildx bake goapp --printPrint the resolved final build parameters (for review)
docker buildx bake --set goapp.platform=linux/arm64Override a property temporarily
TAG=1.4.2 docker buildx bake --pushOverride HCL variables with environment variables and push
docker buildx bake -f compose.yamlUse a Compose file directly as the Bake definition
docker buildx create --name multi --driver docker-container --useCreate a dedicated builder (supports more cache export types)
docker buildx imagetools inspect REF --format '{{json .SBOM}}'Show an image's SBOM (.Provenance also works)
docker buildx imagetools create -t REF:1.4 REF:1.4.2Add a tag on the registry side directly (no pull needed)
git describe --tags / git rev-parse --short HEADGenerate a version number / short SHA locally

Lab 6: Bake multi-image build + GitHub Actions workflow (about 8 min)

Prepare a Git version number
cd ~/myapp
git init -q 2>/dev/null; git add -A; git -c user.name=lab -c user.email=lab@example.com commit -qm "hour2 lab" || true
export TAG=sha-$(git rev-parse --short=7 HEAD); echo $TAG
Write ~/docker-bake.hcl
variable "TAG"      { default = "dev" }
variable "REGISTRY" { default = "local" }

group "default" {
  targets = ["myapp", "goapp"]
}

target "_common" {
  labels = {
    "org.opencontainers.image.source" = "https://github.com/yourname/docker-lab"
  }
}

target "myapp" {
  inherits = ["_common"]
  context  = "./myapp"
  tags     = ["${REGISTRY}/myapp:${TAG}"]
}

target "goapp" {
  inherits  = ["_common"]
  context   = "./goapp"
  tags      = ["${REGISTRY}/goapp:${TAG}"]
  platforms = ["linux/amd64", "linux/arm64"]
}

target "goapp-test" {
  context = "./goapp"
  target  = "test"
}
cd ~
cat > docker-bake.hcl   # paste the content above, end with Ctrl+D
docker buildx bake --print goapp | head -30
docker buildx bake goapp-test          # run the tests first
docker buildx bake                     # build both images in parallel
docker image ls --format '{{.Repository}}:{{.Tag}}' | grep "^local/"
local/goapp:sha-3f9a2c1
local/myapp:sha-3f9a2c1

goapp is built for two platforms; a fresh Engine 29 install uses the containerd image store by default and can load multi-platform results directly. The classic overlay2 store needs --push instead.

GitHub Actions workflow (put it in .github/workflows/docker.yml in your GitHub repository)
name: build-and-push
on:
  push:
    branches: [main]
    tags: ["v*.*.*"]
  pull_request:

permissions:
  contents: read
  packages: write          # push to GHCR

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      # In production, replace each @vX below with the full commit SHA and add a comment naming the version
      - uses: actions/checkout@v6

      - id: meta
        uses: docker/metadata-action@v6
        with:
          images: ghcr.io/${{ github.repository_owner }}/myapp
          tags: |
            type=ref,event=branch
            type=ref,event=pr
            type=semver,pattern={{version}}
            type=semver,pattern={{major}}.{{minor}}
            type=sha

      - uses: docker/setup-qemu-action@v4
      - uses: docker/setup-buildx-action@v4

      - if: github.event_name != 'pull_request'
        uses: docker/login-action@v4
        with:
          registry: ghcr.io
          username: ${{ github.actor }}
          password: ${{ secrets.GITHUB_TOKEN }}

      - uses: docker/build-push-action@v7
        with:
          context: ./myapp
          platforms: linux/amd64,linux/arm64
          push: ${{ github.event_name != 'pull_request' }}
          tags: ${{ steps.meta.outputs.tags }}
          labels: ${{ steps.meta.outputs.labels }}
          cache-from: type=gha
          cache-to: type=gha,mode=max
          sbom: true
          provenance: mode=max

Action versions follow the examples in Docker's official documentation (2026-11): build-push-action@v7, metadata-action@v6, login/setup-qemu/setup-buildx@v4, checkout@v6. To push to Docker Hub, drop the registry and change the username/password to secrets.DOCKERHUB_USERNAME / secrets.DOCKERHUB_TOKEN (an access token).

(Optional) push and verify the attestations: push the code to GitHub, and once the workflow succeeds, run this on the VM
docker buildx imagetools inspect ghcr.io/<your-username>/myapp:main
docker buildx imagetools inspect ghcr.io/<your-username>/myapp:main --format '{{json .SBOM.SPDX.packages}}' | head -c 400; echo

GHCR packages are private by default; run docker login ghcr.io (with a PAT that has read:packages) before pulling.

Case 1: a rollback takes only 30 seconds

Every deployment references a sha-xxxxxxx tag (or its digest), and deployment records live in Git. When a problem appears, change the deployment manifest back to the previous SHA and redeploy; the rollback is auditable and repeatable. Teams using latest first have to work out which image "the previous latest" was.

Case 2: arm64 builds dropped from 40 minutes to 4

A Go + front-end repository built arm64 in QEMU, so both the front-end npm ci and the Go compile ran in the emulator. The fix: the Go stage cross-compiles with --platform=$BUILDPLATFORM; the front-end artifacts are architecture-independent, so they are built in a $BUILDPLATFORM stage too; only the final runtime stage differs per platform.

Case 3: tampered Action tags

Starting on March 19, 2026, many version tags of aquasecurity/trivy-action were force-rewritten to point at malicious commits; workflows referencing them by tag ran malicious code on the runner and leaked secrets (Aqua's official advisory). Workflows pinned by commit SHA were unaffected. Lesson: third-party Actions and scanner images in CI are part of your supply chain too; pin their versions, use least privilege (permissions:), and scope runner secrets as narrowly as possible.

Common errors and fixes

denied: installation not allowed to Create organization package (pushing to GHCR)

The workflow lacks permissions: packages: write, or the organization doesn't allow Actions to create packages. Check the repository/organization Packages settings.

ERROR: docker exporter does not currently support exporting manifest lists

You used --load for a multi-platform result on the classic store. Enable the containerd image store, switch to --push, or load one platform at a time.

exec /bin/sh: exec format error (building arm64 in CI)

QEMU binfmt isn't registered. Add docker/setup-qemu-action before setup-buildx, or switch to cross-compilation / native arm64 runners.

CI downloads dependencies every time; the cache doesn't work

cache-to isn't configured (only cache-from); or mode=min caches only the final stage; or the build context contains files that change on every run.

metadata-action doesn't generate latest

By default (flavor latest=auto) latest is generated only when a semver tag is pushed. To tag latest on main as well, add type=raw,value=latest,enable={{is_default_branch}}, but remember that latest should not be used for deployment.

Verified videos

▶
GitHub Actions Tutorial - Basic Concepts and CI/CD Pipeline with Docker — TechWorld with Nana
32:31 · 2020-10-08 · English · GitHub Actions basics and a Docker pipeline
Version noteThis video was recorded in 2020; its Action versions and login method are outdated. Follow the workflow on this page (build-push-action@v7, metadata-action@v6, login/setup-*@v4, checkout@v6) and pin by commit SHA.

Official documentation

or score ≥ 70% on the Quiz

Module 7 · Security hardening: three lines of defense (image, runtime, daemon)

47:00 – 54:00 · Run with least privilege, and prove with commands that it really is least privilege
7 minseccomp · AppArmor · capabilitiesRootless mode
Learning objectives
  • Master the runtime hardening flags and verify through /proc/1/status that capabilities, NoNewPrivs and seccomp are in effect.
  • Understand the differences between rootless mode and userns-remap and when to use each.
  • Scan images for vulnerabilities without mounting docker.sock, and learn the lessons of the 2026 Trivy supply-chain incident.

What: three lines of defense

LayerMeasuresCovered in
ImageMinimal base image, non-root, no secrets, pinned versions/digests, vulnerability scanning, SBOMModules 2, 3, 6; scanning in this module
RuntimeRead-only root filesystem, drop capabilities, no privilege escalation, resource limits, no --privileged, no docker.sock mount, avoid host networkingThis module
Daemon / hostRootless or userns-remap, control docker group membership, never expose an unencrypted TCP API, patch promptly, CIS Docker BenchmarkThis module + Lesson 1, Module 0

Why: the runtime flags explained one by one

FlagEffectHow to verify
--user 10001:10001 (or USER in the image)Non-root inside the containerdocker exec CTR id
--read-only + --tmpfs /tmpRead-only root filesystem, so attackers can't tamper with the program; only the necessary directories are writabledocker exec CTR touch /app/x should fail
--cap-drop ALL (--cap-add as needed)Drops all Linux capabilities (about 14 are kept by default)grep CapEff /proc/1/status is all zeros
--security-opt no-new-privilegesBlocks privilege escalation via setuid programs and the likegrep NoNewPrivs /proc/1/status is 1
Default seccomp profileBlocks dozens of dangerous system calls (enabled by default; never use seccomp=unconfined)grep Seccomp /proc/1/status is 2
AppArmor docker-defaultMAC policy enabled by default on Ubuntudocker inspect -f '{{.AppArmorProfile}}' CTR
--pids-limit / --memory / --cpusPrevents resource-exhaustion attacksModule 4
Three "nevers"① --privileged: gives the container almost all host privileges (every capability, every device, seccomp/AppArmor disabled). ② -v /var/run/docker.sock:/var/run/docker.sock: equivalent to handing host root to the container. ③ -H tcp://0.0.0.0:2375: exposes an unencrypted, unauthenticated Docker API.

How: rootless and userns-remap

Rootless modeuserns-remap
Daemon identitydockerd and containers run as an ordinary userdockerd is still root
Root in the container maps toThat ordinary user on the host (and its subuid range)An unprivileged subuid range on the host
Installationdockerd-rootless-setuptool.sh install (needs uidmap and ≥65536 subuids/subgids)"userns-remap": "default" in daemon.json
CaveatsSome features are limited (e.g. ports below 1024, and some networking and resource limits need extra setup); see the official Known limitations. Ubuntu 24.04+ may need AppArmor configured as the install script promptsIn Engine 29, a daemon with userns-remap enabled doesn't use the containerd image store by default (official release notes); volume and bind-mount permissions need re-planning
Best forShared development machines, CI runners, single-host services with strict security requirementsCases where the system-wide dockerd must stay

When: where vulnerability scanning belongs

  • In CI: scan after building and before pushing; block on HIGH,CRITICAL findings that have a fixed version (--ignore-unfixed).
  • In the registry: scan continuously (Microsoft Defender for Containers, Docker Scout, etc.), because new vulnerabilities are published every day.
  • The scanner itself is part of the supply chain: in the March 2026 Trivy incident, the v0.69.4 binary, the Docker Hub images 0.69.5/0.69.6 and many trivy-action tags were injected with malicious code (Aqua's official advisory). Pin to a verified version (after the incident the vendor recommended v0.69.2 / v0.69.3; check Aqua's latest advisory) or a digest; never use latest.

Container isolation boundaries

Host kernel (shared by all containers) seccompSystem call filteringDefault profile blocksmount, reboot,kexec_load … capabilitiesRoot privileges split up--cap-drop ALLAdd back as neededNET_BIND_SERVICE AppArmordocker-defaultRestricts /proc, /sysmounts and writes namespacespid · net · mntuser (rootless /userns-remap) cgroupsMemory / CPUPIDs / IO --privileged tears down all three walls at once: seccomp, AppArmor and capabilities

Security scorer: tick options to generate commands and Compose snippets live


      

    

Security commands

CommandDescription
docker info --format '{{.SecurityOptions}}'Security features enabled on the daemon (apparmor, seccomp, rootless, userns)
docker inspect -f '{{.HostConfig.CapDrop}} {{.HostConfig.ReadonlyRootfs}} {{.HostConfig.SecurityOpt}} {{.HostConfig.Privileged}}' CTRAudit a container's security configuration
docker exec CTR grep -E 'Cap(Eff|Bnd)|NoNewPrivs|Seccomp' /proc/1/statusVerify at the kernel level
docker ps -q | xargs docker inspect -f '{{.Name}} privileged={{.HostConfig.Privileged}}'Find privileged containers
docker image save IMG -o img.tar + trivy image --input img.tarScanning without mounting docker.sock
docker scout cves IMGDocker Scout (bundled with Docker Desktop; on Linux install the CLI plugin and log in)
dockerd-rootless-setuptool.sh installInstall rootless mode

Lab 7: hardened run, kernel-level verification, offline scanning (about 6 min)

Run myapp hardened
docker run -d --name sec \
  --read-only --tmpfs /tmp \
  --cap-drop ALL \
  --security-opt no-new-privileges \
  --pids-limit 100 --memory 256m \
  -p 127.0.0.1:5000:5000 myapp:1.1
sleep 2; curl localhost:5000         # the app works as usual (hits=N/A without redis)
Prove the hardening with kernel data
docker exec sec id
docker exec sec touch /app/hacked || echo "root filesystem is read-only ✓"
docker exec sec grep -E 'CapEff|NoNewPrivs|Seccomp:' /proc/1/status
docker inspect -f 'apparmor={{.AppArmorProfile}}' sec
uid=1000(appuser) gid=1000(appuser) groups=1000(appuser)
touch: cannot touch '/app/hacked': Read-only file system
root filesystem is read-only ✓
CapEff: 0000000000000000
NoNewPrivs:     1
Seccomp:        2
apparmor=docker-default
Compare: a default container vs a --privileged container
docker run --rm alpine:3.22 grep -E 'CapEff|Seccomp:' /proc/1/status
docker run --rm --privileged alpine:3.22 grep -E 'CapEff|Seccomp:' /proc/1/status
docker run --rm -v /:/host alpine:3.22 head -1 /host/etc/shadow   # direct proof that docker group = root
CapEff: 00000000a80425fb
Seccomp:        2
CapEff: 000001ffffffffff
Seccomp:        0
root:*:…
Vulnerability scanning without mounting docker.sock
TRIVY_VERSION=0.69.3   # one of the safe versions recommended after the incident; check Aqua's release page for the latest safe version and digest
mkdir -p ~/scan && docker image save myapp:1.1 -o ~/scan/myapp.tar
docker run --rm -v ~/scan:/scan -v trivy-cache:/root/.cache/ \
  aquasec/trivy:$TRIVY_VERSION image --input /scan/myapp.tar \
  --severity HIGH,CRITICAL --ignore-unfixed --exit-code 1
echo "exit=$?   # 1 means fixable high/critical vulnerabilities exist; CI blocks on this"
docker run --rm -v ~/scan:/scan -v trivy-cache:/root/.cache/ aquasec/trivy:$TRIVY_VERSION \
  image --input /scan/myapp.tar --format cyclonedx --output /scan/sbom.json && ls -lh ~/scan
(Optional, preferably on a separate VM) Rootless mode
sudo apt-get install -y uidmap docker-ce-rootless-extras
grep "^$(whoami):" /etc/subuid /etc/subgid          # need ≥ 65536
sudo systemctl disable --now docker.service docker.socket   # official advice: disable the system-wide dockerd first
dockerd-rootless-setuptool.sh install                # follow the prompts for prerequisites such as AppArmor
export DOCKER_HOST=unix:///run/user/$(id -u)/docker.sock
docker info --format '{{.SecurityOptions}}'          # includes name=rootless
docker run -d --name r1 alpine:3.22 sleep 300
ps -o user,pid,cmd -C sleep                          # on the host the process belongs to your user, not root

When finished, restore with dockerd-rootless-setuptool.sh uninstall and sudo systemctl enable --now docker.

Clean up
docker rm -f sec

Case 1: a monitoring agent requires mounting docker.sock

A third-party monitoring container required -v /var/run/docker.sock:/var/run/docker.sock to discover containers. Risk: once that container is compromised, the attacker has host root. Mitigation: prefer collection methods that don't need the socket (read-only cgroup/procfs mounts, the OpenTelemetry Collector docker_stats receiver behind a read-only proxy); if you must use it, restrict the API through a GET-only socket proxy (such as docker-socket-proxy).

Case 2: rolling out a read-only root filesystem

After enabling --read-only the service failed to start: gunicorn needs to write worker heartbeat files to /tmp, and nginx needs to write /var/cache/nginx and /var/run. Approach: first use docker diff in a test environment to find the directories written at run time, then provide writable paths one by one with --tmpfs or volumes.

Case 3: mapping to Kubernetes

securityContext:
  runAsNonRoot: true                 # ↔ USER / --user
  readOnlyRootFilesystem: true       # ↔ --read-only
  allowPrivilegeEscalation: false    # ↔ no-new-privileges
  capabilities: { drop: ["ALL"] }    # ↔ --cap-drop ALL
  seccompProfile: { type: RuntimeDefault }   # ↔ default seccomp

On AKS this can be enforced with Pod Security Admission (restricted level) or Azure Policy, which Hours 3 and 5 use.

Common errors and fixes

Read-only file system (after enabling --read-only)

Find the directories that need writes (docker diff, application logs) and mount --tmpfs or volumes for them. Logs should go to stdout, not files.

bind: permission denied (listening on port 80 after cap-drop ALL)

Without root or capabilities you can't bind ports below 1024. Have the app listen on a high port such as 8080 and map it with -p 80:8080, or use --cap-add NET_BIND_SERVICE.

chown: Operation not permitted (in the entrypoint script)

--cap-drop ALL removed CHOWN. Set ownership at build time with COPY --chown instead of changing it at run time.

Rootless: docker: Cannot connect to the Docker daemon at unix:///var/run/docker.sock

The client still points at the system socket. Set DOCKER_HOST=unix:///run/user/$UID/docker.sock, or use docker context use rootless (the install script creates that context).

Trivy scans are slow / keep re-downloading the vulnerability DB

Mount a volume for the cache directory (like trivy-cache above); cache the database directory in CI; in offline environments use a mirrored vulnerability database.

Learning resources

NoteThe container security videos we found could not be verified by video ID, uploader or length, so none are listed. Below are official and authoritative sources.
or score ≥ 70% on the Quiz

Module 8 · Production readiness review and failure drills

54:00 – 60:00 · Test the first 7 modules with one checklist, one script and six real failures
6 minReview script review.shBridge to Kubernetes
Learning objectives
  • Check any containerized service with one review checklist (image / runtime / observability / release / security).
  • Turn the checklist into repeatable checks with an automated script.
  • Practice the "symptom → evidence → root cause → fix" troubleshooting approach through failure drills.

Production readiness review checklist

CategoryCheckVerification command / locationModule
ImageMulti-stage build, minimal base imagedocker image ls, Dockerfile3
Non-root userdocker image inspect -f '{{.Config.User}}'3, 7
Started in exec form; PID 1 is the application-f '{{json .Config.Entrypoint}}{{json .Config.Cmd}}'1
No secrets; OCI labels presentdocker history --no-trunc, Labels2, 6
RuntimeMemory / CPU / PIDs limitsdocker inspect -f '{{.HostConfig.Memory}}'4
Restart policy and stop timeout aligned with the app's graceful shutdownRestartPolicy, stop_grace_period1
Ports bound only to the necessary addressesdocker port5
ObservabilityHEALTHCHECK checks only itself, with sensible parameters.State.Health4
Logs go to stdout and are rotated.HostConfig.LogConfig4
ReleaseImmutable tags (SHA/semver); deployments reference digestsDeployment manifest6
CI builds automatically, multi-arch, cached, SBOM/provenance; Actions pinned by SHAWorkflow file6
SecurityRead-only root filesystem, cap-drop ALL, no-new-privileges, unprivileged, no docker.sock mount/proc/1/status7
Scan before pushing; scanner version pinnedCI logs7

Mapping from Docker to Kubernetes

In this lessonKubernetes equivalent
Resource limits / reservations (Module 4)resources.limits / resources.requests
HEALTHCHECK (Module 4)livenessProbe / readinessProbe / startupProbe (K8s ignores the image's HEALTHCHECK)
stop_grace_period, graceful shutdown (Module 1)terminationGracePeriodSeconds, preStop
Environment variables / secrets (Module 5)ConfigMap / Secret (or the Key Vault CSI driver)
Security flags (Module 7)securityContext, Pod Security Admission
Image tags / digests (Module 6)Deployment rolling updates and rollback (kubectl rollout undo)
Compose profiles / override files (Module 5)Kustomize overlays / Helm values

Hour 3 (docker-hour3) deploys myapp to Azure Container Apps and moves on to Kubernetes.

Troubleshooting approach: symptom → evidence → root cause → fix → prevention

Symptom502s, restarts, slowness Evidenceps -a · logs · inspect Root causeCheck against the 8 modules FixMinimal change Preventioncheck / CI / review "Prevention" is the step most often skipped: turn this root cause into a build check, a CI rule or an item in the review script

Failure drills (6 scenarios)

Read the symptom and evidence, pick what you think the root cause is, then look at the fix.

Review script review.sh

Save it as ~/review.sh and chmod +x it. Usage: ./review.sh <image> [container].

#!/usr/bin/env bash
# Quick production readiness review: ./review.sh <image> [container]
IMG="$1"; CTR="$2"
ok(){ printf '  \033[32mPASS\033[0m %s\n' "$*"; }
no(){ printf '  \033[31mFAIL\033[0m %s\n' "$*"; }
ii(){ docker image inspect -f "$1" "$IMG"; }

echo "== Image: $IMG"
u=$(ii '{{.Config.User}}')
if [ -n "$u" ] && [ "$u" != root ] && [ "$u" != 0 ]; then ok "non-root user ($u)"; else no "runs as root (no USER)"; fi
if [ -n "$(ii '{{if .Config.Healthcheck}}y{{end}}')" ]; then ok "HEALTHCHECK defined"; else no "no HEALTHCHECK"; fi
cmd="$(ii '{{json .Config.Entrypoint}} {{json .Config.Cmd}}')"
if echo "$cmd" | grep -q '"/bin/sh","-c"'; then no "starts in shell form: $cmd"; else ok "starts in exec form: $cmd"; fi
if [ -n "$(ii '{{index .Config.Labels "org.opencontainers.image.source"}}')" ]; then ok "has OCI source label"; else no "missing org.opencontainers.image.source label"; fi
mb=$(( $(ii '{{.Size}}') / 1024 / 1024 ))
if [ "$mb" -lt 300 ]; then ok "image size ${mb}MB"; else no "large image ${mb}MB (consider multi-stage / slim)"; fi
if docker history --no-trunc "$IMG" | grep -qiE '(token|password|secret|apikey)='; then no "history may contain secrets"; else ok "no obvious secrets in history"; fi

[ -z "$CTR" ] && exit 0
ci(){ docker inspect -f "$1" "$CTR"; }
echo "== Container: $CTR"
[ "$(ci '{{.HostConfig.ReadonlyRootfs}}')" = true ] && ok "read-only root filesystem" || no "root filesystem is writable"
ci '{{.HostConfig.CapDrop}}' | grep -qi all && ok "cap-drop ALL" || no "capabilities not dropped"
ci '{{.HostConfig.SecurityOpt}}' | grep -q no-new-privileges && ok "no-new-privileges" || no "no-new-privileges not set"
[ "$(ci '{{.HostConfig.Privileged}}')" = false ] && ok "unprivileged container" || no "privileged container!"
[ "$(ci '{{.HostConfig.Memory}}')" != 0 ] && ok "memory limit set" || no "no memory limit"
p=$(ci '{{.HostConfig.PidsLimit}}'); [ "$p" != "<nil>" ] && [ "$p" != 0 ] && ok "pids limit $p" || no "no pids limit"
r=$(ci '{{.HostConfig.RestartPolicy.Name}}'); [ -n "$r" ] && [ "$r" != no ] && ok "restart policy $r" || no "no restart policy"
lt=$(ci '{{.HostConfig.LogConfig.Type}}'); lo=$(ci '{{.HostConfig.LogConfig.Config}}')
{ [ "$lt" = local ] || echo "$lo" | grep -q max-size; } && ok "logs are rotated ($lt)" || no "logs not rotated ($lt, no max-size)"
ci '{{range .Mounts}}{{.Source}} {{end}}' | grep -q docker.sock && no "docker.sock is mounted!" || ok "docker.sock not mounted"
ci '{{range $p, $b := .NetworkSettings.Ports}}{{range $b}}{{.HostIp}} {{end}}{{end}}' | grep -qE '(^| )(0\.0\.0\.0|::)( |$)' \
  && no "port published on all addresses" || ok "ports not open on all addresses"

The script is only a quick check; it doesn't replace a human review or a formal compliance scan (such as the CIS Docker Benchmark).

Lab 8: review three images / containers (about 5 min)

Prepare the script: save review.sh from the "Commands" tab to ~/review.sh, then run chmod +x ~/review.sh.
Review a container with "default settings"
docker run -d --name plain -p 8088:80 nginx:alpine
~/review.sh nginx:alpine plain
== Image: nginx:alpine
  FAIL runs as root (no USER)
  FAIL no HEALTHCHECK
  PASS starts in exec form: ["/docker-entrypoint.sh"] ["nginx","-g","daemon off;"]
…
== Container: plain
  FAIL root filesystem is writable
  FAIL capabilities not dropped
…
  FAIL port published on all addresses
Review the goapp built in this lesson
docker run -d --name goprod --read-only --cap-drop ALL --security-opt no-new-privileges \
  --memory 64m --pids-limit 50 --restart unless-stopped --log-driver local \
  -p 127.0.0.1:8080:8080 goapp:slim
~/review.sh goapp:slim goprod

Expected: everything PASSes except "missing OCI source label" (goapp's Dockerfile has no LABEL; local/goapp built with Bake does).

Fix and re-review: add LABEL org.opencontainers.image.source="https://github.com/yourname/docker-lab" to goapp's runtime stage, rebuild and review again until everything PASSes.
docker rm -f plain goprod

Case: turning the review into pipeline gates

A platform team split the checklist into three kinds of automated checks: ① at build time, build checks with # check=error=true and Hadolint; ② before pushing, a Trivy scan (pinned version) + image metadata checks (non-root, HEALTHCHECK, OCI labels, implemented with a script like review.sh or OPA/Conftest policies); ③ at deploy time, Compose/K8s manifest policies (forbid privileged, require readOnlyRootFilesystem, require resource limits, via Azure Policy / Pod Security Admission on AKS). Human reviewers focus only on design issues the automation can't cover.

How this connects to Hours 3 and 5

  • Hour 3: push the reviewed myapp to ACR, deploy it to Azure Container Apps (revisions, traffic splitting and rollback), and move on to Kubernetes.
  • Hour 5: image CI pipelines, tagging and promotion, SBOMs and vulnerability scanning, signing and verification, release and rollback (Azure and AWS side by side).

Common issues in this lesson

SymptomCheck firstMost likely root causeModule
stop always takes 10 seconds, exit code 137/proc/1/cmdlinePID 1 is sh, or the app doesn't handle SIGTERM1
Variable empty in RUNdocker build --checkARG not redeclared inside the stage2
Token appears in historydocker history --no-truncSecret passed via ARG/ENV2
exec /app: no such file or directoryThe file commandDynamically linked binary in static/scratch3
Stuck at health: starting.State.Health.LogCheck tool missing / bad parameters4
Disk filled by logsLogConfigjson-file without rotation4
Production port still exposeddocker compose configports list appended during merge5
exec format error on arm64 nodesimagetools inspectOnly one architecture was built6
Fails to start after going read-onlydocker diffNo tmpfs for a directory that needs writes7
or score ≥ 70% on the Quiz

Command cheat sheet (Hour 2)

Engine 29.x · Compose v5.x · Buildx/Bake · GitHub Actions (2026-11)
After-class reference

Startup and shutdown

ENTRYPOINT ["docker-entrypoint.sh"]      # last line of the script: exec "$@"
CMD ["gunicorn","-b","0.0.0.0:5000","app:app"]
STOPSIGNAL SIGTERM
docker run IMG -w 4                       # replaces CMD only
docker run --entrypoint sh -it IMG        # override the entrypoint
docker exec CTR sh -c 'cat /proc/1/cmdline | tr "\0" " "'
docker stop -t 30 CTR; docker run --stop-timeout 30 --init IMG
# Compose: stop_signal / stop_grace_period: 35s / init: true

Advanced Dockerfile

# syntax=docker/dockerfile:1
# check=error=true
ARG BASE=3.13
FROM python:${BASE}-slim
ARG BASE                                   # redeclare inside the stage
ARG TARGETARCH
RUN --mount=type=secret,id=token,env=TOKEN ./fetch.sh
RUN --mount=type=ssh git clone git@github.com:org/lib.git
RUN --mount=type=cache,target=/root/.cache/pip pip install -r req.txt
COPY --chmod=0755 --chown=10001:10001 run.sh /usr/local/bin/
RUN <<EOF
set -eux
apt-get update && apt-get install -y --no-install-recommends curl
rm -rf /var/lib/apt/lists/*
EOF

Builds and multi-stage

docker build --check .
docker build --secret id=token,src=token.txt --ssh default -t app .
docker build --target test .
docker build --build-arg GO_VERSION=1.27 -t app .
docker buildx build --platform linux/amd64,linux/arm64 -t REG/app:TAG --push .
docker history --no-trunc IMG
docker run --rm -it --pid container:CTR --network container:CTR busybox:1.37 sh

Resources · health · observability

docker run --memory 512m --memory-reservation 256m --cpus 1 --pids-limit 200 IMG
docker update --memory 1g --memory-swap 1g CTR
HEALTHCHECK --interval=10s --timeout=2s --start-period=20s --start-interval=1s --retries=3 CMD …
docker inspect -f '{{json .State.Health}}' CTR
docker ps --filter health=unhealthy
docker events --filter container=CTR --format '{{.Time}} {{.Action}}'
docker run --log-driver local --log-opt max-size=10m --log-opt max-file=3 IMG
# daemon.json: "metrics-addr": "127.0.0.1:9323" → curl 127.0.0.1:9323/metrics

Advanced Compose

docker compose config [--variables|--profiles]
docker compose -f compose.yaml -f compose.prod.yaml up -d --wait
COMPOSE_FILE=compose.yaml:compose.prod.yaml docker compose up -d
docker compose --profile debug up -d
docker compose --env-file .env.prod config
image: redis:${REDIS_TAG:?must be set}      ports: !override ["127.0.0.1:5000:5000"]
build: !reset null                       include: [../platform/observability.yaml]
secrets: { api_key: { file: ./secrets/api_key.txt } }   # → /run/secrets/api_key

Release and CI

docker buildx bake --print; docker buildx bake; TAG=1.4.2 docker buildx bake --push
docker buildx imagetools inspect REF --format '{{json .Provenance}}'
docker buildx imagetools create -t REF:1.4 REF:1.4.2
# GitHub Actions (pin by commit SHA in production):
#   actions/checkout@v6  docker/metadata-action@v6
#   docker/setup-qemu-action@v4  docker/setup-buildx-action@v4
#   docker/login-action@v4  docker/build-push-action@v7
#   with: sbom: true / provenance: mode=max / cache-from: type=gha

Security

docker run --read-only --tmpfs /tmp --cap-drop ALL --security-opt no-new-privileges \
  --user 10001:10001 --pids-limit 100 --memory 256m IMG
docker exec CTR grep -E 'CapEff|NoNewPrivs|Seccomp:' /proc/1/status
docker info --format '{{.SecurityOptions}}'
docker image save IMG -o img.tar
docker run --rm -v $PWD:/scan aquasec/trivy:<pinned-version> image --input /scan/img.tar --severity HIGH,CRITICAL --ignore-unfixed
dockerd-rootless-setuptool.sh install

Review

~/review.sh IMG [CTR]           # Module 8
docker inspect -f '{{.HostConfig.Privileged}} {{.HostConfig.ReadonlyRootfs}} {{.HostConfig.CapDrop}}' CTR
docker ps -q | xargs docker inspect -f '{{.Name}} mem={{.HostConfig.Memory}} pids={{.HostConfig.PidsLimit}}'

Capstone lab + final exam

Turn myapp into a production-grade service that passes the review
After class ≈ 30 minCovers Modules 1–8
TaskMake the following changes in ~/myapp, then review it with ~/review.sh: everything must PASS, and the Trivy scan must show no "fixable critical vulnerabilities".
Dockerfile: multi-stage (venv built in builder), entrypoint script with exec "$@", non-root (fixed UID 10001), HEALTHCHECK with start-interval, OCI labels, # check=error=true.
compose.prod.yaml: immutable image tag, ports !override to 127.0.0.1, read-only root filesystem + tmpfs, cap_drop ALL, no-new-privileges, memory/CPU/PIDs limits, log rotation, secrets, stop_grace_period.
Build: build a sha-xxxxxxx tag with docker-bake.hcl; (optional) push to GitHub to trigger the workflow.
Verify: docker compose -f compose.yaml -f compose.prod.yaml up -d --wait; ~/review.sh; offline Trivy scan; time docker compose stop web under 2 seconds.
Reference answer: Dockerfile
# syntax=docker/dockerfile:1
# check=error=true
ARG PYTHON_VERSION=3.13

FROM python:${PYTHON_VERSION}-slim AS builder
ENV PIP_DISABLE_PIP_VERSION_CHECK=1
RUN python -m venv /opt/venv
ENV PATH="/opt/venv/bin:$PATH"
COPY requirements.txt .
RUN --mount=type=cache,target=/root/.cache/pip pip install -r requirements.txt

FROM python:${PYTHON_VERSION}-slim AS runtime
LABEL org.opencontainers.image.source="https://github.com/yourname/docker-lab" \
      org.opencontainers.image.title="myapp"
RUN useradd --uid 10001 --create-home appuser
WORKDIR /app
COPY --from=builder /opt/venv /opt/venv
ENV PATH="/opt/venv/bin:$PATH" PYTHONUNBUFFERED=1 PYTHONDONTWRITEBYTECODE=1
COPY --chmod=0755 docker-entrypoint.sh /usr/local/bin/
COPY --chown=10001:10001 app.py .
USER 10001:10001
EXPOSE 5000
HEALTHCHECK --interval=15s --timeout=3s --start-period=10s --start-interval=1s --retries=3 \
  CMD ["python", "-c", "import socket; socket.create_connection(('127.0.0.1', 5000), 2)"]
# TCP check only: myapp's "/" increments the redis counter, so it is unsuitable as a health check (adding /healthz would be better)
ENTRYPOINT ["docker-entrypoint.sh"]
CMD ["gunicorn", "-b", "0.0.0.0:5000", "-w", "2", "--graceful-timeout", "20", "app:app"]
Reference answer: compose.prod.yaml
services:
  web:
    build: !reset null
    image: local/myapp:${TAG:?set TAG, e.g. sha-3f9a2c1}
    ports: !override
      - "127.0.0.1:5000:5000"
    environment:
      APP_ENV: prod
    read_only: true
    tmpfs:
      - /tmp
    cap_drop: [ALL]
    security_opt: ["no-new-privileges:true"]
    deploy:
      resources:
        limits: { cpus: "0.5", memory: 256M, pids: 100 }
    stop_grace_period: 25s          # longer than --graceful-timeout 20
    logging:
      driver: local
      options: { max-size: "10m", max-file: "3" }
    restart: unless-stopped
  redis:
    read_only: true
    cap_drop: [ALL]
    cap_add: [SETUID, SETGID]       # the official redis entrypoint uses gosu to switch to the redis user
    security_opt: ["no-new-privileges:true"]
    deploy:
      resources:
        limits: { memory: 128M, pids: 64 }

The official redis image's entrypoint starts as root, drops privileges with gosu/setpriv and may chown /data. With strict hardening you need to keep a few capabilities as required, or switch to user: "999:999" and prepare the volume permissions in advance. Verify each item in a test environment.

Open self-check (answer first, then expand)

1. Why should CMD use the JSON array form? What goes wrong in the cloud with shell form?

In exec form the application is PID 1, receives SIGTERM and shuts down gracefully. In shell form PID 1 may be sh, which doesn't forward signals, so the container is SIGKILLed after 10 seconds, slowing rolling updates and cutting off in-flight requests. Modern shells exec a single command directly, but that is a coincidence you can't rely on.

2. Why does a multi-stage build make the image so much smaller? What does the final image contain?

The compiler toolchain exists only in the build stages; the final image contains only the last stage (or the one given by --target), plus artifacts copied with COPY --from.

3. A container's exit code is 137. What is your first suspicion, and how do you verify it?

Suspect OOM first: docker inspect -f '{{.State.OOMKilled}}'; if false, check whether stop timed out (PID 1 signal handling) or it was killed manually, using the oom/kill events in docker events.

4. What problem does depends_on with condition: service_healthy solve?

The dependent service waits until the dependency's health check passes before starting, rather than just waiting for its container to start.

5. Why not deploy latest to production? What should you use instead?

latest gets overwritten, so you can't tell which version is live, and rolling back is hard. Deploy with Git SHA tags or digests, and publish releases with semantic versions.

6. Name 3 docker run flags that make a container run more securely, and explain how to verify them.

--read-only (touch fails), --cap-drop ALL (CapEff all zeros), --security-opt no-new-privileges (NoNewPrivs is 1), plus --user and --pids-limit.

7. What is wrong with passing a token via ARG? What is the right approach?

The value shows up in docker history and in provenance (mode=max). Use RUN --mount=type=secret + docker build --secret.

8. The production override file has ports: ["127.0.0.1:5000:5000"]. Why is the service still publicly reachable?

ports is a list, so merging appends instead of replacing. Use !override or !reset, and check with docker compose config.

Final exam (12 questions)

Sources and versions

Verified: 2026-11-14
TopicVerified findingSource
Docker Engine29.9.3 (2026-11-03); since 29.0, fresh installs use the containerd image store by default (except with userns-remap)Engine 29 release notes
GitHub Actions versionsbuild-push-action v7 (latest v7.3.0), login/setup-qemu/setup-buildx v4, metadata-action v6, checkout v6Marketplace · Docker docs
BakePart of Buildx; HCL examples and docker buildx bakeBake (2026-10-29)
Compose merge rulescompose.override.yaml loaded automatically; ports appended, environment by key, volumes by target path, command replacedMerge (2026-06-22)
Engine metricsmetrics-addr example 127.0.0.1:9323; "metric names are still under active development and may change"Prometheus
Rootlessdockerd-rootless-setuptool.sh install; requires uidmap and ≥65536 subuids/subgids; disabling the system-wide dockerd first is recommendedRootless mode (2026-06-07)
GoGo 1.27 released on 2026-08-19Go blog
distrolessgcr.io/distroless/static-debian13:nonroot is in usedistroless
Trivy supply-chain incidentThe v0.69.4 binary, Docker Hub 0.69.5/0.69.6 and most trivy-action tags were injected with malicious code (from 2026-03-19); v0.69.2/v0.69.3 and trivy-action v0.35.0 are recommended; pin Actions by commit SHAAqua official advisory

Relationship to docker-hour2-production-ready.ch.md

This lesson covers all 8 sections of that file (warm-up, CMD/ENTRYPOINT, exec form, ARG/ENV and secrets, image layers, Go multi-stage builds, resources and exit codes, operations commands, Compose .env/healthcheck/override, tagging strategy, multi-arch, GitHub Actions, security hardening, self-check questions), with the following updates and additions:

  • Version updates: GitHub Actions moved from checkout@v4 / setup-*@v3 / login@v3 / build-push@v6 to v6 / v4 / v4 / v7, with metadata-action@v6 added for automatic tags; Go 1.22 → 1.27; distroless static-debian12 → static-debian13; Python 3.12 → 3.13.
  • Correction: in the original exec vs shell timing comparison, a single command such as CMD gunicorn … is exec'd directly by modern dash/bash, so the 10-second difference may not show; this lesson uses CMD gunicorn …; echo … instead and asks you to check /proc/1/cmdline.
  • Security fix: the Compose secrets lab now adds a .dockerignore that excludes secrets/, otherwise COPY . . would bake the secrets into the image; GitHub Actions now uses GHCR + GITHUB_TOKEN, and PRs build without pushing.
  • New: ENTRYPOINT×CMD combination rules and entrypoint scripts, aligning STOPSIGNAL and stop timeouts, ARG scope and predefined platform ARGs, ssh mounts, heredoc, COPY --chmod/--link, build checks, Go cross-compilation and test stages, distroless debugging, the full cgroup v2 flag overview, HEALTHCHECK start-interval, events/logging drivers/Engine metrics, Compose variable precedence/!reset/!override/include/profiles/secrets, Bake, attestations (SBOM/provenance), the Trivy supply-chain incident, rootless/userns-remap, kernel-level verification, the review script and failure drills.

Video verification notes

Verified: david hwang, "Dockerfile for Golang Step by Step 2024 (multi-stage build with distroless/scratch)" (2QMoLyfIJx8, verified via oEmbed on 2026-11-17; the earlier Abhishek Veeramalla video was taken down); TechWorld with Nana, "GitHub Actions Tutorial - Basic Concepts and CI/CD Pipeline with Docker" (R8_veQiYBjI, 32:31, 2020-10-08); plus the Fireship and freeCodeCamp videos already verified in Lesson 1. The container security videos we found could not be verified by ID or author, so they are not listed. All videos are in English and predate the versions used in this lesson.

Known limitations

  • IDs, times, sizes, metric names and error message wording in the expected output are examples; your environment may differ.
  • Audio narration is read aloud in English by the browser's Web Speech API in real time; no MP3s are embedded.
  • The rootless lab disables the system-wide dockerd, so do it on a separate VM.