Docker Hour 2: from "it runs" to "production-ready"
- 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/--chmodand 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
| # | Time | Module | Core content | Animation / interactive | Lab (Azure VM) |
|---|---|---|---|---|---|
| 0 | Before class | Recap and warm-up | Rebuild myapp from memory; production readiness self-assessment | 12-item self-assessment score | compose up recap |
| 1 | 00–07 | ENTRYPOINT/CMD and graceful shutdown | Combination rules, exec form, entrypoint script exec "$@", STOPSIGNAL, stop timeout | ENTRYPOINT × CMD × run-argument calculator; shutdown timeline animation | Timing exec vs shell; changing the worker count |
| 2 | 07–14 | Advanced Dockerfile | ARG/ENV scope, secret/ssh mounts, heredoc, COPY options, build checks | "Where does the token end up?" comparer | Secret-leak demo + --check warnings |
| 3 | 14–23 | Multi-stage builds in practice | Go + distroless, test stage, --target, Java/Node patterns, debugging shell-less images | Stage execution diagram + size comparison | goapp: 800 MB → ~10 MB |
| 4 | 23–31 | Resources, health checks and observability | cgroup limit details, HEALTHCHECK parameters, events, logging drivers, Engine metrics | Health-check timeline simulator | Health status events + metrics scraping |
| 5 | 31–39 | Advanced Compose | Variable precedence, override-file merge rules, !reset, include, profiles, secrets | Merge result visualizer | Development/production dual mode |
| 6 | 39–47 | Versioning, multi-arch and CI/CD | SHA/semver tags, Bake, GitHub Actions (v7), caching, attestations | Tag generator + pipeline animation | Bake multi-platform build |
| 7 | 47–54 | Security hardening | Least privilege at runtime, seccomp/AppArmor, rootless, scanning and supply-chain lessons | Security scorer (generates commands live) | Hardened run + vulnerability scan |
| 8 | 54–60 | Production readiness review and failure drills | Review checklist, 5 failure scenarios, mapping to Kubernetes | Failure drill cards | Review your own myapp |
| — | After class | Cheat sheet · Capstone lab | Turn myapp into a production-grade service: multi-stage, hardening, CI, review | Final exam | Capstone lab |
How this relates to Hour 1
Docker architecture, image layering, networking and storage basics, and ACR authentication were covered in Hour 1; this lesson links back only when needed.
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.
We keep using
~/myapp (Flask + Redis) from Labs 5B/7B of Lesson 1 and add ~/goapp (a Go service).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)
- 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
- Memorize the combination rules for ENTRYPOINT × CMD ×
docker runarguments 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
| Instruction | Role | With docker run IMAGE xxx | How to override at run time |
|---|---|---|---|
CMD | Default command or default arguments | The whole CMD is replaced by xxx | Write arguments after the image name |
ENTRYPOINT | Fixed main program | Not replaced; xxx is appended as arguments (exec form) | --entrypoint |
Official combination rules (ENTRYPOINT × CMD)
| No ENTRYPOINT | ENTRYPOINT e p (shell form) | ENTRYPOINT ["e","p"] (exec form) | |
|---|---|---|---|
| No CMD | Error, not allowed (the base image's CMD is inherited) | /bin/sh -c e p | e 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 stopsends 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 withdocker 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
| Parameter | Default | Where to set it |
|---|---|---|
| Stop signal | SIGTERM | Dockerfile STOPSIGNAL, docker run --stop-signal, Compose stop_signal (nginx uses SIGQUIT for graceful shutdown) |
| Stop timeout | 10 seconds | docker stop -t, docker run --stop-timeout, Compose stop_grace_period, K8s terminationGracePeriodSeconds (default 30 seconds) |
| Application graceful shutdown time | gunicorn --graceful-timeout defaults to 30 seconds | Application config |
stop_grace_period to 35s, or set --graceful-timeout to 8 seconds.exec form vs shell form: process tree and signal path
Shutdown sequence in a rolling release
Interactive calculator: which command actually runs?
Shutdown timeline animation
Related commands and flags
| Command / flag | Description |
|---|---|
docker run --entrypoint sh -it IMG | Override ENTRYPOINT (to get into the image when troubleshooting) |
docker run IMG -w 4 | With an exec-form ENTRYPOINT, replaces only CMD (the default arguments) |
docker image inspect -f '{{json .Config.Entrypoint}} {{json .Config.Cmd}}' IMG | Show the image's entrypoint and default command |
docker top CTR / docker exec CTR ps -o pid,comm | Find out who PID 1 is |
docker stop -t 30 CTR / docker run --stop-timeout 30 | Stop timeout |
docker run --stop-signal SIGQUIT | Override the stop signal |
docker run --init | tini as PID 1: forwards signals and reaps zombie processes |
docker kill -s HUP CTR | Send any signal (for example, to make nginx/gunicorn reload config) |
Compose: stop_signal, stop_grace_period, init: true, entrypoint, command | The corresponding Compose fields |
Lab 1: exec vs shell, argument overrides, entrypoint script (about 6 min)
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 .
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.
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
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
services:
web:
stop_grace_period: 35s # longer than gunicorn's default --graceful-timeout 30Case 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
Official documentation
Module 2 · Advanced Dockerfile: variable scope, build-time secrets and build checks
- 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 withdocker build --check.
What: scope of ARG and ENV
| ARG | ENV | |
|---|---|---|
| Lifetime | Build time only | Build time + run time (written to the image config) |
| Scope | From the declaration to the end of the current stage; every FROM starts a new stage, so redeclare it | The current stage plus stages and child images based on it |
| Declared before FROM | Usable 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=V | docker 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 args | Visible 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
| Method | Syntax | Verdict |
|---|---|---|
| ARG | ARG TOKEN + --build-arg TOKEN=… | ✗ Shows up in history and provenance |
| ENV | ENV TOKEN=… | ✗ Permanently written to the image and every container |
| COPY, then delete | COPY .npmrc . → RUN rm .npmrc | ✗ The file is still in the COPY layer |
| secret mount | RUN --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 variable | RUN --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 mount | RUN --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 withCOPY <<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:
| Rule | Triggered when |
|---|---|
JSONArgsRecommended | CMD/ENTRYPOINT uses shell form (the signal problem from Module 1) |
SecretsUsedInArgOrEnv | An ARG/ENV name looks like a secret (TOKEN, PASSWORD, SECRET...) |
UndefinedVar | An undefined variable is referenced (often a forgotten ARG redeclaration inside a stage) |
FromAsCasing | Inconsistent 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
Secret mount data flow
Comparer: where does the token end up?
Build-related flags
| Command / flag | Description |
|---|---|
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}}' IMG | Show each layer's size and creating instruction |
docker image inspect -f '{{json .Config.Env}}' IMG | Show the ENV written to the image |
Lab 2: scope, leaks and fixes (about 6 min)
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.
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
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 ✓
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".
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
Module 3 · Multi-stage builds in practice: from 800 MB to 10 MB
- 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
| Benefit | Description |
|---|---|
| Size | A golang build image is 800 MB or more; distroless static + a static binary is about 10 MB (illustrative; check with docker image ls) |
| Attack surface | No shell, package manager or compiler: far fewer vulnerability findings, and lateral movement is hard even after a compromise |
| Reproducibility | The build environment is pinned by the Dockerfile, so CI matches local builds |
| Parallelism and skipping | BuildKit 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=0the binary doesn't depend on libc, so it can run ondistroless/staticorscratch. - Cross-compilation:
FROM --platform=$BUILDPLATFORM golang:1.27 AS builderruns the compiler natively on the build machine's architecture, thenGOOS=$TARGETOS GOARCH=$TARGETARCHcross-compiles, which is much faster than QEMU emulation. - Caching:
--mount=type=cache,target=/go/pkg/modand/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
-healthchecksubcommand.
When: choosing a base image
| Base image | Contents | Best for | Watch out |
|---|---|---|---|
scratch | Empty | Fully static binaries | No CA certificates, timezone data or /etc/passwd; you must copy them yourself |
gcr.io/distroless/static-debian13:nonroot | CA certificates, tzdata, nonroot user (UID 65532) | Go and Rust static binaries | No shell; the :debug variant includes busybox, for troubleshooting only |
distroless/base, /cc, /java, /python3 | glibc / libstdc++ / runtime | Programs that need libc | Limited language versions; see the project README |
alpine | musl + busybox + apk | When you need a few tools | musl vs glibc behavior differences (DNS, native extensions) |
*-slim (Debian) | glibc + trimmed package set | Interpreted languages such as Python and Node | Larger, but the best compatibility |
goapp stage dependency graph
Multi-stage patterns for common languages
Stage execution simulator: pick a build target
Image size comparison (illustrative)
Multi-stage commands
| Command | Description |
|---|---|
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 sh | Debug distroless: share the PID and network namespaces |
docker cp go:/hello ./hello | Copy files out of a container (works with distroless too) |
Lab 3: a production-grade multi-stage image for a Go service (about 8 min)
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# 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 .
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
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
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
okdocker 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.
Verified videos
static-debian13.Official documentation
Module 4 · Resource limits, health checks and observability
- 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.
--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)
| Flag | cgroup v2 file | Type | Description |
|---|---|---|---|
--memory 512m | memory.max | Hard limit | Exceeding it triggers an OOM kill (exit code 137) |
--memory-reservation 256m | memory.low | Soft reservation | Kept as far as possible when the host is short of memory |
--memory-swap | memory.swap.max | Hard limit | Total of memory + swap; setting it equal to --memory disables swap |
--cpus 1.5 | cpu.max | Hard quota | Exceeding it causes throttling, not a kill |
--cpu-shares 512 | cpu.weight | Relative weight | Only takes effect under CPU contention |
--cpuset-cpus 0,1 | cpuset.cpus | CPU pinning | Latency-sensitive and NUMA workloads |
--pids-limit 200 | pids.max | Hard limit | Guards against fork bombs and thread leaks |
--device-read-bps, etc. | io.max | Hard limit | Limits disk throughput |
--ulimit nofile=65536:65536 | (rlimit, not cgroup) | Process limit | File 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
| Parameter | Default | Meaning |
|---|---|---|
--interval | 30s | Interval between two checks in the normal phase |
--timeout | 30s | A single check that exceeds this is a failure |
--start-period | 0s | Start-up grace period: failures don't count; the first success marks the container healthy |
--start-interval | 5s | Check interval during the grace period (Engine 25.0+), so readiness is detected sooner |
--retries | 3 | Consecutive 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 driver | Characteristics | Recommendation |
|---|---|---|
json-file (default) | No rotation by default | You must configure max-size/max-file |
local | Binary format, compressed, rotated by default | First choice on a single host |
journald / syslog | Hands off to the system log | When central collection already exists (e.g. Azure Monitor Agent collecting journald/syslog) |
fluentd / gelf / awslogs / gcplogs / splunk | Sends directly to the backend | Watch 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)
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.
Runtime operations commands
| Command | Description |
|---|---|
docker stats --no-stream --format 'table {{.Name}}\t{{.CPUPerc}}\t{{.MemUsage}}\t{{.PIDs}}' | Resource snapshot |
docker update --cpus 1 --memory 512m --memory-swap 512m CTR | Change limits on the fly |
docker inspect -f '{{json .State.Health}}' CTR | Health status and output of the last 5 checks |
docker ps --filter health=unhealthy | List unhealthy containers |
docker events --filter container=CTR --since 10m | Event stream: create, start, health_status, oom, die, kill |
docker events --format '{{json .}}' | JSON output, easy to feed into scripts |
docker logs --since 10m --timestamps CTR | Logs with timestamps |
docker run --log-driver local --log-opt max-size=10m --log-opt max-file=3 | Per-container logging configuration |
docker run --log-opt mode=non-blocking --log-opt max-buffer-size=4m | Don't block the app when the log backend is slow (logs are dropped when the buffer is full) |
docker top CTR / docker cp / docker diff | Processes, files and filesystem changes |
curl -s 127.0.0.1:9323/metrics | Engine Prometheus metrics (requires metrics-addr) |
Lab 4: limits, health events, logs and metrics (about 7 min)
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
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.
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.
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
start-interval, so this module relies on the official documentation.Module 5 · Advanced Compose: variables, override merging, profiles and secrets
- Tell
.env(variable interpolation) apart fromenv_file/environment(container environment variables), and know their precedence. - Master the override-file merge rules and how to use
!resetand!override; split large projects withinclude. - Manage optional services with profiles and inject sensitive data as files with secrets.
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 | |
|---|---|---|
| Role | Replace 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)
| Field | How it merges |
|---|---|
compose.override.yaml | Loaded automatically when in the same directory as compose.yaml; not loaded automatically once you use -f explicitly |
Single-value fields such as image, command, restart | Later files replace earlier ones |
Lists such as ports, expose, dns | Appended (easily leads to ports being published twice) |
environment, labels | Merged by key; on the same key the later file wins |
volumes, devices | Merged by mount path in the container; on the same path the later file wins |
!reset tag | Removes the field defined in earlier files, e.g. ports: !reset [], build: !reset null |
!override tag | Replaces 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 debugorCOMPOSE_PROFILES=debug.secrets:: mounted as files at/run/secrets/<name>and never shown among the environment variables indocker inspect. Many official images support*_FILEvariables (such asPOSTGRES_PASSWORD_FILE).COMPOSE_FILEenvironment variable: e.g.COMPOSE_FILE=compose.yaml:compose.prod.yaml, so you don't have to type several-fflags every time.
When: separating development from production
| Development | Single-host production | |
|---|---|---|
| Files | compose.yaml + the auto-loaded compose.override.yaml | -f compose.yaml -f compose.prod.yaml |
| Image | build: . | Immutable tag or digest from the registry (build: !reset null) |
| Code updates | Bind-mount hot reload, or develop.watch (recommended) | Pull the new image, up -d --wait |
| Ports | Published directly | Bound to 127.0.0.1 only, behind a reverse proxy |
| Secrets | Local files | The deployment process fetches them from Key Vault and writes the secrets files |
Configuration loading and merge flow
docker compose configMerge result visualizer
Advanced Compose commands
| Command | Description |
|---|---|
docker compose config / --services / --profiles / --variables | Final config / service list / profile list / variables in use |
docker compose --env-file .env.prod up -d | Specify the interpolation variable file |
docker compose -f compose.yaml -f compose.prod.yaml up -d | Explicit merge (override is no longer auto-loaded) |
COMPOSE_FILE=compose.yaml:compose.prod.yaml docker compose up -d | Specify the file list with an environment variable |
docker compose --profile debug up -d / COMPOSE_PROFILES=debug | Enable a profile |
docker compose up -d --no-deps web | Rebuild one service only, leaving its dependencies alone |
docker compose up -d --force-recreate --wait | Force recreate and wait until healthy |
docker compose run --rm -e DEBUG=1 web python -V | One-off task (-e has the highest precedence) |
docker compose ls | List all Compose projects on the host |
Lab 5: development / production dual mode (about 7 min)
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:
EOFcat > 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
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
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.
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.
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
docker-compose and the version: field, and don't cover !reset or include. This module relies on the official documentation.- Environment variables precedence
- Variable interpolation
- Merge Compose files (updated 2026-06-22)
- Include · Profiles · Secrets
Module 6 · Versioning strategy, multi-arch and CI/CD automation
- Design a tagging strategy: Git SHAs for deployment, semantic versions for releases,
latestas 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 type | Example | Mutable? | Purpose |
|---|---|---|---|
| Git commit SHA | myapp:sha-3f9a2c1 | Immutable (by convention) | Deployment: each image maps to one commit; rolling back means switching to the old SHA |
| Semantic version | myapp:1.4.2, 1.4, 1 | 1.4.2 is immutable; 1.4 / 1 move | Public releases, letting users choose their update granularity |
| Branch / PR | myapp:main, pr-12 | Mutable | Test environments |
latest | myapp:latest | Mutable | Only a convenient alias for local pulls; never use it for deployment |
| digest | myapp@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
| Method | How it works | Speed | Best for |
|---|---|---|---|
| QEMU emulation | setup-qemu-action registers binfmt; arm64 steps run in the emulator | Slow (compile-heavy projects can be an order of magnitude slower) | Interpreted languages, simple projects |
| Cross-compilation | FROM --platform=$BUILDPLATFORM + TARGETARCH (Module 3) | Fast | Languages that support cross-compilation, such as Go, Rust and .NET |
| Native nodes | arm64 runners / remote builder nodes build each platform separately, then the manifests are merged | Fast | Large projects (GitHub offers hosted arm64 runners) |
When: key decisions for CI workflows
- Registry credentials: when pushing to GHCR, use the built-in
GITHUB_TOKEN(withpermissions: 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) ortype=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
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
| Command | Description |
|---|---|
docker buildx bake | Build all targets in the default group |
docker buildx bake goapp --print | Print the resolved final build parameters (for review) |
docker buildx bake --set goapp.platform=linux/arm64 | Override a property temporarily |
TAG=1.4.2 docker buildx bake --push | Override HCL variables with environment variables and push |
docker buildx bake -f compose.yaml | Use a Compose file directly as the Bake definition |
docker buildx create --name multi --driver docker-container --use | Create 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.2 | Add a tag on the registry side directly (no pull needed) |
git describe --tags / git rev-parse --short HEAD | Generate a version number / short SHA locally |
Lab 6: Bake multi-image build + GitHub Actions workflow (about 8 min)
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
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/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).
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
Official documentation
Module 7 · Security hardening: three lines of defense (image, runtime, daemon)
- Master the runtime hardening flags and verify through
/proc/1/statusthat 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
| Layer | Measures | Covered in |
|---|---|---|
| Image | Minimal base image, non-root, no secrets, pinned versions/digests, vulnerability scanning, SBOM | Modules 2, 3, 6; scanning in this module |
| Runtime | Read-only root filesystem, drop capabilities, no privilege escalation, resource limits, no --privileged, no docker.sock mount, avoid host networking | This module |
| Daemon / host | Rootless or userns-remap, control docker group membership, never expose an unencrypted TCP API, patch promptly, CIS Docker Benchmark | This module + Lesson 1, Module 0 |
Why: the runtime flags explained one by one
| Flag | Effect | How to verify |
|---|---|---|
--user 10001:10001 (or USER in the image) | Non-root inside the container | docker exec CTR id |
--read-only + --tmpfs /tmp | Read-only root filesystem, so attackers can't tamper with the program; only the necessary directories are writable | docker 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-privileges | Blocks privilege escalation via setuid programs and the like | grep NoNewPrivs /proc/1/status is 1 |
| Default seccomp profile | Blocks dozens of dangerous system calls (enabled by default; never use seccomp=unconfined) | grep Seccomp /proc/1/status is 2 |
AppArmor docker-default | MAC policy enabled by default on Ubuntu | docker inspect -f '{{.AppArmorProfile}}' CTR |
--pids-limit / --memory / --cpus | Prevents resource-exhaustion attacks | Module 4 |
--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 mode | userns-remap | |
|---|---|---|
| Daemon identity | dockerd and containers run as an ordinary user | dockerd is still root |
| Root in the container maps to | That ordinary user on the host (and its subuid range) | An unprivileged subuid range on the host |
| Installation | dockerd-rootless-setuptool.sh install (needs uidmap and ≥65536 subuids/subgids) | "userns-remap": "default" in daemon.json |
| Caveats | Some 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 prompts | In 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 for | Shared development machines, CI runners, single-host services with strict security requirements | Cases where the system-wide dockerd must stay |
When: where vulnerability scanning belongs
- In CI: scan after building and before pushing; block on
HIGH,CRITICALfindings 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
Security scorer: tick options to generate commands and Compose snippets live
Security commands
| Command | Description |
|---|---|
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}}' CTR | Audit a container's security configuration |
docker exec CTR grep -E 'Cap(Eff|Bnd)|NoNewPrivs|Seccomp' /proc/1/status | Verify 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.tar | Scanning without mounting docker.sock |
docker scout cves IMG | Docker Scout (bundled with Docker Desktop; on Linux install the CLI plugin and log in) |
dockerd-rootless-setuptool.sh install | Install rootless mode |
Lab 7: hardened run, kernel-level verification, offline scanning (about 6 min)
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)
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
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:*:…
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
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.
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
Module 8 · Production readiness review and failure drills
- 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
| Category | Check | Verification command / location | Module |
|---|---|---|---|
| Image | Multi-stage build, minimal base image | docker image ls, Dockerfile | 3 |
| Non-root user | docker 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 present | docker history --no-trunc, Labels | 2, 6 | |
| Runtime | Memory / CPU / PIDs limits | docker inspect -f '{{.HostConfig.Memory}}' | 4 |
| Restart policy and stop timeout aligned with the app's graceful shutdown | RestartPolicy, stop_grace_period | 1 | |
| Ports bound only to the necessary addresses | docker port | 5 | |
| Observability | HEALTHCHECK checks only itself, with sensible parameters | .State.Health | 4 |
| Logs go to stdout and are rotated | .HostConfig.LogConfig | 4 | |
| Release | Immutable tags (SHA/semver); deployments reference digests | Deployment manifest | 6 |
| CI builds automatically, multi-arch, cached, SBOM/provenance; Actions pinned by SHA | Workflow file | 6 | |
| Security | Read-only root filesystem, cap-drop ALL, no-new-privileges, unprivileged, no docker.sock mount | /proc/1/status | 7 |
| Scan before pushing; scanner version pinned | CI logs | 7 |
Mapping from Docker to Kubernetes
| In this lesson | Kubernetes 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
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)
~/review.sh, then run chmod +x ~/review.sh.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
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).
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
| Symptom | Check first | Most likely root cause | Module |
|---|---|---|---|
| stop always takes 10 seconds, exit code 137 | /proc/1/cmdline | PID 1 is sh, or the app doesn't handle SIGTERM | 1 |
| Variable empty in RUN | docker build --check | ARG not redeclared inside the stage | 2 |
| Token appears in history | docker history --no-trunc | Secret passed via ARG/ENV | 2 |
| exec /app: no such file or directory | The file command | Dynamically linked binary in static/scratch | 3 |
| Stuck at health: starting | .State.Health.Log | Check tool missing / bad parameters | 4 |
| Disk filled by logs | LogConfig | json-file without rotation | 4 |
| Production port still exposed | docker compose config | ports list appended during merge | 5 |
| exec format error on arm64 nodes | imagetools inspect | Only one architecture was built | 6 |
| Fails to start after going read-only | docker diff | No tmpfs for a directory that needs writes | 7 |
Command cheat sheet (Hour 2)
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/*
EOFBuilds 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/metricsAdvanced 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_keyRelease 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=ghaSecurity
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 installReview
~/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
~/myapp, then review it with ~/review.sh: everything must PASS, and the Trivy scan must show no "fixable critical vulnerabilities".exec "$@", non-root (fixed UID 10001), HEALTHCHECK with start-interval, OCI labels, # check=error=true.!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.sha-xxxxxxx tag with docker-bake.hcl; (optional) push to GitHub to trigger the workflow.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
| Topic | Verified finding | Source |
|---|---|---|
| Docker Engine | 29.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 versions | build-push-action v7 (latest v7.3.0), login/setup-qemu/setup-buildx v4, metadata-action v6, checkout v6 | Marketplace · Docker docs |
| Bake | Part of Buildx; HCL examples and docker buildx bake | Bake (2026-10-29) |
| Compose merge rules | compose.override.yaml loaded automatically; ports appended, environment by key, volumes by target path, command replaced | Merge (2026-06-22) |
| Engine metrics | metrics-addr example 127.0.0.1:9323; "metric names are still under active development and may change" | Prometheus |
| Rootless | dockerd-rootless-setuptool.sh install; requires uidmap and ≥65536 subuids/subgids; disabling the system-wide dockerd first is recommended | Rootless mode (2026-06-07) |
| Go | Go 1.27 released on 2026-08-19 | Go blog |
| distroless | gcr.io/distroless/static-debian13:nonroot is in use | distroless |
| Trivy supply-chain incident | The 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 SHA | Aqua 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 usesCMD gunicorn …; echo …instead and asks you to check/proc/1/cmdline. - Security fix: the Compose secrets lab now adds a
.dockerignorethat excludessecrets/, otherwiseCOPY . .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.