InfrastructureVol. 6 · Part VI
0 / 0

Shelves / Infrastructure

IN·81

Docker

Building and running images well: every Dockerfile instruction and what it does to layers, the build context and .dockerignore, how the layer cache decides what to rebuild, BuildKit features (cache mounts, secret mounts, multi-platform builds), multi-stage builds for Java, Go, Rust, Python, Node and Zig, tagging and registries, Docker Compose for local environments, healthchecks, resource limits, secrets, non-root users, and supply-chain security: minimal and hardened base images, pinning, scanning, SBOMs, provenance and signing.

30 topics · ~23 min read · 31-question quiz
Updated Suggest a correction

Start here: from source code to a small, safe image

A Dockerfile is a recipe for layers

Each instruction in a Dockerfile produces a filesystem layer or a piece of metadata. The obvious first attempt:

Dockerfile
FROM golang:1.24-alpine
WORKDIR /src
COPY . .
RUN go build -mod=vendor -o /usr/local/bin/tiffin .
CMD /usr/local/bin/tiffin

It works, but the image contains the whole Go toolchain, the source code and the build cache, none of which is needed at run time. A multi-stage build compiles in one stage and copies only the result into a minimal final stage:

Dockerfile
# ---- build stage: has the Go toolchain ----
FROM golang:1.24-alpine AS build
WORKDIR /src
COPY go.mod ./
COPY vendor/ ./vendor/
COPY *.go ./
RUN --mount=type=cache,target=/root/.cache/go-build \
    go build -mod=vendor -trimpath -ldflags="-s -w" -o /out/tiffin .
# ---- runtime stage: just the binary ----
FROM scratch
COPY --from=build /out/tiffin /tiffin
USER 65532:65532
EXPOSE 8080
ENTRYPOINT ["/tiffin"]
Text
tiffin:2.0    8.58MB
tiffin:naive  527MB
== layers of tiffin:2.0
0B	ENTRYPOINT ["/tiffin"]
0B	EXPOSE [8080/tcp]
0B	USER 65532:65532
6.01MB	COPY /out/tiffin /tiffin # buildkit

The final image is one 6 MB layer: 61 times smaller, faster to pull, and with no shell, package manager or compiler for an attacker to use. Four choices did the work:

  • Multi-stage: build tools stay in the build stage.
  • FROM scratch (or a "distroless" image for languages that need a runtime, such as gcr.io/distroless/java21, or a slim Debian/Alpine/Wolfi base): nothing extra in the final image.
  • USER 65532: the process doesn't run as root.
  • Exec-form ENTRYPOINT ["/tiffin"]: the program is PID 1 and receives signals directly (the lab shows what the shell form can do).

Running it

Text
$ docker run -d --name t2 -p 9020:8080 --read-only --cap-drop ALL tiffin:2.0
$ curl -s localhost:9020/
{"hostname":"7c59d4ae74a0","memory_limit":"9223372036854771712","pid":1,"service":"tiffin","uid":65532,"uptime_s":0,"version":"v1"}

-p 9020:8080 publishes the container's port 8080 on the host's 9020; --read-only makes its root filesystem read-only; --cap-drop ALL removes every Linux capability. A static Go service needs none of them, and it's good practice to start from "nothing" and add only what fails.

Compose: several containers as one application

docker compose describes a small multi-container application in one file: services, their images, environment, ports, health checks, dependencies and limits.

YAML
services:
  menu:
    image: tiffin:naive              # Alpine-based build, so it has busybox wget for the health check
    environment: { VERSION: menu-v1 }
    healthcheck:
      test: ["CMD", "wget", "-qO-", "http://localhost:8080/healthz"]
      interval: 2s
      retries: 3
  orders:
    image: tiffin:2.0
    environment: { VERSION: orders-v1 }
    ports: ["9030:8080"]
    depends_on:
      menu: { condition: service_healthy }   # start only after menu passes its health check
    deploy: { resources: { limits: { memory: 64M } } }
Text
 Container compose-menu-1 Waiting
 Container compose-menu-1 Healthy
 Container compose-orders-1 Starting
 Container compose-orders-1 Started
SERVICE   STATUS                  PORTS
menu      Up 1 second (healthy)
orders    Up Less than a second   0.0.0.0:9030->8080/tcp
$ docker compose exec menu wget -qO- http://orders:8080/
{"hostname":"043b5047dc38","memory_limit":"67108864",…,"version":"orders-v1"}

