Images & Dockerfiles: Layers, Caching, Multi-Stage, Multi-Arch, Tagging, Registries, Artifacts
"This specification defines an OCI Image, consisting of an image manifest, an image index (optional), a set of filesystem layers, and a configuration." — Open Container Initiative, OCI Image Format Specification (
spec.md), v1.1
Summary: A container image is not a "mini VM" but a content-addressed bundle (an OCI index, one manifest per platform, a config and an ordered stack of tar layers) that a Dockerfile describes step by step; every practical skill here comes from knowing how those steps become layers, when BuildKit can reuse them, and what ends up shipped, signed and pulled. Focus: The OCI image spec (index, manifest, config, layers, digests, referrers), union filesystems and OverlayFS copy-on-write, every Dockerfile instruction that matters (FROM, RUN, COPY vs ADD, WORKDIR, ENV vs ARG, EXPOSE, LABEL, USER, HEALTHCHECK, ENTRYPOINT vs CMD, exec form vs shell form, STOPSIGNAL), PID 1 and signals with tini, the build context and .dockerignore, layer caching and cache invalidation order, BuildKit and buildx (cache, bind, secret and SSH mounts, external cache backends), multi-stage builds and the builder pattern, base images (scratch, distroless, alpine with musl, debian-slim), the static Go binary with CGO_ENABLED=0, image size and the squashing myth, reproducible builds with SOURCE_DATE_EPOCH, multi-arch builds (platforms, manifest lists, QEMU, cross-compilation), tagging strategy (latest, semantic, immutable tags, digests), registries (Docker Hub and its rate limits, GHCR, ECR, private registries), supply-chain artefacts (SBOM, provenance attestations, cosign signing), linting and scanning (hadolint, Docker build checks, Trivy, Grype, Docker Scout, dive), and how Go and Laravel (php-fpm + Nginx, FrankenPHP + Octane) are containerised. Learning goal: Write a Dockerfile for a Go service and a Laravel app that is small, cache-friendly, non-root, signal-correct, multi-arch and reproducible; read any image's manifest, history and layers and say what is wrong; choose a base image, a tagging scheme and a registry setup; and produce the signature, SBOM and provenance that a deployment policy can verify.
This chapter is the second in the Containers group, after Containers Under the Hood, which owns namespaces, cgroups, the runtime stack (containerd, runc) and OverlayFS as a kernel feature; here OverlayFS appears only as far as it explains layers. Running images (docker run flags, volumes, networks, Compose as a workflow) is Running Containers; hardening a running container (capabilities, seccomp, rootless engines, admission policies) is Container Security; the pipeline that runs these builds (runners, OIDC, environments) is CI/CD Pipelines; how Kubernetes pulls and probes the image is Kubernetes Workloads; why an organisation uses containers at all is Containers & Kubernetes; SAST/SCA policy and incident process are Secure SDLC & Incident Response. Go build flags and module layout are in Toolchain, Modules & Packages and Project Layout, Linting & Build; the command tables are in the Docker cheatsheet.
Page map
| If you are looking for | Go to |
|---|---|
| The whole page in three tables | Everything in one minute |
| Why images are layered and content-addressed | Why it exists |
| OCI 2015, image-spec 1.0 and 1.1, BuildKit default, containerd image store | Where it comes from |
| Index, manifest, config, layers, digests, media types | OCI image spec |
| Union filesystem, OverlayFS, copy-on-write, whiteouts | Layers |
What gets sent to the builder; .dockerignore rules | Build context |
| FROM, RUN, COPY vs ADD, WORKDIR, ENV vs ARG, EXPOSE, LABEL | Dockerfile instructions |
| ENTRYPOINT vs CMD, exec form vs shell form, PID 1, tini, STOPSIGNAL | ENTRYPOINT, CMD and signals |
USER, numeric UIDs, runAsNonRoot | USER and non-root |
| HEALTHCHECK options and exit codes | HEALTHCHECK |
| Why a one-line change rebuilds everything | Layer caching |
| BuildKit, buildx, cache/bind/secret/SSH mounts, cache backends | BuildKit and mounts |
Builder pattern, COPY --from, --target | Multi-stage builds |
| scratch, distroless, alpine (musl), debian-slim, static Go | Base images |
Image size, docker history, dive, --squash | Image size and squashing myths |
SOURCE_DATE_EPOCH, rewrite-timestamp | Reproducible builds |
--platform, manifest list, QEMU, cross-compilation, native nodes | Multi-arch |
| latest, semantic tags, immutable tags, digests | Tagging strategy |
| Docker Hub limits, GHCR, ECR, private registries, mirrors | Registries |
| SBOM, provenance, cosign, referrers | Supply-chain artefacts |
| hadolint, build checks, Trivy, Grype, Docker Scout | Linting and scanning |
| php-fpm images, Composer, OPcache, FrankenPHP, Octane, Nginx | PHP images |
| Build graph, cache keys, manifest JSON, knobs, error messages | Mechanics |
| Code | Go, Laravel |
| Eleven classic problems and their fixes | Solving the classic problems |
| Which base, which tags, which registry, which PHP model | Choosing |
| From one VM to many clusters | In architecture |
| Commands with expected output | Lab |
| Wrong beliefs, summary, quiz, terms | Misconceptions, Cheat sheet, Self-check, Glossary |
Everything in one minute
What an image is made of (OCI image spec v1.1).
| Part | Media type | What it holds | Identified by |
|---|---|---|---|
| Image index (manifest list) | application/vnd.oci.image.index.v1+json | One entry per platform (linux/amd64, linux/arm64...) plus optional attestation manifests | Digest of the index JSON |
| Image manifest | application/vnd.oci.image.manifest.v1+json | One config descriptor and an ordered list of layer descriptors | Digest of the manifest JSON |
| Config | application/vnd.oci.image.config.v1+json | Env, Entrypoint, Cmd, User, WorkingDir, ExposedPorts, Labels, rootfs.diff_ids, history | Digest (this is the "image ID") |
| Layer | application/vnd.oci.image.layer.v1.tar+gzip (or +zstd, or plain tar) | A filesystem changeset: added/changed files and whiteouts for deletions | Digest of the (compressed) blob; DiffID = digest of the uncompressed tar |
| Tag | (registry name) | A human, movable pointer to one manifest or index digest | name:tag, at most 128 characters |
| Referrer | any manifest with a subject field | A signature, SBOM or scan attached to another digest | Listed by GET /v2/<name>/referrers/<digest> |
The Dockerfile in one table.
| Instruction | Creates a layer? | Plain words | Trap |
|---|---|---|---|
FROM | Uses the base's layers | "Start from this image" | latest moves; pin a tag and a digest |
RUN | Yes | Run a command at build time | Cache key is the command string, not what it downloads |
COPY | Yes | Copy files from the context or another stage | COPY . . early kills the cache |
ADD | Yes | COPY plus URLs, Git repos, auto-extracting local tars | Use COPY unless you need those; use --checksum for URLs |
WORKDIR | Metadata (creates the dir) | cd for the rest of the stage | Relative COPY without WORKDIR (hadolint DL3045) |
ENV | Metadata | Environment for build steps and the container | Persists; never for secrets |
ARG | Metadata | Build-time variable, not in the final container | Visible in docker history and max provenance |
EXPOSE | Metadata | Documents the port | Does not publish it |
LABEL | Metadata | org.opencontainers.image.* annotations | Missing source breaks GHCR repo linking |
USER | Metadata | Default user for later RUN and the container | Name without UID defeats runAsNonRoot checks |
HEALTHCHECK | Metadata | Docker probes the container | Shell form needs a shell; distroless has none |
ENTRYPOINT / CMD | Metadata | The program and its default arguments | Shell form: the app is not PID 1 and may miss SIGTERM |
STOPSIGNAL | Metadata | Signal sent by docker stop | php-fpm uses SIGQUIT for a graceful stop |
Base images in one table (sizes as the projects themselves state them).
| Base | libc | Shell / package manager | Size stated by the project | Fits |
|---|---|---|---|---|
scratch | none | none / none | empty | Fully static binaries that need no CA certs, tzdata or /etc/passwd (or that embed them) |
gcr.io/distroless/static-debian13 | none | none / none | "around 2 MiB" | Static Go (CGO_ENABLED=0); includes ca-certificates, tzdata, /etc/passwd, /tmp |
gcr.io/distroless/base-debian13 | glibc | none / none | not stated | cgo Go, Rust, anything needing glibc and libssl |
alpine:3.23 | musl | BusyBox sh / apk | "5 MB"; Docker's guide says "under 6 MB" | Small images that still need a shell; watch musl differences |
debian:trixie-slim | glibc | sh / apt | not stated (full debian: 124 MiB per the distroless README) | Most compatible; php-fpm images are built on it |
Why it exists
Before images, "deploy" meant a runbook: install these packages on the server, copy these files, set these variables, restart this service. Two servers built from the same runbook a month apart differed, because the package mirror moved on. An image freezes the result of the runbook into bytes, names those bytes by their hash, and lets any host with a compatible kernel run exactly those bytes.
Layers exist because shipping the whole filesystem every time would be wasteful. If ten services start FROM debian:trixie-slim, the base layers are stored and pulled once per host; only each service's own layers differ. The same property makes builds fast: if the first eight steps of a Dockerfile have not changed, their layers are reused and only the last steps run again.
| Simpler choice | Richer choice | What you buy | What you pay |
|---|---|---|---|
One big RUN doing everything | Many small, ordered steps | Cache hits on unchanged steps | More layers to reason about |
| Single-stage image (toolchain inside) | Multi-stage (toolchain discarded) | Small, low-CVE runtime image | A slightly longer Dockerfile |
debian base | distroless or scratch | Fewer packages, fewer scanner findings | No shell for debugging (use :debug images or ephemeral containers) |
| Tags only | Tags for humans, digests for deploys | Reproducible rollouts and rollbacks | Tooling must resolve and record digests |
| Native single-arch build | Multi-arch index | One name for x86-64 and ARM hosts | Cross-compilation or emulation in CI |
| Push and hope | SBOM + provenance + signature | Verifiable origin, policy gates | Key or OIDC setup, verification in the cluster |
The analogy used through this page: transparencies on an overhead projector. Each layer is a transparent sheet. The base sheet has the operating system drawn on it; the next sheet adds your files; the next adds a configuration change. What the audience sees (the container's root filesystem) is all sheets stacked. You can never erase ink on a lower sheet: to "delete" something you put an opaque sticker over it on a higher sheet (a whiteout), and the lower sheet still has to be carried to every room. The container gets one extra clean sheet on top to scribble on; it survives docker stop and docker start of that same container and is thrown away only when the container is removed (Docker: "The container's writable layer doesn't persist after the container is deleted"). A new container from the same image, which is what every deploy creates, starts with a clean sheet.
Three common misunderstandings, up front
- "
RUN rm -rf /tmp/buildmakes my image smaller." Only if the files were created in the sameRUN. Files from an earlier layer are hidden by a whiteout, not removed; every pull still downloads them. See Layers. - "A tag identifies an image." A tag is a mutable pointer. The official images'
latest, FrankenPHP's1-php8.6and your own1.4move when someone pushes; only a digest (name@sha256:...) names fixed bytes. See Tagging strategy. - "
EXPOSE 8080opens the port." The Dockerfile reference says "The EXPOSE instruction doesn't actually publish the port. It functions as a type of documentation between the person who builds the image and the person who runs the container." Publishing isdocker run -por a Kubernetes Service.
Where it comes from
| When | What happened | Source |
|---|---|---|
| 22 June 2015 | The Open Container Initiative is launched "by Docker, CoreOS and other leaders in the container industry" under the Linux Foundation | opencontainers.org overview |
| Docker 17.05 | Multi-stage builds arrive ("Docker 17.05 introduced multi-stage builds, simplifying this enormously", in the Composer image docs) | docker-library composer docs |
| 19 July 2017 | OCI image-spec v1.0.0: manifest, index, config, layers become a vendor-neutral standard | GitHub releases of opencontainers/image-spec |
| 17 Nov 2021 | distribution-spec v1.0.1 and image-spec v1.0.2 | GitHub releases |
| 1 Feb 2023 | Docker Engine 23.0: "Set Buildx and BuildKit as the default builder on Linux" | Engine 23.0 release notes |
| Dockerfile 1.5 / BuildKit 0.11 | SOURCE_DATE_EPOCH is honoured for image and layer timestamps | Dockerfile reference, built-in build args |
| 15 Feb 2024 | image-spec and distribution-spec v1.1.0: artifactType, the subject field and the referrers API (signatures and SBOMs as first-class artefacts) | GitHub releases |
| Engine 25.0 | HEALTHCHECK --start-interval | Dockerfile reference |
| 10 Nov 2025 | Docker Engine 29.0; fresh installs use the containerd image store by default, which can hold multi-platform images and attestations | Engine 29 release notes, storage driver docs |
| 2025-2026 | image-spec v1.1.1 (3 Mar 2025), distribution-spec v1.1.1 (29 Jan 2025) | GitHub releases |
Two lineages meet in today's tooling. Docker's own image format came first and the OCI image spec standardised the same shape; Docker's media types such as application/vnd.docker.distribution.manifest.list.v2+json still appear in the wild (the docker buildx imagetools inspect alpine sample in Docker's docs shows exactly that type). The OCI manifest keeps schemaVersion: 2 "to ensure backward compatibility with older versions of Docker". On the build side, the classic builder executed a Dockerfile line by line; BuildKit compiles it into a graph (LLB) and solves it concurrently, which is why stages build in parallel, unused stages are skipped, and mounts like --mount=type=cache exist at all.
The concept catalogue
Each block follows the same order: plain words, the common misunderstanding, the definition, a sequence, real scenarios, what each product does, and the fix.
OCI image spec: index, manifest, config, layers, digests Must-know
In plain words: An image is a small tree of JSON files and tarballs stored by their SHA-256 hash. The tag you type is only a label that points at the top of the tree.
Common misunderstanding: "The image is the big file I downloaded." What you download is a manifest (a few hundred bytes), then a config, then only the layers your host does not already have. Two images sharing a base share those layer blobs on disk and in the registry.
Definition: The OCI image spec defines an image as "an image manifest, an image index (optional), a set of filesystem layers, and a configuration". The manifest's layers array "MUST have the base layer at index 0" and subsequent layers "in stack order". The config carries the runtime defaults and rootfs.diff_ids. A layer DiffID "is the digest over the layer's uncompressed tar archive", which the spec warns not to confuse with the layer digest in the manifest (over the compressed blob). The ChainID of a stack is defined recursively, ChainID(L₀|...|Lₙ) = Digest(ChainID(L₀|...|Lₙ₋₁) + " " + DiffID(Lₙ)), so the same layer on a different base is a different stack.
docker pull ghcr.io/acme/orders-api:1.4.2 on an arm64 host
1 GET /v2/acme/orders-api/manifests/1.4.2 -> image index (media type image.index.v1+json)
2 pick the entry with platform linux/arm64 -> manifest digest sha256:aa...
3 GET /v2/acme/orders-api/manifests/sha256:aa... -> manifest: config + 4 layer descriptors
4 GET /v2/acme/orders-api/blobs/<config digest> -> config JSON (Entrypoint, User, diff_ids)
5 for each layer digest not already on disk: GET /v2/acme/orders-api/blobs/<digest>
6 verify every blob against its digest, unpack into the snapshotter, doneReal scenarios:
- A Kubernetes node pulls 40 services built on the same distroless base: the base blobs are fetched once per node.
- A rollback "to yesterday's
1.4" deploys a different build because someone re-pushed1.4; with the digest recorded at deploy time the rollback is exact. - A security team asks "which running pods contain OpenSSL 3.x?": with SBOM attestations attached to each digest, the answer is a registry query, not a guess.
- An ARM Mac developer pulls
postgres:18and gets thelinux/arm64manifest from the same tag a CI x86 runner uses.
| Product | How it treats OCI images |
|---|---|
| Docker Engine (containerd image store, default on fresh 29.0 installs) | Stores indexes, multi-platform images and attestations; classic store cannot hold image indices |
| containerd / nerdctl | Native OCI content store and snapshotters; Kubernetes nodes use it through CRI |
| Kubernetes | Pulls through the node's runtime; image: name@sha256:... "pins the code that you run" |
| GHCR, ECR, Docker Hub, Harbor, GitLab container registry | Speak the OCI distribution spec; OCI 1.1 referrers support varies (cosign falls back to a tag schema) |
docker buildx imagetools inspect / crane / oras | Read and copy indexes and manifests without pulling layers |
Fix / how to use it: read before you trust. docker buildx imagetools inspect <ref> shows the index and per-platform manifests; the same command with a --format Go template over .Provenance or .SBOM prints the attestations (exact command in Mechanics); deploy name@sha256:... from the digest your build step printed.
Layers, union filesystem, OverlayFS and copy-on-write Must-know
In plain words: Every filesystem-changing instruction adds a read-only sheet; the container adds one writable sheet on top. The kernel shows them as one directory tree.
Common misunderstanding: "Deleting a file in a later step removes it." It only hides it. The OCI layer spec represents removals with whiteout files: "the basename of the entry is prefixed with .wh." and "a whiteout file is an empty file with a special filename that signifies a path should be deleted". The bytes are still in the earlier layer.
Definition: A union filesystem merges several directories into one view. Docker on Linux uses OverlayFS (overlay2): image layers are lowerdirs (read-only), the container layer is the upperdir (writable), and "the unified view is exposed through a directory called merged". Copy-on-write, in Docker's words: "If a file or directory exists in a lower layer within the image, and another layer (including the writable layer) needs read access to it, it just uses the existing file. The first time another layer needs to modify the file ... the file is copied into that layer and modified." OverlayFS "copy_up operations copy the entire file, even if the file is large and only a small part of it's being modified", and the copy-up "only occurs the first time a given file is written".
Container writes to /var/lib/app/data.db (100 MB file from the image)
1 open(O_RDWR) on merged/var/lib/app/data.db
2 OverlayFS sees the file only in a lowerdir -> copy_up: copy all 100 MB into upperdir
3 the write lands on the upperdir copy; later writes hit the copy directly
4 container removed -> upperdir deleted, the image layer never changed
-> databases and logs belong in volumes, not in the container layerReal scenarios:
- A build downloads a 500 MB SDK in one
RUN, uses it in the next and deletes it in a third: the image is still 500 MB bigger. - A PHP container writing sessions into
/var/www/html/storagepays the copy-up cost on the first write of each file; the files survivedocker restartbut are gone when the container is removed, which every redeploy (new container from a new image) does. - Two containers from the same image on one host share every image layer; each has its own small upperdir.
docker diff <container>lists A/C/D (added, changed, deleted) paths: exactly the upperdir contents.
| Storage | Behaviour |
|---|---|
Docker overlay2 (classic store) | lowerdir per layer, upperdir per container, merged mount |
| Docker 29+ / containerd image store | Same OverlayFS idea through containerd snapshotters (overlayfs snapshotter) |
| Kubernetes nodes (containerd, CRI-O) | Overlay snapshotters; container layer is ephemeral storage counted against the pod |
| Podman / Buildah | overlay storage driver from containers/storage |
Fix: create and delete temporary files inside one RUN (or a discarded build stage); put state on volumes; keep frequently rewritten big files out of the image. The kernel side of OverlayFS is in Containers Under the Hood.
Build context and .dockerignore Must-know
In plain words: The build context is the folder you hand to the builder. Only files in it can be COPYed. The legacy builder sent all of it (minus .dockerignore matches) up front; BuildKit can "Detect and skip transferring unused files" and "Incrementally transfer only the changed files", but whatever an instruction such as COPY . . references is sent, even to a remote builder.
Common misunderstanding: ".dockerignore only matters for image size." It matters for speed (less to send), cache stability (a changing .git or node_modules busts COPY . .) and security (.env, keys and credentials stop being copyable at all).
Definition: For docker build . the context is the local directory; it can also be a Git URL, a tarball or stdin. "The build client looks for a file named .dockerignore in the root directory of the context"; a Dockerfile-specific <name>.Dockerfile.dockerignore "takes precedence". Patterns follow Go filepath.Match plus ** "that matches any number of directories (including zero)"; ! makes exceptions, and "the last line of the .dockerignore that matches a particular file determines whether it's included or excluded".
docker build -t shop . (Laravel repo, no .dockerignore)
1 client walks the directory: vendor/, node_modules/, .git/, storage/logs/
2 BuildKit transfers what the Dockerfile references; COPY . . references everything
3 any new log line or git commit changes the checksum of COPY . .
4 every later layer is rebuilt; .env with production keys is now inside a layer
-> add .dockerignore: .git, .env*, vendor, node_modules, storage/logs/*Real scenarios: a 2 GB context because of a local data/ folder; docker build pausing for seconds on "transferring context"; a leaked .env found by a scanner in a public image; a monorepo where each service's Dockerfile needs its own ignore file.
| Tool | Context behaviour |
|---|---|
BuildKit (docker build, buildx) | Transfers only files that instructions reference, still filtered by .dockerignore |
| Classic builder (legacy) | Sent the whole context as a tarball up front |
docker buildx bake | Per-target context and named contexts (contexts = { src = "..." }) |
GitHub Actions build-push-action | Uses the Git context by default unless context: . is set after checkout |
Fix: the go-service and laravel-app snippets each ship a .dockerignore (Go, Laravel); for files needed only by one RUN, prefer a bind mount (RUN --mount=type=bind,source=...) over COPY.
Dockerfile instructions: FROM, RUN, COPY vs ADD, WORKDIR, ENV vs ARG, EXPOSE, LABEL Must-know
In plain words: A Dockerfile is a recipe: start from a base (FROM), run commands (RUN), bring files in (COPY), and set defaults for whoever runs the result (ENV, USER, EXPOSE, CMD).
Common misunderstanding: "ENV and ARG are the same thing with different names." ARG exists only while building ("Unlike ENV, an ARG variable is not embedded in the image and is not available in the final container"); ENV persists into every container. Neither is safe for secrets: build args "are visible in the docker history command and in max mode provenance attestations".
Definition, instruction by instruction:
- FROM
[--platform=<p>] <image>[:<tag>][@<digest>] [AS <name>]starts a stage.ARGbefore the firstFROMis in the global scope and can parameteriseFROM(ARG GO_VERSION=1.27). - RUN executes at build time and commits a layer. Shell form (
RUN apt-get update && ...) runs under/bin/sh -c; exec form (RUN ["cmd","arg"]) does not. Heredocs (RUN <<EOF) keep long scripts readable. Flags:--mount=type=cache|bind|secret|ssh|tmpfs,--network=none|default|host,--security=insecure. - COPY vs ADD. Docker's best-practices guide: "ADD and COPY are functionally similar. COPY supports basic copying of files into the container ... ADD supports features for fetching files from remote HTTPS and Git URLs, and extracting tar files automatically". Use
COPYfor local files (hadolint DL3020: "Use COPY instead of ADD for files and folders"); useADD --checksum=sha256:...for a remote artefact, because "ADD also has built-in support for checksum validation". Useful flags:--from=<stage|image>,--chown,--chmod,--link("your files remain independent on their own layer and don't get invalidated when commands on previous layers are changed"),--parents,--exclude. - WORKDIR sets the working directory (creating it). Prefer it to
RUN cd ...(hadolint DL3003). - ENV vs ARG as above; ENV also has a trap the reference names itself: setting
ENV DEBIAN_FRONTEND=noninteractive"changes the behavior of apt-get, and may confuse users of your image"; use it per-RUNor asARG. - EXPOSE documents ports, default TCP (
EXPOSE 8080/tcp,EXPOSE 53/udp);-Ppublishes them to random high host ports. - LABEL adds metadata; use the OCI annotation keys (
org.opencontainers.image.source,.version,.revision,.created,.licenses,.title,.description,.base.name,.base.digest).MAINTAINERis deprecated in favour ofLABEL org.opencontainers.image.authors. - USER, HEALTHCHECK, ENTRYPOINT, CMD, STOPSIGNAL have their own blocks below. SHELL changes the shell for shell-form
RUN(SHELL ["/bin/bash","-o","pipefail","-c"], hadolint DL4006). ONBUILD registers triggers for child images (rarely a good idea). VOLUME declares a mount point; if later build steps change data inside it, "those changes will be discarded when using the legacy builder. When using Buildkit, the changes will instead be kept." Do not rely on either: put build output outside volume paths.
Build-time vs run-time, for one Dockerfile
1 ARG VERSION=dev build: visible to later RUN, recorded in history
2 ENV PORT=8080 build: visible to RUN; run: present in the container
3 RUN go build -ldflags "-X main.version=$VERSION" VERSION baked into the binary
4 LABEL org.opencontainers.image.version=$VERSION stored in the config
5 docker run -e PORT=9090 image run: overrides ENV; ARG no longer existsReal scenarios: an API token passed as --build-arg NPM_TOKEN=... and later found with docker history --no-trunc; ADD https://.../tool.tar.gz silently changing upstream (no checksum); COPY of a tarball that was expected to be extracted (only ADD extracts local tars); apt-get update in its own RUN, cached for months while apt-get install in the next line fails on stale indexes (Docker's best practices: "Always combine RUN apt-get update with apt-get install in the same RUN statement").
| Feature | Dockerfile frontend version (from the reference) | Notes |
|---|---|---|
RUN --mount, heredocs | # syntax=docker/dockerfile:1 (stable 1.x) | Other builders (Buildah, Kaniko) implement their own subsets; check their docs |
COPY --link / ADD --link | 1.4 | Layer independent of earlier layers; rebase without rebuild |
ADD --checksum | 1.6 | sha256 for HTTP, commit SHA for Git |
RUN --mount=type=secret,env= | 1.10 | Secret as an environment variable |
COPY --exclude / --parents | 1.19 / 1.20 | Filters and parent-directory preservation |
Build checks (docker build --check, # check=error=true) | BuildKit with the Dockerfile frontend | Docker only |
Fix: follow the instruction table in one minute; the Go Dockerfile annotates every line.
ENTRYPOINT vs CMD, exec form vs shell form, PID 1 and signals, tini Must-know
In plain words: ENTRYPOINT is the program; CMD is its default arguments (or the whole command if there is no entrypoint). Write both as JSON arrays so your program is process number 1 and hears docker stop.
Common misunderstanding: "Shell form and exec form are just two spellings." The Dockerfile reference: "The shell form of ENTRYPOINT ignores any CMD or docker run command line arguments. It also starts your ENTRYPOINT as a subcommand of /bin/sh -c, which does not pass signals. This means that the executable will not be the container's PID 1, and will not receive Unix signals. In this case, your executable doesn't receive a SIGTERM from docker stop."
Definition: Exec form ["executable","param1"] "is parsed as a JSON array" and "doesn't automatically invoke a command shell", so no $VAR expansion happens. With an exec-form ENTRYPOINT, "command line arguments to docker run <image> will be appended after all elements in an exec form ENTRYPOINT, and will override all elements specified using CMD". PID 1 is special in Linux: the kernel does not apply default signal actions to it, so a PID 1 without a handler ignores SIGTERM, and orphaned children are re-parented to it and must be reaped. tini is "the simplest init you could think of": it spawns one child, forwards signals and reaps zombies; Docker bundles it as docker-init, enabled with docker run --init ("Run an init inside the container that forwards signals and reaps processes"). STOPSIGNAL sets what docker stop sends; "The default is SIGTERM if not defined", and after the grace period Docker sends SIGKILL.
docker stop shop (CMD php artisan queue:work, shell form)
1 container PID 1 = /bin/sh -c "php artisan queue:work" (shell may stay as parent)
2 docker stop sends SIGTERM to PID 1 = sh
3 sh does not forward it; the worker keeps processing a job
4 grace period ends -> SIGKILL -> job killed mid-way, no graceful stop
fix: CMD ["php","artisan","queue:work"] -> PID 1 = php, SIGTERM handled| ENTRYPOINT | CMD | docker run img runs | docker run img x runs |
|---|---|---|---|
| none | ["app","serve"] | app serve | x |
["app"] | ["serve"] | app serve | app x |
["app"] | none | app | app x |
app (shell form) | anything | /bin/sh -c app (CMD ignored) | /bin/sh -c app (args ignored) |
["app"] | serve (shell form) | app /bin/sh -c serve | app x |
Real scenarios: Laravel queue workers that never finish their job on deploy; Go services that never run srv.Shutdown and drop in-flight requests on every rollout; zombie git processes from a PHP script that shells out, filling the PID table; an entrypoint script that ends with php-fpm instead of exec php-fpm.
| Runtime | What it sends on stop | Grace period knob |
|---|---|---|
| Docker | STOPSIGNAL (default SIGTERM), then SIGKILL | docker stop -t, --stop-timeout, --stop-signal |
| Kubernetes | SIGTERM (or the image STOPSIGNAL where supported), then SIGKILL | terminationGracePeriodSeconds, preStop hook |
| Docker Compose | Same as Docker | stop_grace_period, stop_signal |
| php-fpm official image | STOPSIGNAL SIGQUIT ("Override stop signal to stop process gracefully") | as above |
Fix: exec-form ENTRYPOINT/CMD; entrypoint scripts end with exec "$@" (the reference's own pattern: exec gosu postgres "$@"); docker run --init or tini when the app spawns children; handle SIGTERM in the app (the Go service uses signal.NotifyContext). Docker's build checks flag the mistake: JSONArgsRecommended: JSON arguments recommended for CMD to prevent unintended behavior related to OS signals.
USER and non-root Must-know
In plain words: Unless you say otherwise, the process in the container runs as root. Add a USER line so a bug in your app does not hand an attacker root inside the container.
Common misunderstanding: "Root in a container is harmless because it is isolated." It is still UID 0 against the kernel and any mounted host paths; a kernel or runtime escape starts with full privileges. Rootless engines and user namespaces reduce this (Container Security), but the image should not need root in the first place.
Definition: "The USER instruction sets the user name (or UID) and optionally the user group (or GID) to use as the default user and group for the remainder of the current stage." Warning from the reference: "When the user doesn't have a primary group then the image (or the next instructions) will be run with the root group." hadolint DL3002: "Last user should not be root." Distroless publishes :nonroot tags; its build files define NONROOT = 65532.
Kubernetes pod with securityContext.runAsNonRoot: true
1 kubelet "will validate the image at runtime to ensure that it does not run as UID 0 (root)
and fail to start the container if it does"
2 image config User = "65532:65532" -> numeric, non-zero: the check is unambiguous -> starts
(with only a user name in the image, also set securityContext.runAsUser to a numeric UID)
3 process tries to bind port 80 -> EACCES without CAP_NET_BIND_SERVICE
4 listen on 8080 instead, map 80->8080 in the ServiceReal scenarios: a file-upload path traversal that writes into /etc only because the process is root; an image that fails runAsNonRoot admission; FrankenPHP needing CAP_NET_BIND_SERVICE for ports 80/443 (its docs show setcap, or an unprivileged port with no capability at all).
| Image | Default user | Non-root option |
|---|---|---|
gcr.io/distroless/* | root (latest) | :nonroot tag, UID 65532 |
php:*-fpm | master as root, pool workers as www-data | --user www-data / USER www-data (documented for FPM variants) |
nginx:* | master as root | nginxinc/nginx-unprivileged images, or listen on > 1024 |
golang, node, alpine, debian | root | useradd/adduser -D then USER |
dunglas/frankenphp | root | useradd + setcap or unprivileged SERVER_NAME=:8000 |
Fix: numeric USER 65532:65532 in the Go image; USER www-data in the php-fpm image; files that the app must write (storage/, bootstrap/cache/) owned by that user via COPY --chown.
HEALTHCHECK Important
In plain words: A command Docker runs inside the container every so often; exit 0 means healthy.
Common misunderstanding: "Kubernetes uses my HEALTHCHECK." It does not; Kubernetes has its own liveness, readiness and startup probes (Kubernetes Workloads). HEALTHCHECK is used by Docker Engine, Docker Compose (depends_on: condition: service_healthy) and Swarm.
Definition: HEALTHCHECK [OPTIONS] CMD command or HEALTHCHECK NONE. Options and defaults from the reference: --interval=30s, --timeout=30s, --start-period=0s, --start-interval=5s (Engine 25.0+), --retries=3. Exit codes: 0 healthy, 1 unhealthy, 2 "reserved - don't use this exit code". Output is stored, "only the first 4096 bytes". Only the last HEALTHCHECK counts.
HEALTHCHECK --interval=30s --timeout=3s --start-period=10s --start-interval=5s --retries=3 CMD [...]
(the next check starts `interval` after the previous one COMPLETES; inside the start period the
start interval is used instead; check durations below are rounded)
1 t=0s container starts, status = starting
2 t=5s first check (start interval, inside the 10 s start period) -> exit 0 -> healthy
3 t=35s next check (5 s + 30 s) hangs -> killed at the 3 s timeout, t=38s -> failure 1
4 t=68s (38 + 30) times out at t=71s -> failure 2
5 t=101s (71 + 30) times out at t=104s -> failure 3 = retries -> unhealthy
6 Docker only reports it; Compose dependants or Swarm act on itReal scenarios: a distroless image with HEALTHCHECK CMD curl -f http://localhost/ that is always unhealthy because there is no curl (and no shell for the shell form); a Compose stack where Nginx starts before php-fpm can answer; a health check hitting an endpoint that checks the database, so a DB blip marks every web container unhealthy at once.
| Runtime | Uses image HEALTHCHECK? |
|---|---|
| Docker Engine / Compose / Swarm | Yes |
| Kubernetes | No (probes in the pod spec) |
| AWS ECS | Task-definition healthCheck; it maps to Docker's HEALTHCHECK and overrides the image's ("override any Docker health checks that exist in the container image") |
| Podman | Yes (run by a systemd timer or manually) |
Fix: make the binary probe itself (orders-api healthcheck), or in PHP images use php -r to fetch Laravel's /up route; keep liveness checks local (no database), put dependencies in readiness.
Layer caching and cache invalidation order Must-know
In plain words: The builder reuses a step's result if the step and its inputs are unchanged, but the first changed step forces every later step in that stage to run again. So put what changes rarely at the top and what changes on every commit at the bottom.
Common misunderstanding: "RUN apt-get update re-runs when the mirror has new packages." It does not. The cache docs: for RUN apt-get -y update "the files updated in the container aren't examined to determine if a cache hit exists. In that case just the command string itself is used to find a match." And "Rebuilding the image one week later will still get you the same packages as before."
Definition (Docker's build cache invalidation rules):
- Each instruction is compared with the cache; "If no cached layer matches the instruction exactly, the cache is invalidated", and "Once the cache is invalidated, all subsequent Dockerfile commands generate new images and the cache isn't used."
- For
ADD,COPYandRUN --mount=type=bind, "the builder calculates a cache checksum from file metadata"; "The modification time of a file (mtime) is not taken into account". - An
ARGcauses a miss "upon its first usage, not its definition"; "all RUN instructions following an ARG instruction use the ARG variable implicitly". Predefined proxy args are exempt. - "The contents of build secrets are not part of the build cache. Changing the value of a secret doesn't result in cache invalidation."
WORKDIRrespectsSOURCE_DATE_EPOCH; a dynamic epoch (commit time) "breaks with each commit".- Forcing a re-run: change an earlier layer,
docker builder prune,--no-cache, or--no-cache-filter <stage>.
The diagram shows the general case COPY go.mod go.sum ./; the chapter's own service uses only the standard library, so its Dockerfile copies go.mod alone (there is no go.sum until the first third-party requirement).
Laravel image, developer edits one Blade view
Order A (COPY . . then composer install):
1 COPY . . checksum changed -> MISS
2 RUN composer install MISS (re-downloads every package)
3 RUN npm ci && npm run build MISS
Order B (lock files first):
1 COPY composer.json composer.lock ./ HIT
2 RUN composer install --no-autoloader HIT
3 COPY . . MISS
4 RUN composer dump-autoload runs (seconds)Real scenarios: CI builds taking ten minutes because COPY . . precedes go mod download; a LABEL build_time=$(date)-style ARG at the top of the file busting every layer; a "security rebuild" that changed nothing because apt-get upgrade was cached; ephemeral CI runners with no local cache at all (see external cache backends below).
| Builder | Local cache | External cache |
|---|---|---|
BuildKit (docker driver) | Always on | inline, local, registry, gha "only if you have enabled the containerd image store" |
BuildKit (docker-container, kubernetes, remote drivers) | Per builder | inline, registry, local, gha, s3 (experimental), azblob (experimental) |
| GitHub Actions | none between runs | type=gha or type=registry,ref=...:buildcache |
| GitLab CI | none between jobs (unless a persistent runner) | type=registry to the GitLab container registry |
Fix: order by change frequency; copy lock files (go.mod/go.sum, composer.json/composer.lock, package-lock.json) before source; use cache mounts so a miss is still warm; export cache with --cache-to type=registry,ref=<registry>/<cache-image>,mode=max in CI ("In min cache mode (the default), only layers that are exported into the resulting image are cached, while in max cache mode, all layers are cached, even those of intermediate steps").
BuildKit, buildx and RUN mounts (cache, bind, secret, SSH) Must-know
In plain words: BuildKit is the engine behind docker build; buildx is the CLI plugin that drives it. BuildKit lets a RUN step borrow a directory (a cache, a file from the context, a secret, your SSH agent) without that directory becoming part of the image.
Common misunderstanding: "Deleting the secret file at the end of the RUN keeps it out of the image." Copied or ARG secrets end up in a layer or in history; --mount=type=secret files exist only for the duration of that one RUN and, per the provenance docs, "Secret mounts don't leak outside of the build and are never included in provenance attestations".
Definition: "BuildKit is the default builder for Docker Desktop and Docker Engine users" (on Linux since Engine 23.0; Windows containers still use the legacy builder). It converts the Dockerfile through a frontend (selected by # syntax=docker/dockerfile:1) into LLB, "a content-addressable" build graph, so it can "Detect and skip executing unused build stages" and "Parallelize building independent build stages". RUN --mount types:
| Mount | Example | Persists? | Use for |
|---|---|---|---|
type=cache | --mount=type=cache,target=/root/.cache/go-build | Across builds on that builder, never in the image | Go build cache, /go/pkg/mod, Composer, npm, apt |
type=bind | --mount=type=bind,source=go.sum,target=go.sum | No ("read-only by default"; writes discarded) | Files needed by one step only |
type=secret | --mount=type=secret,id=composer_auth,env=COMPOSER_AUTH | No | Tokens, auth.json, cloud credentials |
type=ssh | --mount=type=ssh + docker build --ssh default | No | git clone of private repos |
type=tmpfs | --mount=type=tmpfs,target=/tmp | No | Scratch space |
Cache mount options: id, target, sharing ("One of shared, private, or locked. Defaults to shared"; apt needs locked), from, source, mode, uid, gid. Secret mount options: id, target, env, required, mode, uid, gid; the CLI side is --secret id=aws,src=$HOME/.aws/credentials or --secret id=API_TOKEN (read from the environment variable of that name).
Private Composer package, three ways
1 ARG COMPOSER_AUTH + RUN composer install
-> token in docker history and in max provenance (leak)
2 COPY auth.json . ; RUN composer install ; RUN rm auth.json
-> token in the COPY layer forever (leak)
3 RUN --mount=type=secret,id=composer_auth,env=COMPOSER_AUTH composer install
docker buildx build --secret id=composer_auth,env=COMPOSER_AUTH .
-> token visible to that RUN only, not cached, not in provenance (correct)Real scenarios: go mod download re-fetching the internet on every CI run (fix: cache mount plus registry cache); npm ci with a private registry token; git clone git@github.com:acme/internal.git during the build (SSH mount); parallel builds corrupting apt state (use sharing=locked).
| Tool | Notes |
|---|---|
docker build | BuildKit through the docker driver; output loaded into the local image store |
docker buildx build | Same, plus drivers (docker-container, kubernetes, remote, Docker Build Cloud), --platform, --push, --cache-to, --attest |
docker buildx bake | Declarative multi-target builds (HCL/JSON/Compose files) |
| Kaniko, Buildah, ko | Build without the Docker daemon; ko builds Go images without a Dockerfile |
Fix: all four mount types appear in the snippets: cache mounts in both Dockerfiles, a secret mount pattern in Solving, bind mounts in Mechanics.
Multi-stage builds and the builder pattern Must-know
In plain words: Use one stage with every tool to build, and a second, tiny stage that receives only the result. The tools never ship.
Common misunderstanding: "Multi-stage is only about size." It is also about attack surface (no compiler or shell for an attacker), cache structure (stages build in parallel and independently), and secrets (a secret used in a build stage never touches the runtime stage's layers).
Definition: Each FROM starts a stage; COPY --from=<stage> copies files from an earlier stage or any image (COPY --from=composer:2 /usr/bin/composer /usr/bin/composer). docker build --target <stage> stops at a named stage. The builder pattern is the older two-Dockerfile workflow (build image, extract artefact with docker cp, second Dockerfile) that multi-stage replaced in Docker 17.05. BuildKit builds only the stages the target depends on.
docker buildx build --target runtime --platform linux/amd64,linux/arm64 .
1 resolve graph: runtime needs build; test is not needed -> skipped
2 build stage runs ONCE per target platform on $BUILDPLATFORM (native, no QEMU)
3 go build with GOOS/GOARCH from TARGETOS/TARGETARCH
4 runtime stage per platform: distroless base layers + one binary layer
5 push: one index with two manifests (+ attestation manifests)Real scenarios: a Go service image going from "golang base plus source" to "distroless plus one binary"; a Laravel image whose Node toolchain is needed only for npm run build; a test stage that CI targets before runtime; an nginx stage and a php-fpm stage from one Dockerfile.
| Language | Build stage | Runtime stage |
|---|---|---|
| Go (cgo off) | golang:1.27-trixie | distroless/static-debian13:nonroot or scratch |
| Go (cgo on) | golang:1.27-trixie | distroless/base-debian13 (glibc) |
| PHP/Laravel | php:8.4-fpm-trixie + Composer, node:22-alpine for assets | php:8.4-fpm-trixie with vendor + nginx:1.28-alpine with public/ |
| Java | JDK image | distroless/java21-debian13 |
| Node | node with dev deps | node slim or distroless nodejs with prod deps |
Fix: the Go and Laravel Dockerfiles are both multi-stage.
Base images: scratch, distroless, alpine vs debian-slim vs distroless, musl, static Go binary, CGO_ENABLED=0 Must-know
In plain words: The base is everything in your image that you did not write. Fewer things in it means fewer things to patch, but also fewer tools when you need to debug.
Common misunderstanding: "Alpine is always the right small base." Alpine "does use musl libc instead of glibc", and the official Go image's own docs call the Alpine variant "highly experimental, and not officially supported by the Go project". DNS resolution details, locale handling and prebuilt glibc binaries are where musl differences show up. For a static Go binary, distroless static is smaller than Alpine and has no shell to exploit.
Definition:
- scratch is the empty image; nothing but what you
COPY. - distroless images "contain only your application and its runtime dependencies. They do not contain package managers, shells or any other programs".
staticcontains ca-certificates, "A /etc/passwd entry for a root user", "A /tmp directory" and tzdata;baseadds glibc and libssl;ccadds libgcc. Tags:latest,nonroot,debug(BusyBox shell),debug-nonroot. All are signed with cosign (keyless). - alpine: musl + BusyBox +
apk, "only 5 MB in size". - debian-slim (
debian:trixie-slim): glibc,apt, the base of the officialphp:*-fpmimages. - Static Go binary: the cgo docs: cgo "is disabled by default when cross-compiling as well as when the CC environment variable is unset and the default C compiler ... cannot be found"; set
CGO_ENABLED=0explicitly sonetandos/useruse the pure-Go implementations and the binary needs no libc. The linker's-s"Omit[s] the symbol table and debug information" (and implies-w, "Omit the DWARF symbol table");-trimpath"remove[s] all file system paths from the resulting executable".
Picking a runtime base for orders-api
1 does the binary need libc? go version -m bin | grep CGO_ENABLED=0 -> no
2 does it need CA certs (calls HTTPS APIs)? yes -> not bare scratch
3 does it need /etc/passwd for a non-root user? yes
4 -> distroless/static-debian13:nonroot (or scratch + COPY certs + passwd)
5 need a shell to debug in staging? -> :debug-nonroot tag, or kubectl debugReal scenarios: x509: certificate signed by unknown authority from a Go binary on scratch without CA certs; time.LoadLocation("Europe/Berlin") failing without tzdata (or use the time/tzdata import); a cgo-enabled binary on distroless static failing to start because glibc is missing; a PHP extension compiled for glibc not loading on Alpine.
| Need | scratch | distroless static | distroless base | alpine | debian-slim |
|---|---|---|---|---|---|
| Static Go, no TLS | Yes | Yes | Overkill | Overkill | Overkill |
| Static Go, HTTPS + time zones | Add certs + tzdata | Yes | Overkill | Yes | Yes |
| cgo / glibc binaries | No | No | Yes | Risky (musl) | Yes |
Shell for docker exec | No | :debug only | :debug only | Yes | Yes |
| Package manager in image | No | No | No | apk | apt |
| PHP-FPM | No | No | No | php:*-fpm-alpine | php:*-fpm (default) |
Fix: the Go image uses distroless/static-debian13:nonroot and CGO_ENABLED=0; the PHP image uses the Debian (trixie) variant, which FrankenPHP's docs also recommend ("Debian variants are recommended").
Image size and image squashing myths; docker history and dive Important
In plain words: Image size is the sum of all layers, including bytes that later layers "deleted". Measure it, find the fat layer, and fix the step that made it.
Common misunderstanding: "Squash the image and the problem goes away." Docker's legacy --squash is "an experimental feature, and should not be considered stable"; squashing "can't take advantage of layer sharing with other images", may store "two copies of the image", and "a single layer takes longer to extract, and you can't parallelize downloading a single layer". Docker's own advice: "For most use cases, multi-stage builds are a better alternative". BuildKit's docker buildx build has no --squash flag.
Definition: docker image history lists each layer with its creating instruction and size (<missing> IDs mean layers pulled from a registry, which carry no local intermediate image). dive shows per-layer file trees and an "image efficiency" score; with CI=true it gives a pass/fail via .dive-ci rules such as lowestEfficiency: 0.95 and highestWastedBytes: 20MB. Compression: layers are gzip by default; --output type=image,...,compression=zstd (levels 0-22) trades CPU for size.
Finding the fat layer
1 docker image history --no-trunc shop-app:dev -> one RUN line is the biggest
2 dive shop-app:dev -> that layer adds /root/.composer/cache
3 fix: COMPOSER_CACHE_DIR on a cache mount, not in a layer
4 CI=true dive shop-app:dev -> fails the build if wasted space returnsReal scenarios: apt-get install without --no-install-recommends and without rm -rf /var/lib/apt/lists/*; node_modules with dev dependencies in the runtime image; a Go image that ships the full toolchain; build caches (~/.cache/go-build, ~/.npm, Composer cache) committed into layers.
| Technique | Effect | Cost |
|---|---|---|
| Multi-stage | Toolchains and caches never ship | None worth naming |
| Cache mounts instead of caches in layers | Package caches never ship | Needs BuildKit |
One RUN for download + use + delete | No hidden bytes | Longer RUN lines |
--no-install-recommends, apk add --no-cache | Fewer packages | You list dependencies yourself |
| Smaller base (distroless/static) | Smallest runtime | No shell |
-ldflags "-s -w", -trimpath (Go) | Smaller, path-free binary | No symbols for debuggers |
--squash (legacy, experimental) | One layer | No sharing, slower pulls; not in BuildKit |
Fix: the go-service Dockerfile combines multi-stage, cache mounts and a stripped static binary; the Lab measures the stripped vs unstripped binary on the host.
Reproducible builds and SOURCE_DATE_EPOCH Good to know
In plain words: A reproducible build produces the same bytes (and therefore the same digest) from the same source, no matter when or where it ran. Timestamps are the first enemy.
Common misunderstanding: "Pinning the base tag makes my build reproducible." Tags move, apt-get installs whatever the mirror has today ("RUN apt-get does not automatically consume SOURCE_DATE_EPOCH to install packages from the past snapshot"), and every file gets the build's current time unless told otherwise.
Definition: reproducible-builds.org: "SOURCE_DATE_EPOCH is a standardised environment variable that distributions can set centrally and have build tools consume ... measured in the number seconds since the Unix epoch". BuildKit (Dockerfile 1.5, BuildKit 0.11) uses it for "the created timestamp in the OCI Image Config", the history timestamps and the org.opencontainers.image.created annotation; file timestamps inside layers change only with the exporter option rewrite-timestamp=true, which "is not set to true by default due to the overhead of rewriting image layers".
Two builds of the same commit, one hour apart
1 without SOURCE_DATE_EPOCH: config "created" differs -> config digest differs -> manifest differs
2 with SOURCE_DATE_EPOCH=$(git log -1 --format=%ct): created fields equal
3 + rewrite-timestamp=true: file mtimes in layers equal
4 + base pinned by digest, no network in RUN, go build -trimpath: digests equal
5 anyone can rebuild and compare the digest to the one you signedReal scenarios: verifying that a release image really came from tag v1.4.2; deduplicating identical rebuilds in a registry; SLSA-style independent rebuilds.
| Source of non-determinism | Fix |
|---|---|
| Timestamps in config and files | SOURCE_DATE_EPOCH + rewrite-timestamp=true |
| Moving base tags | FROM image:tag@sha256:... |
| Package mirrors | Pinned versions (hadolint DL3008), snapshot mirrors (e.g. repro-sources-list.sh) |
| Embedded paths and VCS data (Go) | -trimpath; stamp version via -ldflags -X |
| Cache-busting epoch per commit | Docker docs: use a fixed value (SOURCE_DATE_EPOCH=0) if you want cache reuse |
Fix: docker buildx build --build-arg SOURCE_DATE_EPOCH=$(git log -1 --format=%ct) --output type=image,name=...,push=true,rewrite-timestamp=true . (in GitHub Actions, set it as env on the build step).
Multi-arch: platforms, manifest list, QEMU emulation, cross-compilation Important
In plain words: One image name can hold builds for several CPUs. The registry hands each host the variant for its own architecture.
Common misunderstanding: "Containers are portable, so an amd64 image runs on ARM." Docker's docs: "Containers share the host kernel, which means that the code that's running inside the container must be compatible with the host's architecture. This is why you can't run a linux/amd64 container on an arm64 host (without using emulation)". The usual symptom is the kernel's exec format error at container start.
Definition: A platform is os/arch[/variant] (linux/amd64, linux/arm64, linux/arm/v7). "Multi-platform images contain a manifest list, pointing to multiple manifests, each of which points to a different configuration and set of layers"; on pull, "Docker automatically selects the correct variant based on the host's architecture". Three build strategies from Docker's docs:
- QEMU emulation: "requires no changes to your Dockerfile", but "can be much slower than native builds, especially for compute-heavy tasks like compilation and compression". BuildKit releases bundle QEMU user-mode emulators; manual installs use
tonistiigi/binfmtandbinfmt_misc. - Multiple native nodes:
docker buildx create --appendwith an amd64 and an arm64 node (or Docker Build Cloud). - Cross-compilation:
FROM --platform=$BUILDPLATFORMfor the build stage, then useTARGETOS/TARGETARCH. These automatic args "are defined in the global scope so are not automatically available inside build stages": redeclare them withARG TARGETOS TARGETARCH.
Prerequisite: an image store that holds manifest lists (the containerd image store, default on Docker Desktop and fresh Engine 29.0+), or a docker-container builder that pushes directly (--push), since its builds "aren't automatically loaded to your Docker Engine image store".
docker buildx build --platform linux/amd64,linux/arm64 --push -t ghcr.io/acme/orders-api:1.4.2 .
builder is amd64 ($BUILDPLATFORM = linux/amd64)
1 build stage (amd64, native) GOARCH=amd64 go build -> /out/orders-api
2 build stage (amd64, native) GOARCH=arm64 go build -> /out/orders-api (no QEMU: Go cross-compiles)
3 runtime stage linux/amd64: distroless amd64 layers + binary
4 runtime stage linux/arm64: distroless arm64 layers + binary (COPY only; nothing executes)
5 push both manifests + one index under the tagReal scenarios: Apple-silicon laptops and AWS Graviton nodes next to x86 CI runners; a PHP image whose docker-php-ext-install must compile C under QEMU for arm64 (slow: prefer native arm64 runners); a Go image that builds both arches in the time of one because only the compiler runs.
| Strategy | Dockerfile changes | Speed | Good for |
|---|---|---|---|
| QEMU | None | Slowest for compilation | Interpreted stacks, quick starts, small RUNs |
| Native nodes / Build Cloud | None | Native | PHP/Python/Node images that compile extensions |
| Cross-compile (Go, Rust) | --platform=$BUILDPLATFORM, TARGET* args | Native | Go services |
Fix: the go-service Dockerfile cross-compiles; docker buildx imagetools inspect (sample output in the Lab) shows the resulting platforms.
Tagging strategy: latest, semantic tags, immutable tags, digests Must-know
In plain words: Tags are for people ("1.4", "main"); digests are for machines that must run exactly one build. Push many tags if you like, deploy one digest.
Common misunderstanding: "latest means the newest version." It is just the default tag name when none is given. hadolint DL3007: "You can never rely that the latest tags is a specific version." Kubernetes: "You should avoid using the :latest tag when deploying containers in production as it is harder to track which version of the image is running and more difficult to roll back properly", and with :latest an omitted imagePullPolicy "is automatically set to Always".
Definition: A tag must match [a-zA-Z0-9_][a-zA-Z0-9._-]{0,127} (OCI distribution spec: "at most 128 characters"). A digest is algorithm:hex over the manifest or index bytes; "Digests are hashes of the image's content, and are immutable. Tags can be moved to point to different images, but digests are fixed." With both, "Only the digest will be used for pulling". Semantic tags publish one build as 1.4.2, 1.4, 1 (the shorter ones move forward); commit tags (sha-<full-sha>) never need to move; immutable tags are a registry setting: ECR returns ImageTagAlreadyExistsException "if you push an image with a tag that is already in the repository".
Release v1.4.2 with docker/metadata-action
1 git tag v1.4.2 && git push --tags
2 tags: 1.4.2, 1.4, sha-<40 hex> (1.4 moves from 1.4.1 to 1.4.2)
3 build pushes index sha256:9f1c...; all three tags point to it
4 deploy manifest records ghcr.io/acme/orders-api@sha256:9f1c...
5 rollback = redeploy the previous recorded digest, whatever 1.4 points to nowReal scenarios: two pods of one Deployment running different code after a re-push of 1.4; a base image bump (FROM php:8.4-fpm) silently pulling a new PHP patch release; FrankenPHP's policy "Tags such as latest or 1-php8.6 are moved to the new images, while digests never change. To pin an exact image, reference it by digest."
| Tag kind | Moves? | Use for |
|---|---|---|
latest | Yes, every push | Local experiments only |
1, 1.4 (major/minor) | Yes | Humans who want patches automatically |
1.4.2 (full semver) | Should not (enforce with immutable tags) | Release identity |
sha-<commit> | No | Traceability from image to commit |
main, pr-123 | Yes | Preview environments |
@sha256:... digest | Never | Deployments, base images in FROM, signatures |
Fix: type=semver + type=sha tags in CI (ci workflow), ECR --image-tag-mutability IMMUTABLE (or the equivalent setting in Harbor, GitLab or Artifactory), digests in Kubernetes manifests (Helm values, Kustomize images:, Argo CD Image Updater write-back).
Registries: Docker Hub, GHCR, ECR, private registry, push/pull, rate limits Important
In plain words: A registry is a content-addressed blob store with names on top. docker push uploads missing blobs then the manifest; docker pull does the reverse.
Common misunderstanding: "Docker Hub is free and unlimited for CI." Unauthenticated pulls are limited to "100 per IPv4 address or IPv6 /64 subnet" per 6 hours, Personal accounts to 200, while Pro, Team and Business are "Unlimited" subject to fair use; "A pull for a multi-arch image will count as one pull for each different architecture." The limit error is HTTP 429 with "You have reached your pull rate limit. You may increase the limit by authenticating and upgrading"; a separate abuse limit ("in the order of thousands of requests per minute") returns a plain 429 Too Many Requests.
Definition: The OCI distribution spec defines the HTTP API (/v2/<name>/manifests/<tag-or-digest>, /v2/<name>/blobs/<digest>, uploads, tag lists, and since 1.1 /v2/<name>/referrers/<digest>). Registries you will meet:
| Registry | Name format | Auth from CI | Notable |
|---|---|---|---|
| Docker Hub | docker.io/library/nginx, docker.io/<user>/<repo> | Personal access token | Pull rate limits above; official images live under library/ |
| GHCR (GitHub Container Registry) | ghcr.io/<owner>/<image> | GITHUB_TOKEN with packages: write | Link to a repo with LABEL org.opencontainers.image.source; classic PAT needed outside Actions |
| Amazon ECR | <account>.dkr.ecr.<region>.amazonaws.com/<repo> | aws ecr get-login-password or OIDC role | Tag immutability, lifecycle policies, scanning, pull-through cache |
| Google Artifact Registry / Azure ACR | <region>-docker.pkg.dev/..., <name>.azurecr.io/... | Workload identity / OIDC | Same OCI API |
| GitLab container registry | registry.gitlab.com/<group>/<project> | CI_JOB_TOKEN | Built into GitLab CI |
Harbor, Artifactory, Nexus, registry:2 / distribution | your domain | Robot accounts | Private registry, proxy cache (mirror), replication |
docker push ghcr.io/acme/orders-api:1.4.2
1 HEAD /v2/acme/orders-api/blobs/<digest> for each layer -> 200 exists: skip
2 POST + PUT upload for missing blobs (or cross-repo mount from another repo)
3 PUT config blob
4 PUT /v2/acme/orders-api/manifests/1.4.2 (manifest or index)
5 registry returns the digest; record itReal scenarios: a CI farm behind one NAT IP hitting Docker Hub's anonymous limit on every Monday morning; a Kubernetes cluster pulling nginx through a pull-through cache to avoid the internet; ECR rejecting a re-push of 1.4.2 (immutable, working as intended); GHCR packages not visible to a repo because the source label is missing.
Fix: authenticate every CI pull; mirror base images into your own registry (ECR pull-through cache, Harbor proxy project, registry-mirrors in daemon.json); keep releases immutable; set lifecycle rules for sha-* and pr-* tags.
Supply-chain artefacts: SBOM, provenance attestations, image signing (cosign) Important
In plain words: Next to the image you publish three facts about it: what is inside (SBOM), how and from what it was built (provenance), and who vouches for it (signature). A cluster can refuse anything without them.
Common misunderstanding: "Signing the tag is enough." Signatures are made over a digest; cosign "validates that this digest matches the container during cosign verify". Signing :latest and re-pushing it leaves the old signature pointing at the old digest. Sign name@sha256:... as printed by the build.
Definition: Docker's attestation docs: "Software Bill of Material (SBOM): list of software artifacts that an image contains, or that were used to build the image" and "Provenance: how an image was built". "Provenance attestations with the mode=min level are added to images by default"; SBOM is opt-in (--sbom=true); --provenance=mode=max adds more but "exposes the values of build arguments". Attestations are "wrapped in the in-toto JSON format and attached to the image index in a manifest" whose platform is unknown/unknown. Default provenance follows "SLSA provenance schema, version 0.2" (version=v1 optional). SLSA defines provenance as "an attestation that a particular build platform produced a set of software artifacts". cosign (Sigstore) signs with a key (cosign sign --key cosign.key $IMAGE, or KMS URIs like awskms://, gcpkms://, hashivault://, k8s://) or keyless (cosign sign $IMAGE with an OIDC identity; Fulcio issues a short-lived certificate, the signature is logged in Rekor). Verification pins the identity: cosign verify <image> --certificate-identity=... --certificate-oidc-issuer=.... "Signatures use the OCI 1.1 referrer specification"; cosign tree $IMAGE lists attachments.
Release pipeline, artefacts by digest
1 buildx build --sbom=true --provenance=mode=max --push -> index digest D (+ attestation manifests)
2 trivy image ghcr.io/acme/orders-api@D --exit-code 1 --severity HIGH,CRITICAL
3 cosign sign --yes ghcr.io/acme/orders-api@D (keyless, GitHub OIDC identity)
4 cluster admission (Kyverno / Sigstore policy-controller) verifies identity + issuer for D
5 deploy D; SBOM answers "are we affected by CVE-X?" later without rescanningReal scenarios: the distroless project's own instruction: "We recommend verifying any distroless image you use before building your image" (cosign verify $IMAGE_NAME --certificate-oidc-issuer https://accounts.google.com --certificate-identity keyless@distroless.iam.gserviceaccount.com); an auditor asking which commit and workflow produced a running image (provenance); a zero-day in a library and a fleet-wide SBOM query.
| Artefact | Docker / BuildKit | GitHub | Sigstore |
|---|---|---|---|
| SBOM | --sbom=true (SPDX via BuildKit's scanner) | build-push-action sbom: true | cosign attest --type spdxjson |
| Provenance | --provenance=mode=min (default) / mode=max | provenance: mode=max; artifact attestations | cosign attest --type slsaprovenance |
| Signature | n/a (use cosign or Notation) | OIDC token (id-token: write) | cosign sign, cosign verify |
| Storage | Attestation manifests in the index | Registry referrers | OCI 1.1 referrers or tag fallback |
Fix: the ci workflow builds with sbom: true and provenance: mode=max, scans the digest, then signs it keylessly.
Linting and vulnerability scanning (Trivy, Grype, Docker Scout), hadolint Important
In plain words: Lint the Dockerfile before building (bad patterns), scan the image after building (known CVEs in its packages), and fail the pipeline on the findings you have decided matter.
Common misunderstanding: "Zero CVEs reported means the image is safe." A scanner matches package versions against advisory databases; it says nothing about your code, misses software installed without a package manager, and reports CVEs in packages that a distroless image does not even have. Smaller bases improve "the signal to noise of scanners" (distroless README); they do not replace scanning.
Definition:
- hadolint parses the Dockerfile into an AST and "stands on the shoulders of ShellCheck" for
RUNscripts. Rules cited on this page: DL3002 (last user root), DL3003 (use WORKDIR), DL3006 (always tag the image), DL3007 (latest), DL3008 (pin apt versions), DL3009 (delete apt lists), DL3018 (pin apk versions), DL3020 (COPY instead of ADD), DL3025 (JSON notation for CMD/ENTRYPOINT), DL3045 (COPY to relative path without WORKDIR), DL4006 (pipefail). Ignore inline with# hadolint ignore=DL3008. - Docker build checks:
docker build --check .runs rules such asJSONArgsRecommendedand exits non-zero on violations;# check=error=truemakes a normal build fail. - Trivy:
trivy image <ref>;--severity HIGH,CRITICAL,--exit-code 1,--ignore-unfixed("a shorthand of --ignore-status affected,will_not_fix,fix_deferred,end_of_life"),.trivyignore; it also scans for secrets and misconfigurations. - Grype (Anchore):
grype <image>,grype dir:., orgrype sbom:./sbom.jsonto scan an SBOM (from Syft) "for even faster vulnerability detection". - Docker Scout: Docker's service that "compiles an inventory of components, also known as a Software Bill of Materials (SBOM)" and matches it to advisories, from Docker Hub, Docker Desktop or the CLI.
Pipeline gates, cheapest first
1 hadolint Dockerfile -> DL3007 in FROM: fail in seconds
2 docker build --check . -> JSONArgsRecommended
3 build + push (digest D)
4 trivy image --severity HIGH,CRITICAL --exit-code 1 --ignore-unfixed <ref>@D
5 nightly: rescan deployed digests (new CVEs appear for old images)| Tool | Input | Typical CI use |
|---|---|---|
| hadolint | Dockerfile | Pre-build lint, docker run --rm -i hadolint/hadolint < Dockerfile |
| Docker build checks | Dockerfile | docker build --check . |
| Trivy | Image, filesystem, repo, SBOM | aquasecurity/trivy-action with exit-code: "1" |
| Grype (+ Syft) | Image, directory, SBOM | grype sbom: on the SBOM the build produced |
| Docker Scout | Image (Docker Hub, local) | Docker Hub / Desktop dashboards, CLI |
| dive | Image layers | Size/waste gate with CI=true |
Fix: lint, check, build, scan the digest, sign; the SAST/SCA policy around it lives in Secure SDLC.
PHP images: php-fpm images, Composer in multi-stage, opcache, FrankenPHP, Octane, Nginx sidecar vs single container Important
In plain words: PHP-FPM does not speak HTTP; it speaks FastCGI. So the classic Laravel container setup is two containers (Nginx in front, php-fpm behind), while FrankenPHP is one container that is both web server and PHP runtime.
Common misunderstanding: "Publish port 9000 of the fpm container and point the load balancer at it." The official image docs: "the FastCGI protocol is inherently trusting, and thus extremely insecure to expose outside of a private container network ... do not use Docker's --publish (-p) flag with this image variant."
Definition:
- php-fpm images (
php:8.4-fpm, ondebian:trixie-slim):CMD ["php-fpm"],EXPOSE 9000,STOPSIGNAL SIGQUIT, pools run aswww-data;zz-docker.confsetsdaemonize = noand "should not be overridden". The image "ships with the default php.ini-development and php.ini-production" and it is "strongly recommended to use the production config". Extensions viadocker-php-ext-install,docker-php-ext-enable,pecl install(pin versions), or theinstall-php-extensionsproject. - opcache: enabled by default in the official image's Dockerfile ("enable OPcache by default"). In immutable images set
opcache.validate_timestamps=0; PHP's docs: "When this directive is disabled, you must reset OPcache manually via opcache_reset(), opcache_invalidate() or by restarting the Web server". Defaults to know:memory_consumption128,interned_strings_buffer8,max_accelerated_files10000,revalidate_freq2. - Composer in multi-stage:
COPY --from=composer:2 /usr/bin/composer /usr/bin/composer, lock files first,composer install --no-dev --no-scripts --no-autoloader --prefer-dist, then source, thencomposer dump-autoload --optimize --classmap-authoritative(-o"Convert PSR-0/4 autoloading to classmap",-a"Autoload classes from the classmap only"). Running Composer inside the PHP stage avoids--ignore-platform-reqs, which the Composer image docs list as "(discouraged)". - FrankenPHP: "a modern PHP application server written in Go" (Laravel docs), images
dunglas/frankenphp:<frankenphp-version>-php<php-version>-<os>withtrixie,bookwormoralpine; worker mode viaFRANKENPHP_CONFIG="worker ./public/index.php". - Octane: "boots your application once, keeps it in memory, and then feeds it requests", on FrankenPHP, Swoole/Open Swoole or RoadRunner; workers default to one per CPU core (
--workers),--max-requestsrecycles workers against memory leaks. - Nginx sidecar vs single container: Nginx + php-fpm as two containers (two images, one pod or one Compose project) vs FrankenPHP (or an
nginx + php-fpm + supervisordimage, which breaks the one-process-per-container rule Docker's best practices recommend: "Each container should have only one concern").
Request through the two-container setup
1 client -> web (nginx:1.28-alpine) :80
2 static file in /var/www/html/public? serve it (Vite assets in public/build)
3 else -> fastcgi_pass app:9000 (php-fpm container, private network only)
4 php-fpm worker runs public/index.php with OPcache (no stat calls)
5 docker stop app -> SIGQUIT -> FPM finishes in-flight requests, then exits| Model | Containers | Pros | Cons |
|---|---|---|---|
| Nginx + php-fpm (sidecar or separate service) | 2 | Standard, each image does one thing, Nginx serves static files | Two images to version together; public/ copied into both |
| FrankenPHP (classic mode) | 1 | One image, HTTP/2/3, automatic HTTPS (Caddy) | Newer; ops teams know Nginx better |
| FrankenPHP + Octane (worker mode) | 1 | App booted once: far less per-request work | Shared state between requests; memory leaks need --max-requests |
Apache + mod_php (php:*-apache) | 1 | Simplest | Process-per-request model; less common for Laravel at scale |
| Nginx + php-fpm + supervisord in one image | 1 | One artefact | Several processes, signal handling and logs get harder |
Fix: the Laravel section has both: a two-target Dockerfile (app + web) with Compose, and a FrankenPHP/Octane image.
Mechanics
The build graph: frontend, LLB, stages, mounts
# syntax=docker/dockerfile:1 on the first line tells BuildKit which frontend image parses the file (the reference: "Set to dockerfile.v0 to ignore the Dockerfile # syntax= directive and use the built-in frontend instead", via BUILDKIT_SYNTAX). The frontend emits LLB; BuildKit solves the graph from the requested target backwards, so stages the target does not need never run, and independent stages run concurrently.
Dockerfile (go-service) LLB graph solved for --target runtime
FROM golang AS build ─▶ [golang base] ─▶ [COPY go.mod] ─▶ [go mod download] ─▶ [COPY .] ─▶ [go build]
FROM build AS test ─▶ (not needed by runtime: skipped) │
FROM distroless AS runtime ─▶ [distroless base] ─────────────────────▶ [COPY --from=build binary] ◀─┘
cache mounts /go/pkg/mod and /root/.cache/go-build hang off the RUN vertices, outside any layerA bind mount avoids even the COPY layer when a file is needed by one step only; Docker's cache guide shows the Go form RUN --mount=type=bind,target=. go build -o /app/hello, with the warning that "the build output must be written outside the bind mount target". With bind mounts the cache key still covers the mounted files' metadata, exactly as for COPY.
How a cache key is decided
| Instruction | What is compared | Changes that cause a miss |
|---|---|---|
FROM | Resolved base digest | New base digest (only re-resolved with --pull or when not local) |
RUN | Command string + parent + build args in use + mount specs | Text edit, changed ARG value used by it, changed mount id/target |
COPY / ADD (local) | Checksum over file content and metadata (not mtime) | Any byte, mode or ownership change in matched files |
ADD <url> | Remote content (checksum if given) | Upstream change |
RUN --mount=type=bind | Like COPY for the bound files | Bound file change |
RUN --mount=type=secret | Secret id and target, never the value | Id or path change |
WORKDIR | Path + SOURCE_DATE_EPOCH | Epoch change |
ENV, LABEL, USER, EXPOSE | Instruction text | Value change (cheap: metadata only, but later steps miss) |
A manifest and an index, byte for byte
The OCI spec's example manifest has this shape (digests shortened):
{
"schemaVersion": 2,
"mediaType": "application/vnd.oci.image.manifest.v1+json",
"config": {
"mediaType": "application/vnd.oci.image.config.v1+json",
"digest": "sha256:b5b2b2c5...",
"size": 7023
},
"layers": [
{ "mediaType": "application/vnd.oci.image.layer.v1.tar+gzip", "digest": "sha256:9834876d...", "size": 32654 },
{ "mediaType": "application/vnd.oci.image.layer.v1.tar+gzip", "digest": "sha256:3c3a4604...", "size": 16724 }
],
"annotations": { "com.example.key1": "value1" }
}Reading the real thing without pulling layers:
# Index and per-platform manifests (Docker's own docs show this for alpine)
docker buildx imagetools inspect alpine
docker buildx imagetools inspect --raw ghcr.io/acme/orders-api:1.4.2 | jq .
# Attestations attached by BuildKit
docker buildx imagetools inspect ghcr.io/acme/orders-api:1.4.2 --format "{{json .Provenance}}"
docker buildx imagetools inspect ghcr.io/acme/orders-api:1.4.2 --format "{{json .SBOM}}"
# Config and layer history of a local image
docker image inspect --format '{{json .Config}}' orders-api:dev | jq .
docker image history --no-trunc orders-api:devAttestation manifests sit in the index with "platform": {"architecture": "unknown", "os": "unknown"} and the annotations vnd.docker.reference.type: attestation-manifest and vnd.docker.reference.digest: <digest of the image manifest>, which is why a naive script listing "platforms" of an index sometimes prints unknown/unknown.
Knobs
| Knob | Where | Default | Notes |
|---|---|---|---|
HEALTHCHECK --interval / --timeout / --start-period / --start-interval / --retries | Dockerfile | 30s / 30s / 0s / 5s / 3 | --start-interval needs Engine 25.0+ |
STOPSIGNAL | Dockerfile | SIGTERM | docker run --stop-signal overrides |
--mount=type=cache,sharing= | Dockerfile | shared | locked for apt; private for exclusive copies |
--mount=type=secret,mode= | Dockerfile | 0400, uid 0 | env= since Dockerfile 1.10 |
--cache-to ...,mode= | buildx | min | max caches intermediate stages too |
--provenance=mode= | buildx | min (on by default) | max includes build-arg values |
--sbom | buildx | off | SPDX JSON in-toto attestation |
BUILDX_NO_DEFAULT_ATTESTATIONS | env | unset | Disables default provenance |
compression= / compression-level= | --output type=image | gzip | zstd 0-22, gzip/estargz 0-9 |
rewrite-timestamp= | --output type=image | false | Apply SOURCE_DATE_EPOCH to file mtimes |
SOURCE_DATE_EPOCH | build arg / env | unset | Dockerfile 1.5, BuildKit 0.11 |
--platform | buildx | builder's platform | Comma list for multi-arch |
opcache.validate_timestamps | php.ini | 1 | 0 in immutable images |
opcache.memory_consumption / max_accelerated_files | php.ini | 128 / 10000 | Raise for big apps (classmap size) |
| Docker Hub pulls per 6 h | registry | 100 anonymous per IP, 200 Personal | Pro/Team/Business unlimited (fair use) |
| Tag length | registry | max 128 chars | [a-zA-Z0-9_][a-zA-Z0-9._-]{0,127} |
Error messages you will actually see
| Message | Meaning | Fix |
|---|---|---|
You have reached your pull rate limit. You may increase the limit by authenticating and upgrading (HTTP 429) | Docker Hub pull limit | docker login in CI, mirror base images |
429 Too Many Requests (short body) | Docker Hub abuse limit | Slow down, cache, mirror |
exec format error (container exits immediately) | Binary architecture does not match the host (Linux ENOEXEC, errno 8) | Build the right --platform or a multi-arch index |
ERROR: failed to build: Attestation is not supported for the docker driver. | Classic image store cannot hold attestations | Enable the containerd image store or use docker-container driver |
ImageTagAlreadyExistsException | ECR immutable tags | New tag per build (that is the point) |
E: Package 'php-XXX' has no installation candidate | The php image blocks Debian's PHP packages | Use docker-php-ext-install/pecl, not apt install php-* |
Lint Rule 'JSONArgsRecommended': JSON arguments recommended for CMD to prevent unintended behavior related to OS signals | Build check on shell-form CMD | Exec form |
x509: certificate signed by unknown authority (Go on scratch) | No CA bundle in the image | distroless/static, or COPY /etc/ssl/certs/ca-certificates.crt |
container ... is unhealthy / Compose dependency failed to start | HEALTHCHECK failing (often: no curl in image) | Self-probing binary or php -r probe |
[pool www] 'user' directive is ignored when FPM is not running as root (notice) | FPM started via USER www-data | Expected; workers run as the current user |
Go
The Go service is a 150-line stdlib HTTP server that does the four things an image needs from the application: listen on the port the image documents, stop cleanly on SIGTERM within the grace period, answer health probes, and report the version stamped at build time.
Before
A Dockerfile that builds and runs, and is wrong in eight ways (each line says how):
# A Dockerfile that works, and is a poor image. Every line is a lesson.
# latest: a different Go (and Debian) every time the tag moves.
FROM golang:latest
# Whole context (including .git, .env, local binaries) copied before the build:
# any file change invalidates the dependency download and the compile.
COPY . /app
WORKDIR /app
# No cache mounts, no -trimpath, no version stamping; cgo left at its default.
RUN go build -o orders-api .
EXPOSE 8080
# Runs as root. The final image still contains the whole Go toolchain,
# a shell, apt and the source code.
# Shell form: Docker wraps this in /bin/sh -c, so the shell, not orders-api,
# can end up as PID 1 and SIGTERM may never reach the application.
CMD ./orders-apiAfter
The application side: signal.NotifyContext for SIGTERM, a serve function that flips readiness off before srv.Shutdown and bounds the drain with a timeout (tests cancel the context with a request in flight, and with a request that never finishes), /healthz and /readyz, and a healthcheck subcommand so a shell-less image can still have a HEALTHCHECK.
// Command orders-api is a minimal HTTP service built to be packaged in a
// container image. It shows the application side of a good image:
// - it listens on $PORT (default 8080, matching EXPOSE in the Dockerfile);
// - it exits cleanly on SIGTERM (what `docker stop` and Kubernetes send);
// - it answers /healthz (liveness) and /readyz (readiness);
// - "orders-api healthcheck" probes the local server, so a distroless image
// with no shell and no curl can still have an exec-form HEALTHCHECK;
// - version and commit are injected at build time with -ldflags -X.
package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"log/slog"
"net"
"net/http"
"os"
"os/signal"
"sync/atomic"
"syscall"
"time"
)
// Set with: go build -ldflags "-X main.version=1.4.2 -X main.commit=abc1234".
var (
version = "dev"
commit = "none"
)
// shutdownTimeout must stay below the container stop grace period
// (docker stop -t default 10 s; Kubernetes terminationGracePeriodSeconds default 30 s).
const shutdownTimeout = 8 * time.Second
func main() {
if len(os.Args) > 1 && os.Args[1] == "healthcheck" {
os.Exit(healthcheck(addr()))
}
logger := slog.New(slog.NewJSONHandler(os.Stdout, nil))
if err := run(logger); err != nil {
logger.Error("exit", "err", err)
os.Exit(1)
}
}
func addr() string {
port := os.Getenv("PORT")
if port == "" {
port = "8080"
}
return net.JoinHostPort("", port)
}
func run(logger *slog.Logger) error {
// NotifyContext turns SIGTERM/SIGINT into context cancellation. This only
// works if this binary is PID 1 (exec-form ENTRYPOINT) or behind an init
// such as tini / docker run --init that forwards signals.
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGTERM, syscall.SIGINT)
defer stop()
ln, err := net.Listen("tcp", addr())
if err != nil {
return err
}
var ready atomic.Bool
return serve(ctx, logger, ln, newMux(&ready), &ready, shutdownTimeout)
}
// serve runs the HTTP server on ln until ctx is cancelled, then fails
// readiness and drains in-flight requests for at most timeout.
func serve(ctx context.Context, logger *slog.Logger, ln net.Listener, h http.Handler, ready *atomic.Bool, timeout time.Duration) error {
srv := &http.Server{
Handler: h,
ReadHeaderTimeout: 5 * time.Second,
}
errc := make(chan error, 1)
go func() {
logger.Info("listening", "addr", ln.Addr().String(), "version", version, "commit", commit)
errc <- srv.Serve(ln)
}()
ready.Store(true)
select {
case err := <-errc:
return err
case <-ctx.Done():
}
// Fail readiness first so the load balancer stops sending new requests,
// then drain in-flight requests within the grace period.
ready.Store(false)
logger.Info("shutting down", "timeout", timeout.String())
sctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
if err := srv.Shutdown(sctx); err != nil {
return fmt.Errorf("shutdown: %w", err)
}
if err := <-errc; !errors.Is(err, http.ErrServerClosed) {
return err
}
logger.Info("stopped")
return nil
}
func newMux(ready *atomic.Bool) *http.ServeMux {
mux := http.NewServeMux()
mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte("ok\n"))
})
mux.HandleFunc("GET /readyz", func(w http.ResponseWriter, _ *http.Request) {
if !ready.Load() {
http.Error(w, "not ready", http.StatusServiceUnavailable)
return
}
_, _ = w.Write([]byte("ready\n"))
})
mux.HandleFunc("GET /version", func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(map[string]string{"version": version, "commit": commit})
})
mux.HandleFunc("GET /orders/{id}", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(map[string]string{"id": r.PathValue("id"), "status": "paid"})
})
return mux
}
// healthcheck is the body of `orders-api healthcheck`, used by the Dockerfile's
// exec-form HEALTHCHECK. Exit code 0 = healthy, 1 = unhealthy (Docker reserves 2).
func healthcheck(listen string) int {
_, port, err := net.SplitHostPort(listen)
if err != nil {
return 1
}
client := &http.Client{Timeout: 2 * time.Second}
resp, err := client.Get("http://127.0.0.1:" + port + "/healthz")
if err != nil {
return 1
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return 1
}
return 0
}package main
import (
"context"
"errors"
"io"
"log/slog"
"net"
"net/http"
"net/http/httptest"
"runtime"
"strings"
"sync/atomic"
"testing"
"time"
)
func TestHealthAndReadiness(t *testing.T) {
var ready atomic.Bool
srv := httptest.NewServer(newMux(&ready))
defer srv.Close()
get := func(path string) int {
resp, err := http.Get(srv.URL + path)
if err != nil {
t.Fatal(err)
}
resp.Body.Close()
return resp.StatusCode
}
if got := get("/healthz"); got != http.StatusOK {
t.Fatalf("/healthz = %d, want 200", got)
}
if got := get("/readyz"); got != http.StatusServiceUnavailable {
t.Fatalf("/readyz before ready = %d, want 503", got)
}
ready.Store(true)
if got := get("/readyz"); got != http.StatusOK {
t.Fatalf("/readyz after ready = %d, want 200", got)
}
}
func TestOrderRoute(t *testing.T) {
var ready atomic.Bool
rec := httptest.NewRecorder()
newMux(&ready).ServeHTTP(rec, httptest.NewRequest("GET", "/orders/42", nil))
if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), `"id":"42"`) {
t.Fatalf("got %d %q", rec.Code, rec.Body.String())
}
}
func TestHealthcheckCommand(t *testing.T) {
var ready atomic.Bool
srv := httptest.NewServer(newMux(&ready))
defer srv.Close()
_, port, _ := net.SplitHostPort(strings.TrimPrefix(srv.URL, "http://"))
if code := healthcheck(":" + port); code != 0 {
t.Fatalf("healthcheck against live server = %d, want 0", code)
}
srv.Close()
if code := healthcheck(":" + port); code != 1 {
t.Fatalf("healthcheck against closed server = %d, want 1", code)
}
}
func TestVersionStamping(t *testing.T) {
oldV, oldC := version, commit
version, commit = "1.4.2", "abc1234" // what -ldflags "-X main.version=... -X main.commit=..." sets
defer func() { version, commit = oldV, oldC }()
var ready atomic.Bool
rec := httptest.NewRecorder()
newMux(&ready).ServeHTTP(rec, httptest.NewRequest("GET", "/version", nil))
if got, want := strings.TrimSpace(rec.Body.String()), `{"commit":"abc1234","version":"1.4.2"}`; got != want {
t.Fatalf("/version = %s, want %s", got, want)
}
}
// TestServeDrainsOnCancel cancels the context (what SIGTERM does via
// signal.NotifyContext) while a request is in flight: the request must
// complete, readiness must flip off, and serve must return nil in time.
func TestServeDrainsOnCancel(t *testing.T) {
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
var ready atomic.Bool
started := make(chan struct{})
release := make(chan struct{})
mux := newMux(&ready)
mux.HandleFunc("GET /slow", func(w http.ResponseWriter, _ *http.Request) {
close(started)
<-release
_, _ = w.Write([]byte("done"))
})
ctx, cancel := context.WithCancel(context.Background())
logger := slog.New(slog.DiscardHandler)
done := make(chan error, 1)
go func() { done <- serve(ctx, logger, ln, mux, &ready, 2*time.Second) }()
type result struct {
body string
err error
}
resc := make(chan result, 1)
go func() {
resp, err := http.Get("http://" + ln.Addr().String() + "/slow")
if err != nil {
resc <- result{err: err}
return
}
defer resp.Body.Close()
b, err := io.ReadAll(resp.Body)
resc <- result{string(b), err}
}()
<-started
cancel() // "SIGTERM"
// Shutdown waits for the in-flight request; readiness is already off.
deadline := time.Now().Add(time.Second)
for ready.Load() && time.Now().Before(deadline) {
runtime.Gosched()
}
if ready.Load() {
t.Fatal("readiness still true after cancel")
}
select {
case err := <-done:
t.Fatalf("serve returned %v before the in-flight request finished", err)
case <-time.After(100 * time.Millisecond):
}
close(release)
r := <-resc
if r.err != nil || r.body != "done" {
t.Fatalf("in-flight request: body=%q err=%v", r.body, r.err)
}
select {
case err := <-done:
if err != nil {
t.Fatalf("serve = %v, want nil", err)
}
case <-time.After(2 * time.Second):
t.Fatal("serve did not return within the shutdown timeout")
}
}
// TestServeShutdownTimeout: a request that never finishes makes serve give up
// after the timeout and report it, instead of hanging past the grace period.
func TestServeShutdownTimeout(t *testing.T) {
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
var ready atomic.Bool
started := make(chan struct{})
block := make(chan struct{})
defer close(block)
mux := http.NewServeMux()
mux.HandleFunc("GET /stuck", func(http.ResponseWriter, *http.Request) {
close(started)
<-block
})
ctx, cancel := context.WithCancel(context.Background())
done := make(chan error, 1)
go func() { done <- serve(ctx, slog.New(slog.DiscardHandler), ln, mux, &ready, 200*time.Millisecond) }()
go func() {
if resp, err := http.Get("http://" + ln.Addr().String() + "/stuck"); err == nil {
resp.Body.Close()
}
}()
<-started
start := time.Now()
cancel()
select {
case err := <-done:
if !errors.Is(err, context.DeadlineExceeded) {
t.Fatalf("serve = %v, want shutdown deadline exceeded", err)
}
if el := time.Since(start); el > time.Second {
t.Fatalf("serve took %v, want about 200ms", el)
}
case <-time.After(2 * time.Second):
t.Fatal("serve hung past the shutdown timeout")
}
}module academy/docker-images-dockerfiles
go 1.24The image: manifest-first ordering, cache mounts, cross-compilation from $BUILDPLATFORM, a test target, distroless static with a numeric non-root user, OCI labels, exec-form HEALTHCHECK and ENTRYPOINT.
# syntax=docker/dockerfile:1
#
# orders-api: multi-stage, cross-compiled, distroless, non-root.
# Build: docker buildx build --platform linux/amd64,linux/arm64 \
# --build-arg VERSION=1.4.2 --build-arg COMMIT=$(git rev-parse --short HEAD) \
# -t ghcr.io/acme/orders-api:1.4.2 --push .
# In production pin both FROM lines by digest as well as tag, e.g.
# golang:1.27-trixie@sha256:<digest> (look it up with: docker buildx imagetools inspect golang:1.27-trixie)
ARG GO_VERSION=1.27
# ---- build stage: runs on the builder's own CPU ($BUILDPLATFORM), no QEMU ----
FROM --platform=$BUILDPLATFORM golang:${GO_VERSION}-trixie AS build
WORKDIR /src
# 1. Dependency manifest first: this layer is reused until go.mod (and go.sum,
# once the module has third-party requirements) changes.
# This module uses only the standard library, so there is no go.sum to copy.
COPY go.mod ./
RUN --mount=type=cache,target=/go/pkg/mod \
go mod download
# 2. Source next: editing main.go invalidates only the layers from here down.
COPY . .
# 3. Cross-compile a static binary for the requested target platform.
ARG TARGETOS TARGETARCH
ARG VERSION=dev
ARG COMMIT=none
RUN --mount=type=cache,target=/go/pkg/mod \
--mount=type=cache,target=/root/.cache/go-build \
CGO_ENABLED=0 GOOS=$TARGETOS GOARCH=$TARGETARCH \
go build -trimpath \
-ldflags="-s -w -X main.version=${VERSION} -X main.commit=${COMMIT}" \
-o /out/orders-api .
# ---- test stage: `docker buildx build --target test .` runs vet and tests ----
FROM build AS test
RUN --mount=type=cache,target=/go/pkg/mod \
--mount=type=cache,target=/root/.cache/go-build \
go vet ./... && go test ./...
# ---- runtime stage: no shell, no package manager, CA certs + tzdata only ----
FROM gcr.io/distroless/static-debian13:nonroot AS runtime
ARG VERSION=dev
ARG COMMIT=none
LABEL org.opencontainers.image.title="orders-api" \
org.opencontainers.image.source="https://github.com/acme/orders-api" \
org.opencontainers.image.version="${VERSION}" \
org.opencontainers.image.revision="${COMMIT}" \
org.opencontainers.image.licenses="MIT"
COPY --from=build /out/orders-api /orders-api
# Numeric UID:GID (65532 = distroless "nonroot") so Kubernetes runAsNonRoot can verify it.
USER 65532:65532
ENV PORT=8080
EXPOSE 8080
# Exec form: there is no /bin/sh in this image. The binary probes itself.
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
CMD ["/orders-api", "healthcheck"]
# Exec form: orders-api is PID 1 and receives SIGTERM from `docker stop`.
ENTRYPOINT ["/orders-api"]# Send the builder only what the build needs. Smaller context, fewer cache
# misses, no secrets in layers.
.git
.github
.idea
.vscode
# Local build output and test artefacts
bin/
dist/
*.out
coverage.*
# Secrets and local config never belong in an image
.env
.env.*
*.pem
*.key
# The Dockerfiles themselves are still sent to the builder for the build,
# but excluding them keeps COPY . . from baking them into the image.
Dockerfile*
.dockerignoreThe pipeline that builds, scans, signs and pushes it (GitHub Actions; the same steps map one-to-one onto GitLab CI with docker buildx and cosign in a job):
# .github/workflows/build-push.yml
# Multi-arch build, registry cache, SBOM + max provenance, scan, keyless signing.
# Pin third-party actions to a full commit SHA in production; tags are shown for readability.
name: image
on:
push:
branches: [main]
tags: ["v*.*.*"]
permissions:
contents: read
packages: write # push to ghcr.io with GITHUB_TOKEN
id-token: write # OIDC token for cosign keyless signing
env:
IMAGE: ghcr.io/${{ github.repository_owner }}/orders-api
jobs:
image:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7
- uses: docker/setup-qemu-action@v4 # only needed for RUN steps under emulation
- uses: docker/setup-buildx-action@v4
- uses: docker/login-action@v4
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- id: meta
uses: docker/metadata-action@v6
with:
images: ${{ env.IMAGE }}
tags: |
type=semver,pattern={{version}}
type=semver,pattern={{major}}.{{minor}}
type=sha,format=long
type=ref,event=branch
- id: build
uses: docker/build-push-action@v7
with:
context: go-service
platforms: linux/amd64,linux/arm64
push: true
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
build-args: |
VERSION=${{ steps.meta.outputs.version }}
COMMIT=${{ github.sha }}
cache-from: type=registry,ref=${{ env.IMAGE }}:buildcache
cache-to: type=registry,ref=${{ env.IMAGE }}:buildcache,mode=max
provenance: mode=max
sbom: true
- name: Scan the pushed digest
uses: aquasecurity/trivy-action@v0.36.0
with:
image-ref: ${{ env.IMAGE }}@${{ steps.build.outputs.digest }}
format: table
exit-code: "1"
ignore-unfixed: true
severity: CRITICAL,HIGH
- uses: sigstore/cosign-installer@v4.1.4
- name: Sign by digest (keyless, GitHub OIDC)
env:
DIGEST: ${{ steps.build.outputs.digest }}
run: cosign sign --yes "${IMAGE}@${DIGEST}"The Go angle
- Static by choice, not by accident. cgo is off by default only when cross-compiling or when no C compiler is found; the
golangimages have gcc, so a native build inside them links against glibc. Always setCGO_ENABLED=0forstatic/scratchimages, and check withgo version -m binary | grep CGO_ENABLED. - What cgo-free changes. With cgo off,
netuses the pure-Go DNS resolver andos/userreads/etc/passwddirectly, which is why distroless ships a passwd file. If you need cgo (SQLite viamattn/go-sqlite3, some crypto libraries), usedistroless/baseorcc. - Version stamping.
-ldflags "-X main.version=..."sets a string variable at link time. Go also embeds VCS data (vcs.revision,vcs.time,vcs.modified) when it builds inside a repository;.dockerignoreexcludes.git, so in the image that data is absent and theCOMMITbuild arg carries it instead (-buildvcs=falsemakes the omission explicit). - Size flags.
-s -wdrop the symbol table and DWARF;-trimpathremoves local paths (and makes builds from different checkouts byte-identical). The Lab shows the difference on this service. - Caches.
/go/pkg/mod(module cache) and/root/.cache/go-build(build cache) are exactly the paths Docker's cache guide uses;GOFLAGS=-mod=readonlyand a committedgo.sumkeep the download step deterministic. - ko builds Go images without a Dockerfile (cosign's own docs use it); it produces distroless-based, multi-arch images and is a good fit for pure-Go services.
- Graceful shutdown budget.
shutdownTimeout(8 s) must be below the runtime's grace period (Docker's defaultdocker stoptimeout is 10 s; KubernetesterminationGracePeriodSecondsdefaults to 30 s). In Kubernetes, readiness flips off first so endpoints are removed before the drain. - More on build flags and module hygiene: Toolchain, Modules & Packages, Project Layout, Linting & Build, and the server itself in HTTP Server & Client.
Laravel
Before
The Dockerfile many Laravel projects start with: one stage, root, development php.ini, Composer and Node inside the runtime, config cached at build time, and a shell-form start command.
# Before: works on a laptop, wrong in production
FROM php:8.4-fpm
RUN apt-get update && apt-get install -y git unzip nodejs npm libpq-dev \
&& docker-php-ext-install pdo_pgsql
COPY --from=composer:2 /usr/bin/composer /usr/bin/composer
COPY . /var/www/html
WORKDIR /var/www/html
RUN composer install && npm install && npm run build
# Bakes the BUILD machine's .env (or none) into bootstrap/cache/config.php
RUN php artisan config:cache
CMD php-fpmAfter
One Dockerfile, two runtime targets (app = php-fpm, web = Nginx), with Composer and Vite in their own stages:
# syntax=docker/dockerfile:1
#
# Laravel 13 on php-fpm + Nginx, two images from one Dockerfile.
# Build context: the root of a Laravel application (artisan, composer.json,
# composer.lock, package.json, package-lock.json, app/, public/, resources/ ...).
# docker buildx build --target app -t ghcr.io/acme/shop-app:1.8.0 .
# docker buildx build --target web -t ghcr.io/acme/shop-web:1.8.0 .
ARG PHP_VERSION=8.4
ARG NODE_VERSION=22
# ---- base: PHP runtime + extensions, shared by every later stage ----
FROM php:${PHP_VERSION}-fpm-trixie AS base
# Extensions the shop needs beyond the image defaults (check `php -m` first).
# The -dev packages stay because the extensions link against their libraries.
# (Cache-mount pattern from the Dockerfile reference: keep apt's downloads between builds.)
RUN rm -f /etc/apt/apt.conf.d/docker-clean; \
echo 'Binary::apt::APT::Keep-Downloaded-Packages "true";' > /etc/apt/apt.conf.d/keep-cache
RUN --mount=type=cache,target=/var/cache/apt,sharing=locked \
--mount=type=cache,target=/var/lib/apt,sharing=locked \
apt-get update \
&& apt-get install -y --no-install-recommends libpq-dev libicu-dev libzip-dev unzip \
&& docker-php-ext-install -j"$(nproc)" pdo_pgsql intl zip pcntl bcmath
# Production php.ini (the image ships php.ini-development and php.ini-production).
RUN mv "$PHP_INI_DIR/php.ini-production" "$PHP_INI_DIR/php.ini"
# OPcache is already enabled in the official image; tune it for immutable code.
COPY docker/php/opcache.ini "$PHP_INI_DIR/conf.d/zz-opcache.ini"
WORKDIR /var/www/html
# ---- vendor: Composer in its own stage; only vendor/ and the autoloader leave it ----
FROM base AS vendor
COPY --from=composer:2 /usr/bin/composer /usr/bin/composer
ENV COMPOSER_CACHE_DIR=/tmp/composer-cache
# Lock files first: this layer is reused until dependencies change.
COPY composer.json composer.lock ./
RUN --mount=type=cache,target=/tmp/composer-cache \
composer install --no-dev --no-scripts --no-autoloader --prefer-dist --no-interaction
# Application code, then the optimized, authoritative classmap.
# dump-autoload runs the post-autoload-dump scripts (artisan package:discover).
COPY . .
RUN composer dump-autoload --no-dev --optimize --classmap-authoritative --no-interaction
# ---- assets: Vite build; Node never reaches the runtime images ----
FROM node:${NODE_VERSION}-alpine AS assets
WORKDIR /app
COPY package.json package-lock.json ./
RUN --mount=type=cache,target=/root/.npm npm ci
COPY . .
RUN npm run build
# ---- app: the php-fpm image that runs in production ----
FROM base AS app
LABEL org.opencontainers.image.source="https://github.com/acme/shop" \
org.opencontainers.image.title="shop-app"
COPY --from=vendor --chown=www-data:www-data /var/www/html /var/www/html
COPY --from=assets --chown=www-data:www-data /app/public/build /var/www/html/public/build
COPY --chmod=0755 docker/php/entrypoint.sh /usr/local/bin/app-entrypoint
# FPM as a non-root user: the official image documents --user for FPM variants.
USER www-data
# Inherited from php:8.4-fpm: EXPOSE 9000, STOPSIGNAL SIGQUIT (graceful FPM stop).
ENTRYPOINT ["app-entrypoint"]
CMD ["php-fpm"]
# ---- web: Nginx with only the public/ directory, talking FastCGI to app:9000 ----
FROM nginx:1.28-alpine AS web
COPY docker/nginx/default.conf /etc/nginx/conf.d/default.conf
COPY --from=app /var/www/html/public /var/www/html/publicThe entrypoint caches config at start-up (when the real environment exists) and execs so php-fpm is PID 1:
#!/bin/sh
# Runs at container start, when the real environment (DB_HOST, APP_KEY, ...) exists.
# Caching config at build time would bake the build machine's env into the image.
set -eu
php artisan optimize # config, events, routes and views caches
# exec replaces this shell, so php-fpm becomes PID 1 and receives SIGQUIT/SIGTERM.
exec docker-php-entrypoint "$@"; Code inside an image never changes, so never stat files for changes.
; A new release is a new image (and a new container), which starts with an empty cache.
opcache.enable=1
opcache.validate_timestamps=0
opcache.memory_consumption=256
opcache.interned_strings_buffer=32
opcache.max_accelerated_files=20000# Based on the Laravel deployment docs' Nginx example; fastcgi_pass points at
# the php-fpm container (service "app") instead of a local Unix socket.
server {
listen 80;
server_name _;
root /var/www/html/public;
add_header X-Frame-Options "SAMEORIGIN";
add_header X-Content-Type-Options "nosniff";
index index.php;
charset utf-8;
location / {
try_files $uri $uri/ /index.php?$query_string;
}
location = /favicon.ico { access_log off; log_not_found off; }
location = /robots.txt { access_log off; log_not_found off; }
error_page 404 /index.php;
location ~ ^/index\.php(/|$) {
fastcgi_pass app:9000;
# The PHP files live in the app container at the same path.
fastcgi_param SCRIPT_FILENAME /var/www/html/public/index.php;
include fastcgi_params;
fastcgi_hide_header X-Powered-By;
}
location ~ /\.(?!well-known).* {
deny all;
}
}# Laravel build context: keep secrets, dependencies and local state out.
.git
.env
.env.*
!.env.example
node_modules
vendor
public/build
public/hot
storage/logs/*
storage/framework/cache/*
storage/framework/sessions/*
storage/framework/views/*
bootstrap/cache/*.php
tests
phpunit.xml
.phpunit.result.cache
docker-compose*.yml
compose*.yaml
Dockerfile*
.dockerignoreA minimal Compose file for the two containers (Compose itself is taught in Running Containers):
# Two containers from one Dockerfile: Nginx (web) in front of php-fpm (app).
# Running, volumes and Compose itself: see /platform/docker-run-volumes-compose.
services:
app:
build:
context: .
target: app
image: ghcr.io/acme/shop-app:dev
env_file: .env
web:
build:
context: .
target: web
image: ghcr.io/acme/shop-web:dev
ports:
- "8080:80"
depends_on:
- app
healthcheck:
# /up is Laravel's health route: 200 if the app boots, 500 otherwise.
# It goes through Nginx and FastCGI, so it tests both containers.
test: ["CMD", "wget", "-q", "-O", "/dev/null", "http://127.0.0.1/up"]
interval: 30s
timeout: 3s
retries: 3
start_period: 10sThe single-container alternative: FrankenPHP with Octane, non-root on an unprivileged port, health-checked through /up with PHP itself:
# syntax=docker/dockerfile:1
#
# Laravel 13 + Octane on FrankenPHP: ONE container, no Nginx, no php-fpm.
# Build context: the root of a Laravel application with laravel/octane installed.
# Tags follow dunglas/frankenphp:<frankenphp-version>-php<php-version>-<os>.
FROM dunglas/frankenphp:1-php8.4-trixie AS base
# install-php-extensions ships in the FrankenPHP images; pcntl is required by Octane.
RUN install-php-extensions pcntl pdo_pgsql intl zip opcache
RUN mv "$PHP_INI_DIR/php.ini-production" "$PHP_INI_DIR/php.ini"
WORKDIR /app
FROM base AS vendor
COPY --from=composer:2 /usr/bin/composer /usr/bin/composer
ENV COMPOSER_CACHE_DIR=/tmp/composer-cache
COPY composer.json composer.lock ./
RUN --mount=type=cache,target=/tmp/composer-cache \
composer install --no-dev --no-scripts --no-autoloader --prefer-dist --no-interaction
COPY . .
RUN composer dump-autoload --no-dev --optimize --classmap-authoritative --no-interaction
FROM base AS app
ARG USER=appuser
# Non-root, unprivileged port, no extra capability (FrankenPHP docs, "Running with no capabilities").
RUN useradd ${USER} \
&& setcap -r /usr/local/bin/frankenphp \
&& chown -R ${USER}:${USER} /config/caddy /data/caddy
COPY --from=vendor --chown=${USER}:${USER} /app /app
USER ${USER}
ENV SERVER_NAME=:8000
EXPOSE 8000
# No curl needed: PHP itself fetches Laravel's /up health route.
HEALTHCHECK --interval=30s --timeout=3s --start-period=10s --retries=3 \
CMD ["php", "-r", "exit(@file_get_contents('http://127.0.0.1:8000/up') === false ? 1 : 0);"]
# Octane boots the app once and keeps it in memory; workers default to one per CPU core.
ENTRYPOINT ["php", "artisan", "octane:frankenphp"]
CMD ["--host=0.0.0.0", "--port=8000"]The Laravel angle
- Requirements. Laravel 13 "requires PHP 8.3 or higher" plus Ctype, cURL, DOM, Fileinfo, Filter, Hash, Mbstring, OpenSSL, PCRE, PDO, Session, Tokenizer and XML; most are compiled into the official image (check
php -m), so only drivers and extras (pdo_pgsql,intl,zip,pcntl,bcmath) are installed. php artisan optimize"will cache all of these files" (config, events, routes, views). Config caching freezesenv()values, so it belongs at container start (entrypoint) or in a release step, never in a build stage that has no production environment.- Health route. Laravel serves
/upby default ("will return a 200 HTTP response if the application has booted without exceptions"), configured withhealth: '/up'inbootstrap/app.php; it is the natural target for Compose health checks and Kubernetes probes:
<?php
// bootstrap/app.php (excerpt): the health route used by HEALTHCHECK and probes
use Illuminate\Foundation\Application;
return Application::configure(basePath: dirname(__DIR__))
->withRouting(
web: __DIR__.'/../routes/web.php',
commands: __DIR__.'/../routes/console.php',
health: '/up',
)
->create();- Writable paths. Only
storage/andbootstrap/cache/need to be writable; logs should go tostderr(LOG_CHANNEL=stderr) so the container runtime collects them, and sessions/cache to Redis or the database, not the container layer. - Queue workers and the scheduler reuse the
appimage with a different command:CMD ["php","artisan","queue:work","--max-time=3600"](exec form so SIGTERM reaches the worker) andCMD ["php","artisan","schedule:work"]. Laravel documents--max-time("process jobs for the given number of seconds and then exit") and presentsschedule:workfor running the scheduler in the foreground without cron; production setups may instead runschedule:runfrom cron. - Octane caveat. The app stays in memory, so static state and singletons leak between requests; Laravel's Octane docs cover
--max-requestsand the per-request reset rules. On a host, the static FrankenPHP binary that Octane downloads "includes its own copy of PHP", so system PHP updates do not reach it; in Docker, thedunglas/frankenphpimages "are based on official PHP images", so a new image digest is how PHP gets patched. - Sail (
laravel/sail) is a development environment, not a production image; build production images from a Dockerfile like the one above.
Solving the classic problems
| Problem | Solution | How | Advantage | Cost / limit |
|---|---|---|---|---|
| Every build re-downloads dependencies | Manifest-first ordering + cache mounts | COPY go.mod go.sum / composer.lock before source; --mount=type=cache | Minutes become seconds | Needs BuildKit; cache is per builder |
| CI has no cache | External cache | --cache-to type=registry,...,mode=max / type=gha | Warm builds on fresh runners | Cache export time and storage |
| Image is huge | Multi-stage + smaller base | Toolchain in build stage, distroless/slim runtime | Smaller pulls, fewer CVEs | No shell in distroless |
| Secrets in layers or history | Secret mounts | RUN --mount=type=secret,id=... + --secret | Never stored, not in provenance | Changing a secret does not bust cache |
App ignores docker stop | Exec form + signal handling | ENTRYPOINT ["app"], exec "$@", tini/--init | Graceful drains | Must also handle SIGTERM in code |
| Runs as root | USER with numeric UID | USER 65532:65532, COPY --chown | Passes runAsNonRoot, smaller blast radius | Ports < 1024 need a capability |
| Wrong architecture | Multi-arch index | --platform linux/amd64,linux/arm64, cross-compile | One name for every host | Emulation is slow for compiled stacks |
| "Same tag, different code" | Digests + immutable tags | Deploy @sha256:; ECR IMMUTABLE | Exact rollbacks | Need tooling to bump digests |
| Docker Hub 429s | Authenticate and mirror | docker login, pull-through cache | Stable CI | One more registry to run |
| Unknown origin of an image | Provenance + signature | --provenance=mode=max, cosign sign by digest, admission verify | Policy-enforced trust | Key/OIDC setup, policy maintenance |
| Health check always failing | Self-probe | CMD ["/app","healthcheck"], php -r | Works without curl or shell | One more code path to test |
Dependencies re-download on every commit
Order by change frequency, then add cache mounts so even a miss is warm. In the Go Dockerfile, go.mod is copied alone; once the module gains third-party requirements, copy go.sum with it (COPY go.mod go.sum ./). For Composer, composer.json composer.lock then composer install --no-autoloader, then COPY . ., then dump-autoload.
Secrets needed at build time
# syntax=docker/dockerfile:1
FROM php:8.4-fpm-trixie AS vendor
COPY --from=composer:2 /usr/bin/composer /usr/bin/composer
COPY composer.json composer.lock ./
# COMPOSER_AUTH holds {"github-oauth": {"github.com": "..."}} for private packages
RUN --mount=type=secret,id=composer_auth,env=COMPOSER_AUTH,required=true \
composer install --no-dev --no-scripts --no-autoloader --prefer-distCOMPOSER_AUTH="$(cat ~/.composer/auth.json)" \
docker buildx build --secret id=composer_auth,env=COMPOSER_AUTH --target app .Graceful stop that actually drains
Exec-form ENTRYPOINT; the Go service catches SIGTERM, fails readiness, then calls srv.Shutdown with a timeout below the grace period; the Laravel entrypoint ends in exec docker-php-entrypoint "$@" and php-fpm's image-level STOPSIGNAL SIGQUIT gives FPM's graceful stop. For processes that fork children (a PHP script calling exec() on tools), run with docker run --init or put tini in the image.
Size regression in a pull request
Gate it: CI=true dive <image> with a .dive-ci (lowestEfficiency, highestWastedBytes), and compare docker image ls sizes between main and the PR build. The usual culprits are listed under Image size.
Debugging a distroless container
There is no shell to docker exec into. Options: rebuild with the :debug (or :debug-nonroot) tag, which "provides a busybox shell"; docker run --entrypoint=sh image:debug; in Kubernetes, kubectl debug -it pod --image=busybox --target=app attaches an ephemeral container sharing the process namespace (Kubernetes Workloads).
Base image CVEs appear after release
Rebuild on a schedule (nightly or weekly) with --pull, so the newest base digest is resolved; Renovate or Dependabot can bump FROM image:tag@sha256:... lines in pull requests. Docker's guide adds that COPY --link lets BuildKit "rebase your images when the base images receive updates, without having to execute the whole build again".
One image, several processes (Laravel web + queue + scheduler)
Build one app image and run it three times with different commands (php-fpm, queue:work, schedule:work) rather than baking supervisord into the image. Each container then has one PID 1, its own restart policy and its own scaling.
Choosing
Which runtime base
| Workload | Recommended base | Extra technique | Reason |
|---|---|---|---|
Go service, CGO_ENABLED=0 | gcr.io/distroless/static-debian13:nonroot | -trimpath -ldflags "-s -w" | Smallest useful base with certs, tzdata, passwd |
| Go CLI with no TLS or time zones | scratch | Embed time/tzdata if needed | Nothing to patch |
| Go with cgo (SQLite, librdkafka) | gcr.io/distroless/base-debian13 or cc | Same Debian release as the build stage | glibc ABI match |
| Laravel on php-fpm | php:8.4-fpm-trixie + nginx:1.28-alpine | Production ini, OPcache tuned, non-root FPM | Official, maintained, glibc |
| Laravel with Octane | dunglas/frankenphp:1-php8.4-trixie | pcntl, non-root, SERVER_NAME=:8000 | One process serves HTTP and PHP |
| Tools image for CI jobs | debian:trixie-slim or alpine:3.23 | Pin package versions | Needs a shell and a package manager |
Which tags
| Situation | Tags to push | What to deploy |
|---|---|---|
Release from a Git tag v1.4.2 | 1.4.2, 1.4, 1, sha-<commit> | Digest of that build |
| Main branch | main, sha-<commit> | Digest (GitOps tool writes it back) |
| Pull request preview | pr-<n> | Digest; delete tag on merge |
| Base images you consume | (theirs) | FROM name:tag@sha256:... bumped by bot |
Which registry setup
| Team / platform | Registry | Why |
|---|---|---|
| GitHub-centric, open source | GHCR | GITHUB_TOKEN, repo linking, free public images |
| AWS workloads (EKS, ECS) | ECR (+ pull-through cache for Docker Hub) | IAM auth, immutability, in-region pulls |
| GitLab-centric | GitLab container registry | CI_JOB_TOKEN, built-in cleanup policies |
| Air-gapped or multi-cloud | Harbor / Artifactory | Proxy cache, replication, robot accounts, signing policy |
| Public distribution | Docker Hub (+ GHCR mirror) | Discoverability; mind pull limits for your users |
Which PHP serving model
| Situation | Model | Reason |
|---|---|---|
| Existing Nginx expertise, classic Laravel | Nginx + php-fpm, two containers | Well understood, static files from Nginx |
| One image per service wanted, HTTP/3, automatic TLS | FrankenPHP (classic mode) | One process, Caddy built in |
| Latency-sensitive API, app is stateless-safe | FrankenPHP or Swoole/RoadRunner with Octane | Boot once, serve many requests |
| Kubernetes pod | Nginx sidecar + php-fpm in one pod, or FrankenPHP | Sidecar shares localhost; FastCGI never leaves the pod |
In architecture: from a single process to a distributed system
An image is the unit that crosses every boundary below: it is what CI produces, what a registry stores, what an orchestrator schedules and what a policy engine verifies. The architecture questions are about how many images, who builds them, where they are stored and how a deployment names them.
Monolith: one process, one image
A Laravel monolith on one VM: one Dockerfile with app and web targets, a Compose file, and docker compose pull && docker compose up -d on deploy. The simplest correct version already needs the essentials of this page: lock-file-first caching, production php.ini and OPcache, non-root FPM, config:cache at start, and a release tag that never moves (1.8.0) so docker compose up on the second VM runs the same bytes. Scheduler and queue workers are the same image with different commands, not separate Dockerfiles.
Modular monolith: one repository, several images
The same codebase starts producing more than one image (web, worker, a Go sidecar for PDF rendering). Decisions: one Dockerfile with several targets (shared base stage, built once) versus one Dockerfile per module; a docker buildx bake file that builds all targets in one invocation with shared cache; per-target .dockerignore files (worker.Dockerfile.dockerignore) so a frontend change does not rebuild the worker. Versioning stays unified (all images get sha-<commit>), which keeps "which web goes with which worker" trivial.
Microservices: many images, many teams
Twenty services, each in its own repository, built by GitHub Actions or GitLab CI and deployed to Kubernetes. What must be shared is not code but the golden path: a base image per language maintained by the platform team (ghcr.io/acme/base-go:1.27 built on distroless, ghcr.io/acme/base-php:8.4-fpm with extensions and production ini), a reusable CI workflow that builds multi-arch, attaches SBOM and provenance, scans and signs, and an admission policy that only admits signed images from ghcr.io/acme/*. A typical flow for orders-api v1.4.2:
1 git tag v1.4.2 -> CI: lint (hadolint, --check) -> test target -> build+push index D
2 CI: trivy image @D (fail on fixable HIGH/CRITICAL) -> cosign sign @D (OIDC identity of the workflow)
3 CI opens a PR in the GitOps repo: Helm values image.digest = D (or Kustomize images: digest)
4 Argo CD (or Flux) syncs; Kyverno / policy-controller verifies the signature for D before admission
5 kubelet pulls D; nodes that already have the distroless base fetch only the binary layerProvisioning around it (registries, IAM roles for CI's OIDC, ECR lifecycle and immutability) is typically Terraform; Helm charts and Argo CD are covered in Packaging for Kubernetes and GitOps. The architectural view of why containers and Kubernetes at all is Containers & Kubernetes.
Distributed data: registries, mirrors, caches and regions
At scale the registry becomes a distributed system on your critical path: a node that cannot pull cannot start pods, and a region-wide outage of an upstream registry stops every autoscaling event. Patterns: pull-through caches (ECR pull-through cache, Harbor proxy projects, registry-mirrors for Docker Engine, containerd hosts.toml mirrors) so Docker Hub's per-IP limits and outages stop mattering; replication of release repositories into each region (ECR cross-region replication, Harbor replication rules) so pulls stay in-region; content addressing makes this safe: a digest fetched from a mirror is verified locally, so a mirror cannot substitute bytes. Signatures and attestations must replicate too (OCI 1.1 referrers or cosign's tag scheme), or the policy engine in the far region will reject an image whose signature stayed behind. Large images also have a cost per node: lazy-pulling snapshotters (stargz, SOCI, nydus; Docker 29's lazy-pull feature for known remote snapshotters) start containers before every byte is local.
Scaling path: 1x, 10x, 100x
| Scale | Builds | Images and registry | Deploys |
|---|---|---|---|
| 1x (one team, one VM) | Local docker build, then a single CI job | Docker Hub or GHCR, semver tags | Compose, pinned tags |
| 10x (several teams, one cluster) | CI with registry cache (mode=max), multi-arch, build checks and scanning as gates | GHCR/ECR, immutable release tags, lifecycle rules, base images maintained centrally | Helm/Kustomize with digests, Argo CD or Flux |
| 100x (many clusters, regions) | Remote/native multi-arch builders (BuildKit on Kubernetes, Docker Build Cloud), bake files, reproducible builds | Regional replicas, pull-through caches, referrers replicated, SBOM inventory queried centrally | Signed-digest admission everywhere, scheduled rebuilds for base CVEs, progressive delivery |
Lab
Label: every docker, buildx, cosign, trivy, hadolint and dive command below is expected, not run: no Docker daemon and no Docker labs in this build environment (AUTHORING cost rule). Their output is shown as placeholders or as the sample output printed in Docker's own docs, never as invented sizes, timings or digests. Steps marked ran on the host were executed on macOS (Go 1.27.4, darwin/arm64) and show real output.
1. Build and test the Go service without Docker (ran on the host)
cd docs/snippets/platform/docker-images-dockerfiles/go-service
gofmt -l . ; go vet ./... ; go test -race -count=1 ./...
# ok academy/docker-images-dockerfiles 1.421s2. What CGO_ENABLED=0, -s -w and cross-compilation do (ran on the host)
for a in amd64 arm64; do
CGO_ENABLED=0 GOOS=linux GOARCH=$a go build -trimpath \
-ldflags "-s -w -X main.version=1.4.2 -X main.commit=abc1234" -o orders-api-linux-$a .
done
GOOS=linux GOARCH=amd64 go build -o orders-api-linux-amd64-full . # no flags
file orders-api-linux-*
# orders-api-linux-amd64: ELF 64-bit LSB executable, x86-64, ..., statically linked, ..., stripped
# orders-api-linux-amd64-full: ELF 64-bit LSB executable, x86-64, ..., statically linked, ..., with debug_info, not stripped
# orders-api-linux-arm64: ELF 64-bit LSB executable, ARM aarch64, ..., statically linked, ..., stripped
ls -l orders-api-linux-*
# 7237792 orders-api-linux-amd64 (stripped, -trimpath)
# 10683044 orders-api-linux-amd64-full (symbols + DWARF)
# 6750368 orders-api-linux-arm64
go version -m orders-api-linux-arm64 | grep -E 'CGO_ENABLED|GOARCH|trimpath'
# build -trimpath=true
# build CGO_ENABLED=0
# build GOARCH=arm64Two observations: the "full" build is static too, because cross-compiling disables cgo by default (exactly the cgo docs' rule); and -s -w removed about a third of the file (7.2 MB vs 10.7 MB here).
3. Signals, readiness and the self-probe (ran on the host)
Commands as run, in one session (native darwin build of the same code; the JSON log lines are trimmed of their time field):
go build -trimpath -ldflags "-s -w -X main.version=1.4.2 -X main.commit=abc1234" -o orders-api .
PORT=18080 ./orders-api > run.log 2>&1 & P=$!
curl -s --retry 20 --retry-connrefused --retry-delay 0 http://127.0.0.1:18080/version
# {"commit":"abc1234","version":"1.4.2"}
curl -s -w '%{http_code}\n' http://127.0.0.1:18080/readyz
# ready
# 200
PORT=18080 ./orders-api healthcheck; echo "healthcheck exit=$?" # healthcheck exit=0
kill -TERM $P; wait $P; echo "server exit=$?" # server exit=0
cat run.log
# {"level":"INFO","msg":"listening","addr":"[::]:18080","version":"1.4.2","commit":"abc1234"}
# {"level":"INFO","msg":"shutting down","timeout":"8s"}
# {"level":"INFO","msg":"stopped"}
PORT=18081 ./orders-api healthcheck; echo "exit=$?" # nothing listening: exit=14. Build, inspect and compare the two Dockerfiles (expected, not run)
docker build -f Dockerfile.before -t orders-api:before .
docker buildx build --target runtime -t orders-api:after --load .
docker image ls orders-api
# REPOSITORY TAG IMAGE ID SIZE
# orders-api before <id> <size> (full golang toolchain + Debian + source)
# orders-api after <id> <size> (distroless static base + one binary layer)
docker image history orders-api:after
docker image inspect --format '{{.Config.User}} {{json .Config.Entrypoint}}' orders-api:after
# 65532:65532 ["/orders-api"]
docker run -d --name o1 -p 8080:8080 orders-api:after
docker inspect --format '{{.State.Health.Status}}' o1 # starting, then healthy
docker stop o1 # returns within the 8 s drain, well before the 10 s SIGKILL
docker logs o1 # ... "shutting down" ... "stopped"Try the same docker stop against orders-api:before (shell-form CMD): if /bin/sh stays PID 1, the stop waits the full 10 s and ends in SIGKILL with no "stopped" line.
5. Cache behaviour (expected, not run)
docker buildx build --target runtime --progress=plain . 2>&1 | grep -E '^#[0-9]+ (\[|CACHED|DONE)'
echo '// touch' >> main.go
docker buildx build --target runtime --progress=plain . 2>&1 | grep -E '^#[0-9]+ (\[|CACHED|DONE)'
# expected shape (step numbers and timings are placeholders):
# #N [build 3/6] COPY go.mod ./ then #N CACHED
# #N [build 4/6] RUN ... go mod download then #N CACHED
# #N [build 5/6] COPY . . then #N DONE <time>
# #N [build 6/6] RUN ... go build ... then #N DONE <time>
docker build --check . # build checks; non-zero exit on violations6. Multi-arch index and attestations (expected, not run; the sample below is Docker's documented output for alpine)
docker buildx create --name multi --driver docker-container --use
docker buildx build --platform linux/amd64,linux/arm64 \
--sbom=true --provenance=mode=max \
-t registry.example.test/acme/orders-api:1.4.2 --push .
docker buildx imagetools inspect alpine
# Name: docker.io/library/alpine:latest
# MediaType: application/vnd.docker.distribution.manifest.list.v2+json
# Digest: sha256:21a3deaa0d32a8057914f36584b5288d2e5ecc984380bc0118285c70fa8c9300
# Manifests:
# Name: docker.io/library/alpine:latest@sha256:e7d88de73db3d3fd9b2d63aa7f447a10fd0220b7cbf39803c803f2af9ba256b3
# MediaType: application/vnd.docker.distribution.manifest.v2+json
# Platform: linux/amd64
# ...
# Platform: linux/arm64/v87. Rate-limit headers, scan and sign (expected, not run; header sample from Docker's pull-limit docs)
TOKEN=$(curl -s "https://auth.docker.io/token?service=registry.docker.io&scope=repository:ratelimitpreview/test:pull" | jq -r .token)
curl -s --head -H "Authorization: Bearer $TOKEN" https://registry-1.docker.io/v2/ratelimitpreview/test/manifests/latest
# ratelimit-limit: 100;w=21600
# ratelimit-remaining: 20;w=21600
# docker-ratelimit-source: 192.0.2.1
hadolint Dockerfile.before # expect DL3007 (latest), DL3025 (JSON CMD), DL3002-style findings
trivy image --severity HIGH,CRITICAL --exit-code 1 --ignore-unfixed registry.example.test/acme/orders-api:1.4.2
cosign sign --yes registry.example.test/acme/orders-api@sha256:<digest from the push>
cosign verify registry.example.test/acme/orders-api@sha256:<digest> \
--certificate-identity=https://github.com/acme/orders-api/.github/workflows/build-push.yml@refs/tags/v1.4.2 \
--certificate-oidc-issuer=https://token.actions.githubusercontent.comCommon misconceptions
| Belief | Reality |
|---|---|
RUN rm in a later step shrinks the image | It adds a whiteout; the earlier layer's bytes still ship. Delete in the same RUN or use a discarded stage |
EXPOSE publishes a port | Documentation only; -p/-P or a Service publishes |
latest is the newest version | It is the default tag name; it moves on every push and is not ordered |
| A tag identifies fixed content | Only a digest does; tags move (FrankenPHP: "Tags such as latest ... are moved ... digests never change") |
ARG is safe for secrets because it is not in the container | It is in docker history and in max-mode provenance; use secret mounts |
Shell-form CMD behaves like exec form | /bin/sh -c may be PID 1 and swallow SIGTERM; build checks warn (JSONArgsRecommended) |
Kubernetes uses the Dockerfile HEALTHCHECK | It uses its own probes; HEALTHCHECK is for Docker, Compose and Swarm |
| Alpine is always the best small base | musl differences; Go's Alpine image is "not officially supported by the Go project"; distroless static is smaller for Go |
--squash is the fix for big images | Experimental, legacy builder only, loses layer sharing; multi-stage is Docker's recommended alternative |
apt-get update in a cached layer gives current packages | The cache key is the command string; the week-old index is reused |
| An amd64 image runs anywhere | Only on amd64 (or under emulation); otherwise exec format error |
| Zero scanner findings means secure | Scanners match package versions; they do not see your code or unpackaged binaries |
| Signing a tag protects the deployment | Signatures cover a digest; deploy and verify by digest |
| Running as root in a container is harmless | UID 0 against the kernel and mounted paths; add USER with a numeric UID |
Cheat sheet
| Topic | Remember |
|---|---|
| Image anatomy | index -> manifest per platform -> config + ordered layers; everything by digest |
| Layers | Read-only, additive; whiteouts hide, never free; container layer is copy-on-write, survives stop/start, deleted with the container |
| Cache order | Rarely-changing first: base, system packages, lock files, dependency install, source, build |
| Cache rules | First miss invalidates the rest of the stage; RUN keyed by command string; COPY by file checksum (not mtime) |
| BuildKit mounts | cache for package caches, bind for one-step files, secret for tokens, ssh for private Git |
| Multi-stage | Build with everything, COPY --from only the artefact; --target picks a stage |
| Go image | CGO_ENABLED=0 -trimpath -ldflags "-s -w", FROM --platform=$BUILDPLATFORM, distroless static nonroot |
| PID 1 | Exec form, exec "$@" in scripts, --init/tini for children, handle SIGTERM in code |
| USER | Numeric UID:GID, writable dirs via COPY --chown |
| HEALTHCHECK | Defaults 30s/30s/0s/5s/3; exit 0/1 (2 reserved); self-probe in shell-less images |
| Tags | Humans read tags (1.4.2, 1.4, sha-...); machines deploy digests; releases immutable |
| Registries | Authenticate CI; Docker Hub anonymous 100 pulls / 6 h per IP; mirror base images |
| Supply chain | Default min provenance; add --sbom=true; mode=max exposes build args; cosign by digest |
| Scanning | hadolint + docker build --check before; Trivy/Grype/Scout after; rescan deployed digests |
| PHP | php-fpm + Nginx (never publish 9000) or FrankenPHP/Octane; production ini; OPcache validate_timestamps=0; Composer --no-dev + authoritative classmap; config:cache at start |
| Reproducible | SOURCE_DATE_EPOCH, rewrite-timestamp=true, bases by digest, pinned packages |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — A Dockerfile downloads a 400 MB archive in one RUN, extracts it in a second and deletes the archive in a third. Why is the image still large, and what are two fixes? Must-know
Answer
Answer: Each RUN commits a layer; the archive lives in the first layer and the later deletion only adds a whiteout entry that hides it, so every pull still downloads those bytes. Fix it by doing download, extract and delete in a single RUN, or by doing the work in a build stage and copying only the extracted result into the runtime stage with COPY --from. See Layers.
2 — You edit one Go source file and CI re-downloads every module. What is wrong in the Dockerfile and how do you fix it? Must-know
Answer
Answer: The source is copied (COPY . .) before go mod download, so the changed file's checksum invalidates the download step and everything after it. Copy go.mod and go.sum first, run go mod download, then copy the source; add --mount=type=cache for /go/pkg/mod and /root/.cache/go-build, and export a registry cache (mode=max) because CI runners start empty. See Layer caching.
3 — docker stop on your container always takes 10 seconds and the app logs no shutdown. Why, and what do you change? Must-know
Answer
Answer: The start command is in shell form (or an entrypoint script without exec), so /bin/sh is PID 1 and does not forward SIGTERM; after the daemon's 10 s default for Linux containers Docker sends SIGKILL. Use exec-form ENTRYPOINT/CMD, end scripts with exec "$@", handle SIGTERM in the app, and add --init/tini if the app spawns children. See ENTRYPOINT, CMD and signals.
4 — What is the difference between ENV and ARG, and why is neither acceptable for an npm or Composer token? Must-know
Answer
Answer: ARG exists only at build time and is not in the final container's environment; ENV is set for later build steps and persists into every container. Both are recorded: ARG values appear in docker history and in max-mode provenance, ENV in the image config. Pass tokens with RUN --mount=type=secret,id=... and docker buildx build --secret, which are never stored in a layer, the cache or provenance. See Dockerfile instructions and BuildKit.
5 — Why deploy image@sha256:... instead of image:1.4, and what does Kubernetes do differently for :latest? Must-know
Answer
Answer: A tag is a movable pointer, so two pods (or a rollback) can resolve 1.4 to different builds; a digest names fixed bytes and makes deploys and rollbacks exact. With an image reference that has a digest and no imagePullPolicy, Kubernetes sets IfNotPresent; with :latest it sets Always, and the docs advise avoiding :latest in production. See Tagging strategy.
6 — Your Go image is FROM scratch and HTTPS calls fail with x509: certificate signed by unknown authority. Explain and give two fixes. Important
Answer
Answer: scratch is empty: there is no CA bundle for Go's TLS verification (and no tzdata or /etc/passwd). Either switch to gcr.io/distroless/static-debian13, which contains ca-certificates, tzdata and a passwd file, or COPY --from=build /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/ into the scratch image. See Base images.
7 — How does a cross-compiled multi-arch Go build avoid QEMU, and which Dockerfile lines make it work? Important
Answer
Answer: The build stage is pinned to the builder's own architecture with FROM --platform=$BUILDPLATFORM, and the compiler targets the other architecture via GOOS=$TARGETOS GOARCH=$TARGETARCH (redeclared with ARG TARGETOS TARGETARCH inside the stage) with CGO_ENABLED=0. The runtime stage per platform only copies the binary, so nothing foreign ever executes. buildx then pushes one index with a manifest per platform. See Multi-arch.
8 — Why should the php-fpm container's port 9000 never be published, and what serves HTTP instead? Important
Answer
Answer: FastCGI is "inherently trusting": anyone who can talk to FPM can ask it to execute PHP files with chosen parameters, so the official image warns against -p on fpm variants. Put Nginx (or Caddy) in front on a private network or in the same pod, which serves static files and passes PHP requests with fastcgi_pass app:9000; or replace both with FrankenPHP, which speaks HTTP itself. See PHP images.
9 — Why does running php artisan config:cache in the Dockerfile cause production bugs, and where should it run? Important
Answer
Answer: Config caching evaluates env() once and writes the result to bootstrap/cache/config.php; at build time the production environment (DB host, keys) does not exist, so the image freezes build-machine or empty values. Run php artisan optimize (or config:cache) at container start in an entrypoint that ends with exec, or in a release step with the real environment. See The Laravel angle.
10 — What do --provenance=mode=min, mode=max and --sbom=true attach, and what is the risk of mode=max? Important
Answer
Answer: BuildKit attaches in-toto attestations to the image index: min-level SLSA provenance by default (build timestamps, materials, without build-arg values or secret identities), max-level provenance with full build parameters, and an SPDX SBOM when --sbom=true. mode=max exposes the values of build arguments, so anything secret passed as ARG leaks to anyone who can pull the image. See Supply-chain artefacts.
11 — Is docker build --squash a good way to shrink images today? Good to know
Answer
Answer: No. It is experimental, belongs to the legacy builder (BuildKit's buildx build has no such flag), produces one layer that cannot share bytes with other images and cannot be downloaded in parallel, and can double local storage. Docker's docs recommend multi-stage builds instead, plus cache mounts and same-RUN cleanup. See Image size.
12 — Two builds of the same commit produce different digests. Name three causes and the fix for each. Good to know
Answer
Answer: Timestamps in the config, history and files (fix: SOURCE_DATE_EPOCH plus rewrite-timestamp=true); a moving base tag (fix: FROM name:tag@sha256:...); and package managers installing whatever is current (fix: pinned versions and snapshot mirrors). For Go add -trimpath and stamp versions explicitly with -ldflags -X. See Reproducible builds.
13 — A Compose stack marks the distroless Go container unhealthy forever although the service works. What is the likely HEALTHCHECK, and what is the fix? Must-know
Answer
Answer: A shell-form check such as HEALTHCHECK CMD curl -f http://localhost:8080/healthz: distroless has neither /bin/sh nor curl, so every check fails. Use the exec form and make the binary probe itself (HEALTHCHECK CMD ["/orders-api","healthcheck"]), keeping the probe local (no database) and the exit codes 0/1. See HEALTHCHECK.
Glossary
| Term | Meaning |
|---|---|
| OCI image spec | Open Container Initiative standard for image index, manifest, config and layers (v1.1, 2024) |
| Image index / manifest list | JSON listing one manifest per platform (plus attestation manifests) under one digest |
| Image manifest | JSON pointing to one config blob and an ordered list of layer blobs |
| Config (image config) | JSON with runtime defaults (Env, Entrypoint, Cmd, User), rootfs.diff_ids and history |
| Layers | Tar changesets stacked in order; base at index 0 |
| DiffID / ChainID | Digest of an uncompressed layer / compound digest identifying a stack of layers |
| Digest | sha256:<hex> of content; immutable identity of a blob, manifest or index |
| Union filesystem | Several directories presented as one merged tree |
| OverlayFS | Linux union filesystem used by Docker's overlay2 and containerd snapshotters (lowerdir, upperdir, merged) |
| Copy-on-write | A file is copied into the writable layer the first time it is modified (OverlayFS copy_up, whole file) |
| Whiteout | .wh.<name> entry in a layer marking a path as deleted; hides, does not free |
| Build context | The files sent to the builder; the only files COPY can read |
| .dockerignore | Pattern file excluding paths from the build context; last matching line wins, ! re-includes |
| Dockerfile instructions | FROM, RUN, COPY, ADD, WORKDIR, ENV, ARG, EXPOSE, LABEL, USER, HEALTHCHECK, ENTRYPOINT, CMD, STOPSIGNAL, SHELL, VOLUME, ONBUILD |
| FROM | Starts a stage from a base image (tag and/or digest, optional --platform, AS name) |
| RUN | Executes a command at build time and commits a layer; supports --mount |
| COPY vs ADD | COPY copies local/stage files; ADD also fetches URLs and Git repos and extracts local tars |
| WORKDIR | Sets (and creates) the working directory for later instructions |
| ENV vs ARG | ENV persists into containers; ARG is build-time only but recorded in history/provenance |
| EXPOSE | Documents listening ports; does not publish |
| LABEL | Image metadata; use org.opencontainers.image.* keys |
| USER and non-root | Default user/group for later steps and the container; use a numeric non-zero UID |
| HEALTHCHECK | Docker's in-container probe; exit 0 healthy, 1 unhealthy |
| ENTRYPOINT vs CMD | The executable vs its default arguments (CMD alone is the whole default command) |
| Exec form vs shell form | JSON array run directly vs string run under /bin/sh -c |
| PID 1 and signals | The first process in the namespace; no default signal actions, must reap children |
| tini | Minimal init that forwards signals and reaps zombies; Docker's --init uses it as docker-init |
| STOPSIGNAL | Signal docker stop sends (default SIGTERM; php-fpm images use SIGQUIT) |
| Layer caching | Reusing a step's previous result when the instruction and inputs match |
| Cache invalidation order | First miss invalidates all later steps in the stage; order instructions by change frequency |
| BuildKit | Docker's build engine: LLB graph, concurrency, mounts, attestations; default builder |
| buildx | Docker CLI plugin driving BuildKit (drivers, --platform, --push, --cache-to, bake) |
| LLB / frontend | BuildKit's content-addressed build graph / the parser that turns a Dockerfile into it |
| Cache mounts (--mount=type=cache) | Persistent build-time directory shared across builds, never in the image |
| Secret mounts | --mount=type=secret: a secret visible to one RUN only, not cached, not in provenance |
| SSH mount | --mount=type=ssh: forwards the SSH agent for private Git access |
| Multi-stage builds | Several FROM stages in one Dockerfile; later stages copy artefacts from earlier ones |
| Builder pattern | Pre-17.05 two-Dockerfile workflow (build image, extract artefact) replaced by multi-stage |
| scratch | The empty base image |
| distroless | Google's minimal images without shell or package manager (static, base, cc, language runtimes; :nonroot, :debug) |
| Static Go binary | A Go executable with no dynamic libc dependency, built with CGO_ENABLED=0 |
| CGO_ENABLED=0 | Disables cgo; pure-Go net and os/user, static output |
| alpine vs debian-slim vs distroless | musl + BusyBox + apk vs glibc + apt vs no shell and no package manager |
| musl | The C library used by Alpine; differs from glibc in DNS, locale and ABI details |
| Image size | Sum of all layer blobs (compressed on the registry, uncompressed on disk) |
| Image squashing myths | The belief that --squash is the right size fix; it is experimental, legacy and loses layer sharing |
| dive | Tool that browses layers and scores wasted space; CI=true gives pass/fail |
| Reproducible builds | Same source gives the same bytes and digest |
| SOURCE_DATE_EPOCH | Standard variable (seconds since 1970) that build tools use instead of "now" |
| Multi-arch / platforms | One image name for several os/arch[/variant] targets |
| QEMU emulation | Running foreign-architecture binaries through binfmt_misc user-mode emulation during builds |
| Cross-compilation | Compiling for the target platform on the build platform ($BUILDPLATFORM to $TARGETPLATFORM) |
| Tagging strategy | The set of tags pushed per build (semver, commit, branch) and which one is deployed |
| latest | The default tag name; mutable and unordered |
| Semantic tags | 1.4.2, 1.4, 1 for one build; the shorter ones move forward |
| Immutable tags | Registry setting that rejects pushing an existing tag (ECR ImageTagAlreadyExistsException) |
| Registries | Servers implementing the OCI distribution spec: Docker Hub, GHCR, ECR, GitLab, Harbor, Artifactory |
| Docker Hub | Docker's public registry; pull rate limits per 6 hours by account type |
| GHCR | GitHub Container Registry, ghcr.io, authenticated with GITHUB_TOKEN in Actions |
| ECR | Amazon Elastic Container Registry; IAM auth, tag immutability, lifecycle policies |
| Private registry | A registry you run or rent (Harbor, registry:2, Artifactory), often as a pull-through cache |
| push/pull | Upload missing blobs then the manifest / fetch manifest then missing blobs |
| Rate limits | Docker Hub: 100 anonymous pulls per IPv4 or IPv6 /64 per 6 h, 200 for Personal; HTTP 429 |
| Referrers | OCI 1.1 artefacts whose subject points to another manifest (signatures, SBOMs) |
| Image signing (cosign) | Sigstore tool signing image digests with keys, KMS or keyless OIDC (Fulcio + Rekor) |
| SBOM | Software Bill of Materials; BuildKit emits SPDX JSON with --sbom=true |
| Provenance attestations | SLSA-format record of how an image was built; BuildKit adds mode=min by default |
| Vulnerability scanning (Trivy, Grype, Docker Scout) | Matching image packages against advisories; gate with severity and exit codes |
| hadolint | Dockerfile linter (DL rules) using ShellCheck for RUN scripts |
| Build checks | docker build --check rules such as JSONArgsRecommended; # check=error=true fails builds |
| php-fpm images | Official php:*-fpm images: FastCGI on 9000, STOPSIGNAL SIGQUIT, www-data pools |
| Composer in multi-stage | Composer binary copied from composer:2, lock files first, --no-dev, authoritative classmap |
| opcache | PHP bytecode cache; enabled in official images; validate_timestamps=0 for immutable code |
| FrankenPHP | PHP application server written in Go on Caddy; classic and worker modes; dunglas/frankenphp images |
| Octane | Laravel package that boots the app once and serves requests from memory (FrankenPHP, Swoole, RoadRunner) |
| Nginx sidecar vs single container | Nginx + php-fpm as two containers (or one pod) vs one FrankenPHP container |
References
- Open Container Initiative, Image Format Specification: https://github.com/opencontainers/image-spec/blob/main/spec.md — manifest: https://github.com/opencontainers/image-spec/blob/main/manifest.md — config: https://github.com/opencontainers/image-spec/blob/main/config.md — layers: https://github.com/opencontainers/image-spec/blob/main/layer.md — index: https://github.com/opencontainers/image-spec/blob/main/image-index.md — annotations: https://github.com/opencontainers/image-spec/blob/main/annotations.md
- OCI Distribution Specification: https://github.com/opencontainers/distribution-spec/blob/main/spec.md — releases: https://github.com/opencontainers/image-spec/releases
- OCI overview: https://opencontainers.org/about/overview/
- Dockerfile reference: https://docs.docker.com/reference/dockerfile/
- Docker build: context and .dockerignore https://docs.docker.com/build/concepts/context/ — cache https://docs.docker.com/build/cache/ — invalidation https://docs.docker.com/build/cache/invalidation/ — optimize https://docs.docker.com/build/cache/optimize/ — backends https://docs.docker.com/build/cache/backends/
- Docker build: multi-stage https://docs.docker.com/build/building/multi-stage/ — best practices https://docs.docker.com/build/building/best-practices/ — multi-platform https://docs.docker.com/build/building/multi-platform/ — secrets https://docs.docker.com/build/building/secrets/ — BuildKit https://docs.docker.com/build/buildkit/ — build checks https://docs.docker.com/build/checks/ — exporters https://docs.docker.com/build/exporters/
- Docker attestations: https://docs.docker.com/build/metadata/attestations/ — SBOM https://docs.docker.com/build/metadata/attestations/sbom/ — provenance https://docs.docker.com/build/metadata/attestations/slsa-provenance/ — storage https://docs.docker.com/build/metadata/attestations/attestation-storage/ — reproducible builds in GitHub Actions https://docs.docker.com/build/ci/github-actions/reproducible-builds/
- Docker CLI:
buildx buildhttps://docs.docker.com/reference/cli/docker/buildx/build/ —imagetools inspecthttps://docs.docker.com/reference/cli/docker/buildx/imagetools/inspect/ —image build(legacy,--squash) https://docs.docker.com/reference/cli/docker/image/build/ —image historyhttps://docs.docker.com/reference/cli/docker/image/history/ —container run(--init) https://docs.docker.com/reference/cli/docker/container/run/ —container stophttps://docs.docker.com/reference/cli/docker/container/stop/ - Docker storage: drivers and copy-on-write https://docs.docker.com/engine/storage/drivers/ — OverlayFS https://docs.docker.com/engine/storage/drivers/overlayfs-driver/
- Docker Engine release notes 23.0 https://docs.docker.com/engine/release-notes/23.0/ and 29 https://docs.docker.com/engine/release-notes/29/
- Docker Hub usage and limits: https://docs.docker.com/docker-hub/usage/ — pulls: https://docs.docker.com/docker-hub/usage/pulls/ — Docker Scout: https://docs.docker.com/scout/
- Official image docs: golang https://github.com/docker-library/docs/tree/master/golang — php https://github.com/docker-library/docs/tree/master/php — alpine https://github.com/docker-library/docs/tree/master/alpine — composer https://github.com/docker-library/docs/tree/master/composer — php 8.4 fpm Dockerfile https://github.com/docker-library/php/blob/master/8.4/trixie/fpm/Dockerfile
- Distroless: https://github.com/GoogleContainerTools/distroless — base/static contents https://github.com/GoogleContainerTools/distroless/blob/main/base/README.md
- Go: cgo https://go.dev/src/cmd/cgo/doc.go — go command https://go.dev/src/cmd/go/alldocs.go — linker flags https://go.dev/src/cmd/link/doc.go
- tini: https://github.com/krallin/tini — dive: https://github.com/wagoodman/dive — hadolint: https://github.com/hadolint/hadolint and rule pages https://github.com/hadolint/hadolint/wiki/DL3007, https://github.com/hadolint/hadolint/wiki/DL3008, https://github.com/hadolint/hadolint/wiki/DL3002, https://github.com/hadolint/hadolint/wiki/DL3020, https://github.com/hadolint/hadolint/wiki/DL4006
- Sigstore cosign: signing https://docs.sigstore.dev/cosign/signing/signing_with_containers/ — verifying https://docs.sigstore.dev/cosign/verifying/verify/ — cosign-installer https://github.com/sigstore/cosign-installer
- SLSA provenance v1.0: https://slsa.dev/spec/v1.0/provenance — reproducible-builds.org SOURCE_DATE_EPOCH: https://reproducible-builds.org/docs/source-date-epoch/
- Trivy: container images https://trivy.dev/latest/docs/target/container_image/ — filtering https://trivy.dev/latest/docs/configuration/filtering/ — exit codes https://trivy.dev/latest/docs/configuration/others/ — trivy-action https://github.com/aquasecurity/trivy-action — Grype: https://github.com/anchore/grype
- GitHub Actions: build-push-action https://github.com/docker/build-push-action — metadata-action https://github.com/docker/metadata-action — checkout https://github.com/actions/checkout — GHCR https://docs.github.com/en/packages/working-with-a-github-packages-registry/working-with-the-container-registry
- Amazon ECR: pushing https://docs.aws.amazon.com/AmazonECR/latest/userguide/docker-push-ecr-image.html — tag immutability https://docs.aws.amazon.com/AmazonECR/latest/userguide/image-tag-mutability.html
- Kubernetes images and pull policy: https://kubernetes.io/docs/concepts/containers/images/ — pod termination: https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle/
- Laravel 13: deployment https://laravel.com/docs/13.x/deployment — Octane https://laravel.com/docs/13.x/octane
- FrankenPHP: Docker https://frankenphp.dev/docs/docker/ — Laravel https://frankenphp.dev/docs/laravel/
- PHP: OPcache configuration https://www.php.net/manual/en/opcache.configuration.php — FPM non-root notice in
fpm_unix.chttps://github.com/php/php-src/blob/master/sapi/fpm/fpm/fpm_unix.c — Composer CLI https://getcomposer.org/doc/03-cli.md