Compose created a private network where services find each other by name (http://orders:8080), waited for menu to be healthy before starting orders, and applied the 64 MB limit. It's the standard tool for local development environments and small single-host deployments; Kubernetes (chapter 83) takes over when you need many machines.

How deep to go in Docker

Volume 17 defines six mastery levels. For this chapter they look like this; the chapter aims at L3 everywhere, and its lab at L4.

Level What you can do
L1 Explain images, containers, Dockerfiles, tags and registries
L2 Write multi-stage Dockerfiles, run containers safely, and use Compose for local stacks
L3 Explain layers and caching, BuildKit features, image formats, networking and PID 1 behaviour
L4 Diagnose slow builds, bloated images, leaked secrets, signal problems and port or DNS issues
L5 Set image standards for a team: bases, users, scanning, signing, SBOMs, provenance
L6 Run build and registry infrastructure at scale with caching, mirrors and supply-chain policy

The Dockerfile

Instructions

A Dockerfile is a recipe that builds an OCI image (chapter 80), one step at a time. Docker Engine 29 uses BuildKit as its builder and the containerd image store by default.

Instruction Purpose Creates a layer?
FROM image AS name Base image; starts a (named) stage Uses base layers
RUN cmd Execute a command at build time Yes (filesystem diff)
COPY src dst Copy from the build context (or --from=stage) Yes
ADD src dst Like COPY, plus URLs, Git repos and auto-extracting local tarballs; prefer COPY unless you need those Yes
WORKDIR /app Set working directory (creates it) Metadata (+ dir)
ENV K=v Environment variable, at build time and in the running container Metadata
ARG K=default Build-time variable only (--build-arg); not persisted in the image config, but visible in history if used in RUN Metadata
USER 10001:10001 User for subsequent RUN and at runtime Metadata
EXPOSE 8080 Documentation of the listening port (doesn't publish it) Metadata
ENTRYPOINT ["app"] The executable Metadata
CMD ["--port","8080"] Default arguments (or default command if no ENTRYPOINT) Metadata
HEALTHCHECK CMD … Container health probe Metadata
LABEL k=v Metadata (OCI annotations: org.opencontainers.image.source, .revision, .version) Metadata
STOPSIGNAL SIGTERM Signal sent on docker stop Metadata
SHELL, VOLUME, ONBUILD Change the RUN shell, declare a volume, trigger in child builds Metadata

Exec form versus shell form:

  • Exec form ENTRYPOINT ["java", "-jar", "app.jar"] runs the program directly as PID 1, so it receives SIGTERM.
  • Shell form ENTRYPOINT java -jar app.jar runs /bin/sh -c "java -jar app.jar". The shell is PID 1 and usually doesn't forward SIGTERM, so your app is SIGKILLed after the stop timeout (10 s by default for docker stop).
  • Use the exec form, or exec in a wrapper script (exec java …).

ENTRYPOINT + CMD: docker run image --debug replaces CMD (the arguments) but keeps ENTRYPOINT.

The build context

docker build -t orders:dev . sends the build context (here, the current directory) to the builder. COPY can only read from the context (or other stages and named contexts). A .dockerignore excludes files from the context:

Text
# .dockerignore: keep the context small, fast and free of secrets
.git
**/node_modules
**/target
**/build
**/__pycache__
*.log
.env
.env.*
**/*.pem
Dockerfile*
docker-compose*.yml

Without it, builds upload gigabytes (.git, node_modules, build outputs), invalidate the cache whenever any file changes, and can bake secrets (.env, keys) into images.

Layers and the build cache

How caching works

BuildKit caches the result of each step. A step is reused if its instruction and inputs are unchanged:

  • For RUN: the command string and the parent layer. (It doesn't check whether the internet changed: RUN apt-get update is cached until something above it changes.)
  • For COPY/ADD: the checksums of the copied files (and metadata).
  • Once one step misses the cache, every following step reruns.

So order instructions from least to most frequently changing: base image, OS packages, dependency manifests, dependency download, then source code.

good: cache-friendly FROM maven:3.9-eclipse-temurin-25 COPY pom.xml . RUN mvn dependency:go-offline COPY src ./src RUN mvn package code change → only the orange steps rerun bad: cache-hostile FROM maven:3.9-eclipse-temurin-25 COPY . . RUN mvn package any file change (even README)→ re-download every dependency ✓ = cached (green) · ↻ = rebuilt (orange)
Dockerfile order and the layer cache. Copying only the dependency manifest before the source code means a code change invalidates only the last layers; copying everything first means every code change re-downloads all dependencies.

Keeping layers small

  • Combine install and cleanup in one RUN, because a later layer can't remove bytes from an earlier one:
Dockerfile
RUN apt-get update \
 && apt-get install -y --no-install-recommends ca-certificates curl \
 && rm -rf /var/lib/apt/lists/*
  • Use --no-install-recommends (apt), --no-cache (apk), pip install --no-cache-dir.
  • Don't install compilers and build tools in the final image: use multi-stage builds.
  • COPY --chown=10001:10001 sets ownership while copying, instead of a separate chown -R layer that duplicates every file.
  • COPY --link creates a layer independent of the previous ones, so rebasing onto a new base image doesn't invalidate it.
  • Inspect with docker history image or the dive tool.

BuildKit features

Start Dockerfiles with # syntax=docker/dockerfile:1 to get the latest stable frontend features:

  • Cache mounts keep package-manager caches between builds without putting them in layers: RUN --mount=type=cache,target=/root/.m2 mvn package.
  • Secret mounts expose a secret file to one RUN without writing it into any layer or the history: RUN --mount=type=secret,id=npmrc,target=/root/.npmrc npm ci, built with docker build --secret id=npmrc,src=$HOME/.npmrc ..
  • SSH mounts for private Git dependencies: RUN --mount=type=ssh git clone ….
  • Bind mounts to read context files without copying them into a layer.
  • Multi-platform builds: docker buildx build --platform linux/amd64,linux/arm64 -t reg/app:1.4 --push . produces an image index (QEMU emulation, cross-compilation, or native builder nodes).
  • Remote cache: --cache-to type=registry,ref=reg/app:buildcache,mode=max and --cache-from share the layer cache across CI runners.
  • Build checks: docker build --check lints common Dockerfile mistakes.

Multi-stage builds

A multi-stage build uses one or more heavyweight build stages (compilers, SDKs, dev dependencies) and copies only the artefacts into a small runtime stage. The final image contains no build tools, source code or caches.

# Java (Spring Boot): build with Maven, extract layers, run on a slim JRE as non-root
# syntax=docker/dockerfile:1
FROM eclipse-temurin:25-jdk AS build
WORKDIR /src
COPY .mvn/ .mvn/
COPY mvnw pom.xml ./
RUN --mount=type=cache,target=/root/.m2 ./mvnw -q dependency:go-offline
COPY src ./src
RUN --mount=type=cache,target=/root/.m2 ./mvnw -q -DskipTests package \
 && java -Djarmode=tools -jar target/*.jar extract --layers --launcher --destination /extracted

FROM eclipse-temurin:25-jre AS runtime
RUN groupadd -g 10001 app && useradd -u 10001 -g app -s /usr/sbin/nologin app
WORKDIR /app
# Separate layers: dependencies change rarely, application code often
COPY --from=build --chown=app:app /extracted/dependencies/ ./
COPY --from=build --chown=app:app /extracted/spring-boot-loader/ ./
COPY --from=build --chown=app:app /extracted/snapshot-dependencies/ ./
COPY --from=build --chown=app:app /extracted/application/ ./
USER 10001
EXPOSE 8080
ENV JAVA_TOOL_OPTIONS="-XX:MaxRAMPercentage=75 -XX:+ExitOnOutOfMemoryError"
ENTRYPOINT ["java", "org.springframework.boot.loader.launch.JarLauncher"]

Notes:

  • scratch is an empty image: no shell, no libc, no CA certificates, no /etc/passwd, no timezone data. Add what you need (CA bundle, zoneinfo) or use distroless static, which provides them plus a nonroot user (UID 65532).
  • Alpine is small but uses musl libc: some glibc-built binaries and Python wheels don't work, and DNS and memory allocator behaviour differ. It's fine for Go, Rust and Zig static builds; for Python and Java, Debian-slim, distroless, Wolfi/Chainguard or Docker Hardened Images are usually safer choices.
  • Java alternatives: jlink a custom runtime with only needed modules; GraalVM native image for fast start and small memory (closed-world restrictions apply); Jib builds layered images straight from Maven/Gradle without a Dockerfile; Spring Boot buildpacks (./mvnw spring-boot:build-image). JDK 24–25 AOT cache (-XX:AOTCache) speeds start-up when the cache is built into the image.
  • Cloud Native Buildpacks (pack build) produce images from source with no Dockerfile, with standardised rebasing of OS layers.

Tags and registries

Shell
docker build -t ghcr.io/acme/orders:1.4.2 -t ghcr.io/acme/orders:sha-3f9c2e1 .
docker push ghcr.io/acme/orders:1.4.2
docker push ghcr.io/acme/orders:sha-3f9c2e1
docker buildx imagetools inspect ghcr.io/acme/orders:1.4.2   # digests per platform
docker pull ghcr.io/acme/orders@sha256:…                      # pin exactly

Tagging conventions:

  • Immutable tags: Git SHA (sha-3f9c2e1) and full semantic version (1.4.2). Never overwrite them; enable tag immutability in the registry.
  • Moving tags for humans: 1.4, 1, latest, main. Never deploy these to production.
  • Add OCI labels with source repository and revision so any running image traces back to a commit: --label org.opencontainers.image.revision=$GIT_SHA.
  • Use docker login with credential helpers (docker-credential-ecr-login, gcloud auth configure-docker) or short-lived CI tokens (OIDC), not long-lived passwords.

Running containers

Shell
# publish host:container; immutable root fs; non-root; no capabilities; hard limits; tini as PID 1
docker run -d --name orders \
  -p 8080:8080 \
  -e SPRING_PROFILES_ACTIVE=prod \
  --env-file ./orders.env \
  -v orders-data:/var/lib/orders \
  --read-only --tmpfs /tmp \
  --user 10001:10001 \
  --cap-drop ALL --security-opt no-new-privileges \
  --memory 512m --memory-swap 512m \
  --cpus 1.5 --pids-limit 256 \
  --restart unless-stopped \
  --init \
  ghcr.io/acme/orders@sha256:…

docker logs -f orders         # stdout/stderr
docker exec -it orders sh     # (no shell in distroless: use `docker debug` or an ephemeral debug container)
docker stats                  # live CPU/memory per container
docker inspect orders         # full config, state, mounts, network
docker stop -t 30 orders      # SIGTERM, wait 30 s, then SIGKILL

Resource limits

  • --memory sets the cgroup memory.max; exceeding it gets the container OOM-killed (exit 137, OOMKilled: true in docker inspect). Set --memory-swap equal to it to forbid swap.
  • --cpus 1.5 sets cpu.max quota; --cpu-shares sets relative weight; --cpuset-cpus pins.
  • --pids-limit stops fork bombs and thread leaks.
  • Without limits, one container can starve the host. Runtimes inside (JVM, Go) size themselves from these limits (chapter 80).

Healthchecks

Dockerfile
HEALTHCHECK --interval=10s --timeout=2s --start-period=30s --start-interval=2s --retries=3 \
  CMD ["/orders", "healthcheck"]
  • The container's status becomes starting → healthy / unhealthy. Docker itself doesn't restart unhealthy containers (Swarm and Compose's depends_on: condition: service_healthy use the status; Kubernetes ignores Docker HEALTHCHECK and uses its own probes, chapter 83).
  • Prefer a check built into the binary (distroless images have no curl), or a tiny static helper.
  • Check the process's ability to serve (an HTTP endpoint), not deep dependencies.

Secrets

Approach Verdict
ENV PASSWORD=… or ARG in the Dockerfile Never: baked into image config or history; anyone who can pull the image can read it
COPY secret.pem then RUN rm Never: still in the earlier layer
Build secrets: RUN --mount=type=secret ✓ For build-time credentials (private registries, package tokens)
-e SECRET=… at runtime Acceptable for development; visible in docker inspect and to processes in the container
Mounted files (/run/secrets/…): Compose/Swarm secrets, Kubernetes Secrets as volumes ✓ Better: file permissions, not in environment dumps
Fetch from a secrets manager at start-up (Vault, AWS Secrets Manager) with workload identity ✓ Best for production: short-lived, rotated, audited

Scan images for leaked secrets in CI (trivy image --scanners secret, gitleaks on the repo).

Non-root users

Containers run as root (UID 0) by default. Even with namespaces, root inside a container shares UID 0 with the host unless user namespaces are used, so a runtime or kernel escape gives host root, and root inside can modify any file in mounted volumes.

  • Create a dedicated user with a fixed numeric UID (e.g. 10001) and USER 10001 in the Dockerfile; Kubernetes runAsNonRoot: true checks the numeric UID.
  • Listen on ports above 1024 (8080, not 80), or grant NET_BIND_SERVICE only.
  • Make the root filesystem read-only (--read-only) and mount tmpfs for scratch directories.
  • Drop all capabilities and set no-new-privileges.

Docker Compose

Compose describes a multi-container application in compose.yaml (the older version: key is obsolete) and runs it with docker compose up. It's the standard for local development environments and simple single-host deployments, not a production orchestrator for many hosts.

YAML
# compose.yaml: API + Postgres + Redis + Kafka for local development
services:
  orders:
    build:
      context: .
      target: runtime
    ports: ["8080:8080"]
    environment:
      DB_URL: postgres://orders@db:5432/orders      # service names resolve via Compose DNS
      REDIS_URL: redis://cache:6379
      KAFKA_BOOTSTRAP: kafka:9092
    secrets: [db_password]
    depends_on:
      db: { condition: service_healthy }
      cache: { condition: service_started }
    deploy:
      resources:
        limits: { cpus: "1.5", memory: 512M }
    read_only: true
    tmpfs: [/tmp]
    develop:
      watch:
        - action: sync+restart
          path: ./src
          target: /app/src
  db:
    image: postgres:18
    environment:
      POSTGRES_USER: orders
      POSTGRES_PASSWORD_FILE: /run/secrets/db_password
    secrets: [db_password]
    volumes: [pgdata:/var/lib/postgresql]
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U orders"]
      interval: 5s
      timeout: 3s
      retries: 10
  cache:
    image: redis:8
  kafka:
    image: apache/kafka:4.1.0
    profiles: [streaming]                          # only with: docker compose --profile streaming up

volumes:
  pgdata:

secrets:
  db_password:
    file: ./secrets/db_password.txt
Shell
docker compose up -d --build          # build and start in the background
docker compose watch                  # sync file changes into containers (develop.watch)
docker compose logs -f orders
docker compose ps
docker compose exec db psql -U orders
docker compose down -v                # stop and remove containers, networks AND volumes

Compose creates a project network where services find each other by service name (db:5432). depends_on with service_healthy waits for the healthcheck, which is how you avoid "app started before the database was ready" (the application should still retry connections). Multiple files (compose.yaml + compose.override.yaml, or -f) layer environment-specific settings. Testcontainers (Java, Go, Python, Node, .NET, Rust) starts the same containers from test code (Vol. 11).

Supply-chain security

An image is software you ship, including everything in its base image. The roadmap's security list in practice:

Minimal base images

Fewer packages mean fewer vulnerabilities, fewer tools for attackers ("living off the land"), and smaller downloads:

Base Size (approx.) Shell/package manager Notes
ubuntu, debian 30–80 MB Yes Familiar, many CVEs to triage
debian:*-slim, python:*-slim 25–50 MB Yes Good compromise
alpine ~5–8 MB Yes (apk) musl caveats
distroless (Google) 2–20 MB No Debian-based runtime-only images: static, base, cc, java, python3, nodejs
Chainguard Images / Wolfi small No (or -dev variants) Rebuilt daily, near-zero known CVEs, SBOMs and signatures included
Docker Hardened Images small No (dev variants exist) Minimal, signed images with SBOMs and provenance; made free and open source (Apache 2.0) in December 2025
scratch 0 No Static binaries only

Debugging without a shell: docker debug (Docker Desktop), kubectl debug with an ephemeral container (chapter 83), or -debug image variants in non-production.

Pinning

  • Base images by digest: FROM eclipse-temurin:25-jre@sha256:… (tools like Renovate and Dependabot update pinned digests via pull requests, so you get updates deliberately).
  • Dependencies by lockfile: package-lock.json + npm ci, uv.lock/poetry.lock, Cargo.lock, go.sum, Maven/Gradle dependency locking or verification metadata.
  • OS packages: pin major versions; rebuild regularly to pick up security patches. Pinning everything forever means never patching: pin for reproducibility, and automate updates.

Image scanning

Scanners compare the image's packages (OS and language dependencies) against vulnerability databases:

  • Trivy (Aqua, open source: OS packages, language dependencies, misconfigurations, secrets, licences), Grype (Anchore, often with Syft SBOMs), Docker Scout, registry-native scanning (ECR, Artifact Registry, ACR, Harbor), Snyk.
  • Run in CI (fail on fixable critical/high findings, with an exceptions process), and continuously on stored images, since new CVEs appear for old images.
  • Use VEX (Vulnerability Exploitability eXchange) statements to record "not affected" decisions so teams don't re-triage the same CVE.
Shell
trivy image --severity HIGH,CRITICAL --ignore-unfixed --exit-code 1 ghcr.io/acme/orders:1.4.2
trivy fs --scanners vuln,secret,misconfig .         # repository, Dockerfile, IaC

SBOMs

A Software Bill of Materials lists every component in the artefact (name, version, supplier, licence, hashes), so when the next Log4Shell lands you can answer "where do we run it?" in minutes.

  • Formats: SPDX (Linux Foundation, ISO/IEC 5962) and CycloneDX (OWASP).
  • Generate: docker buildx build --sbom=true (attached to the image as an attestation), syft ghcr.io/acme/orders:1.4.2 -o cyclonedx-json, build-tool plugins (CycloneDX Maven/Gradle plugins, cargo cyclonedx, cyclonedx-gomod).
  • Store and query SBOMs centrally (Dependency-Track, GUAC). Regulations increasingly expect them (US federal procurement guidance, the EU Cyber Resilience Act).

Provenance and signing

  • Provenance records how an artefact was built: source repository and commit, builder identity, build parameters. The SLSA framework (Supply-chain Levels for Software Artifacts) defines levels; provenance is expressed as in-toto attestations. docker buildx build --provenance=mode=max attaches SLSA provenance; GitHub Actions actions/attest-build-provenance and the SLSA GitHub generator produce signed provenance from CI.
  • Signing proves an image came from you and wasn't altered:
  • Sigstore cosign: keyless signing with short-lived certificates tied to a CI OIDC identity (e.g. "GitHub Actions workflow X in repo Y"), recorded in the Rekor transparency log. cosign sign ghcr.io/acme/orders@sha256:…, cosign verify --certificate-identity … --certificate-oidc-issuer ….
  • Notation (Notary Project, CNCF): X.509-based signing, common with Azure and AWS Signer.
  • Verification at deploy time closes the loop: Kubernetes admission policies (Sigstore policy-controller, Kyverno verifyImages, Connaisseur, Ratify with Gatekeeper) reject images that aren't signed by your CI or lack required attestations (chapter 83).
source+ lockfiles buildpinned base scanTrivy/Grype attestSBOM+SLSA signcosign registryby digest cluster admission policyverify signature + attestations, else reject fail the pipeline on fixablecritical CVEs or leaked secrets
A secure image pipeline. Source and pinned dependencies are built in CI from a minimal base; the image is scanned, gets an SBOM and provenance attestation, is signed with a CI identity, pushed by digest, and verified by an admission policy before it runs.

Lab: builds, contexts, secrets and signals

Docker 29 with BuildKit on the volume's VM, building the tiffin app (one vendored dependency) with the naive and multi-stage Dockerfiles from the on-ramp.

Experiment 1: what a source change costs

Rebuilding with no changes, then after a one-line edit to main.go:

Text
no change, naive:         0.915 s
no change, multi-stage:   0.352 s
source edit, naive:       23.434 s
source edit, multi-stage: 1.603 s

With no changes both builds were fully cached. After an edit, the naive build's COPY . . invalidated everything after it, and go build recompiled the standard library and dependencies from scratch (23 s). The multi-stage build used a BuildKit cache mount (RUN --mount=type=cache,target=/root/.cache/go-build): the compiler's cache persists between builds without becoming part of any image, so only the changed package was recompiled. The same idea applies to Maven (/root/.m2), Gradle, npm and pip caches. Also order instructions from least to most frequently changed: copy dependency manifests and download dependencies before copying source.

Experiment 2: the build context

A 300 MB test-data directory sits in the project; a Dockerfile does COPY . /ctx:

Text
with .dockerignore, COPY . /ctx:                         0.755 s
without .dockerignore (300 MB more to send and copy):    18.512 s

Everything COPY . can see is sent to the builder and hashed, and lands in a layer. .dockerignore keeps out .git, test data, local builds, node_modules and, importantly, secrets like .env files. Prefer copying explicit paths over COPY . ..

Experiment 3: a deleted secret is still in the image

A Dockerfile copies a credentials file, uses it, and deletes it in the next step:

Text
ls: /tmp/creds.env: No such file or directory
found in layer blob f3bff7b3dc0992f0b290
with RUN --mount=type=secret: 0 layers contain the key

The running container couldn't see the file, but docker save showed it intact in the COPY layer: anyone who can pull the image can extract it. Layers only add; a later deletion hides, it doesn't remove. BuildKit's secret mounts make the file available during one RUN without writing it to any layer. The same applies to ARG and ENV: build arguments are recorded in the image history. For runtime secrets, inject them when the container starts (environment from a secret store, mounted files, Kubernetes Secrets), never at build time.

Experiment 4: PID 1 and docker stop

A "wrapper" image whose CMD pipes the app's output through tee, compared with the exec-form image:

Text
tiffin:wrapper: PID 1 is '/bin/sh -c /usr/local/bin/tiffin | tee /tmp/tiffin.log'; docker stop took 10.167 s, exit code 137
tiffin:2.0: PID 1 is '/tiffin'; docker stop took 0.146 s, exit code 0

With the shell as PID 1, docker stop's SIGTERM went to sh, which doesn't forward signals, and as PID 1 the kernel doesn't apply default signal actions to it. Docker waited its 10-second grace period and sent SIGKILL (137). The app never got to drain requests. Every deploy, scale-down and node drain would drop in-flight work and take 10 seconds per container. Fixes: exec-form ENTRYPOINT, exec "$@" at the end of entrypoint scripts, or a tiny init (tini, docker run --init) that forwards signals and reaps zombies. Log to stdout, and let the platform collect it, rather than tee-ing to files.

Try it yourself

  1. Add RUN apk add --no-cache curl (or any package install) before COPY *.go and after it, change a source file, and compare rebuild times.
  2. Generate an SBOM (docker buildx build --sbom=true or syft) and scan the naive and multi-stage images with Trivy or Grype. Compare the findings.
  3. Build tiffin for linux/arm64 as well with docker buildx build --platform linux/amd64,linux/arm64 and inspect the multi-arch index.
  4. Sign the image with cosign and verify it, using a local registry (registry:2) if you have one.

Revision sheet: Docker

Key ideas

  • Dockerfile: FROM, WORKDIR, COPY/ADD, RUN, ENV, ARG, USER, EXPOSE, ENTRYPOINT/CMD (exec vs shell form), HEALTHCHECK, LABEL.
  • Layers and cache: content-addressed layers; a cache miss invalidates later steps; order by change frequency; cache mounts; remote cache export/import.
  • Multi-stage builds: build and runtime stages; scratch, distroless, slim and Wolfi bases; static vs dynamic binaries.
  • Tags and registries: tags are mutable, digests immutable; pin bases by digest; multi-arch indexes; private registries and mirrors.
  • Running: ports, volumes and bind mounts, environment, limits, restart policies, logging drivers, read-only rootfs, dropped capabilities, --init.
  • Compose: services, networks, volumes, health checks and depends_on conditions, profiles, overrides for dev.
  • Supply chain: SBOMs, vulnerability scanning, signing (cosign/Sigstore), provenance (SLSA), base image updates, secrets via BuildKit mounts.

Numbers to remember

  • Lab: multi-stage image 8.6 MB vs 527 MB naive; cache mounts cut a rebuild from 23.4 s to 1.6 s; a 300 MB context added 18 s; a shell PID 1 made docker stop take 10.2 s and exit 137.

Pitfalls

  • COPY . . before installing dependencies.
  • Secrets in COPY, ARG or ENV (they stay in layers and history).
  • Mutable latest tags in production.
  • Shell-form CMD or entrypoint scripts without exec.
  • Running as root; writable root filesystems.
  • Huge build contexts without .dockerignore.

Glossary

  • Layer: an immutable filesystem diff identified by its digest.
  • Digest: content hash (sha256:…) naming an exact image or layer.
  • BuildKit: Docker's build engine (parallel stages, cache and secret mounts).
  • Distroless: images with only the runtime and app.
  • SBOM: software bill of materials listing an image's components.
  • Multi-arch index: a manifest list pointing at per-platform images.