Skip to content

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 forGo to
The whole page in three tablesEverything in one minute
Why images are layered and content-addressedWhy it exists
OCI 2015, image-spec 1.0 and 1.1, BuildKit default, containerd image storeWhere it comes from
Index, manifest, config, layers, digests, media typesOCI image spec
Union filesystem, OverlayFS, copy-on-write, whiteoutsLayers
What gets sent to the builder; .dockerignore rulesBuild context
FROM, RUN, COPY vs ADD, WORKDIR, ENV vs ARG, EXPOSE, LABELDockerfile instructions
ENTRYPOINT vs CMD, exec form vs shell form, PID 1, tini, STOPSIGNALENTRYPOINT, CMD and signals
USER, numeric UIDs, runAsNonRootUSER and non-root
HEALTHCHECK options and exit codesHEALTHCHECK
Why a one-line change rebuilds everythingLayer caching
BuildKit, buildx, cache/bind/secret/SSH mounts, cache backendsBuildKit and mounts
Builder pattern, COPY --from, --targetMulti-stage builds
scratch, distroless, alpine (musl), debian-slim, static GoBase images
Image size, docker history, dive, --squashImage size and squashing myths
SOURCE_DATE_EPOCH, rewrite-timestampReproducible builds
--platform, manifest list, QEMU, cross-compilation, native nodesMulti-arch
latest, semantic tags, immutable tags, digestsTagging strategy
Docker Hub limits, GHCR, ECR, private registries, mirrorsRegistries
SBOM, provenance, cosign, referrersSupply-chain artefacts
hadolint, build checks, Trivy, Grype, Docker ScoutLinting and scanning
php-fpm images, Composer, OPcache, FrankenPHP, Octane, NginxPHP images
Build graph, cache keys, manifest JSON, knobs, error messagesMechanics
CodeGo, Laravel
Eleven classic problems and their fixesSolving the classic problems
Which base, which tags, which registry, which PHP modelChoosing
From one VM to many clustersIn architecture
Commands with expected outputLab
Wrong beliefs, summary, quiz, termsMisconceptions, Cheat sheet, Self-check, Glossary

Everything in one minute ​

What an image is made of (OCI image spec v1.1).

PartMedia typeWhat it holdsIdentified by
Image index (manifest list)application/vnd.oci.image.index.v1+jsonOne entry per platform (linux/amd64, linux/arm64...) plus optional attestation manifestsDigest of the index JSON
Image manifestapplication/vnd.oci.image.manifest.v1+jsonOne config descriptor and an ordered list of layer descriptorsDigest of the manifest JSON
Configapplication/vnd.oci.image.config.v1+jsonEnv, Entrypoint, Cmd, User, WorkingDir, ExposedPorts, Labels, rootfs.diff_ids, historyDigest (this is the "image ID")
Layerapplication/vnd.oci.image.layer.v1.tar+gzip (or +zstd, or plain tar)A filesystem changeset: added/changed files and whiteouts for deletionsDigest of the (compressed) blob; DiffID = digest of the uncompressed tar
Tag(registry name)A human, movable pointer to one manifest or index digestname:tag, at most 128 characters
Referrerany manifest with a subject fieldA signature, SBOM or scan attached to another digestListed by GET /v2/<name>/referrers/<digest>

The Dockerfile in one table.

InstructionCreates a layer?Plain wordsTrap
FROMUses the base's layers"Start from this image"latest moves; pin a tag and a digest
RUNYesRun a command at build timeCache key is the command string, not what it downloads
COPYYesCopy files from the context or another stageCOPY . . early kills the cache
ADDYesCOPY plus URLs, Git repos, auto-extracting local tarsUse COPY unless you need those; use --checksum for URLs
WORKDIRMetadata (creates the dir)cd for the rest of the stageRelative COPY without WORKDIR (hadolint DL3045)
ENVMetadataEnvironment for build steps and the containerPersists; never for secrets
ARGMetadataBuild-time variable, not in the final containerVisible in docker history and max provenance
EXPOSEMetadataDocuments the portDoes not publish it
LABELMetadataorg.opencontainers.image.* annotationsMissing source breaks GHCR repo linking
USERMetadataDefault user for later RUN and the containerName without UID defeats runAsNonRoot checks
HEALTHCHECKMetadataDocker probes the containerShell form needs a shell; distroless has none
ENTRYPOINT / CMDMetadataThe program and its default argumentsShell form: the app is not PID 1 and may miss SIGTERM
STOPSIGNALMetadataSignal sent by docker stopphp-fpm uses SIGQUIT for a graceful stop

Base images in one table (sizes as the projects themselves state them).

BaselibcShell / package managerSize stated by the projectFits
scratchnonenone / noneemptyFully static binaries that need no CA certs, tzdata or /etc/passwd (or that embed them)
gcr.io/distroless/static-debian13nonenone / none"around 2 MiB"Static Go (CGO_ENABLED=0); includes ca-certificates, tzdata, /etc/passwd, /tmp
gcr.io/distroless/base-debian13glibcnone / nonenot statedcgo Go, Rust, anything needing glibc and libssl
alpine:3.23muslBusyBox sh / apk"5 MB"; Docker's guide says "under 6 MB"Small images that still need a shell; watch musl differences
debian:trixie-slimglibcsh / aptnot stated (full debian: 124 MiB per the distroless README)Most compatible; php-fpm images are built on it
What a registry stores for ghcr.io/acme/orders-api:1.4.2tag 1.4.2mutable pointer (a name)image index (manifest list)sha256:9f1c... immutableimage.index.v1+jsonmanifest linux/amd64image.manifest.v1+jsonconfig + layers[0..n]manifest linux/arm64same app, other CPUconfig + layers[0..n]attestation manifestplatform unknown/unknownin-toto SBOM + provenanceconfig blobEnv, Entrypoint, User,rootfs.diff_ids, historylayer blobs (tar+gzip/zstd)base at index 0, then instack order; shared by digestreferrers (OCI 1.1 subject field)cosign signature, extra SBOM, scan report:artifacts whose subject = a manifest digest;GET /v2/name/referrers/digest lists themPull by tag: tag to index, client picks its platform, fetches config and layers it lacks.Pull by digest (name@sha256:...): the same bytes forever. Deploy digests, read tags.Docker Hub rate limits: a normal pull counts once; a multi-arch pull counts once per architecture pulled.

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 choiceRicher choiceWhat you buyWhat you pay
One big RUN doing everythingMany small, ordered stepsCache hits on unchanged stepsMore layers to reason about
Single-stage image (toolchain inside)Multi-stage (toolchain discarded)Small, low-CVE runtime imageA slightly longer Dockerfile
debian basedistroless or scratchFewer packages, fewer scanner findingsNo shell for debugging (use :debug images or ephemeral containers)
Tags onlyTags for humans, digests for deploysReproducible rollouts and rollbacksTooling must resolve and record digests
Native single-arch buildMulti-arch indexOne name for x86-64 and ARM hostsCross-compilation or emulation in CI
Push and hopeSBOM + provenance + signatureVerifiable origin, policy gatesKey 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 ​

  1. "RUN rm -rf /tmp/build makes my image smaller." Only if the files were created in the same RUN. Files from an earlier layer are hidden by a whiteout, not removed; every pull still downloads them. See Layers.
  2. "A tag identifies an image." A tag is a mutable pointer. The official images' latest, FrankenPHP's 1-php8.6 and your own 1.4 move when someone pushes; only a digest (name@sha256:...) names fixed bytes. See Tagging strategy.
  3. "EXPOSE 8080 opens 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 is docker run -p or a Kubernetes Service.

Where it comes from ​

WhenWhat happenedSource
22 June 2015The Open Container Initiative is launched "by Docker, CoreOS and other leaders in the container industry" under the Linux Foundationopencontainers.org overview
Docker 17.05Multi-stage builds arrive ("Docker 17.05 introduced multi-stage builds, simplifying this enormously", in the Composer image docs)docker-library composer docs
19 July 2017OCI image-spec v1.0.0: manifest, index, config, layers become a vendor-neutral standardGitHub releases of opencontainers/image-spec
17 Nov 2021distribution-spec v1.0.1 and image-spec v1.0.2GitHub releases
1 Feb 2023Docker Engine 23.0: "Set Buildx and BuildKit as the default builder on Linux"Engine 23.0 release notes
Dockerfile 1.5 / BuildKit 0.11SOURCE_DATE_EPOCH is honoured for image and layer timestampsDockerfile reference, built-in build args
15 Feb 2024image-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.0HEALTHCHECK --start-intervalDockerfile reference
10 Nov 2025Docker Engine 29.0; fresh installs use the containerd image store by default, which can hold multi-platform images and attestationsEngine 29 release notes, storage driver docs
2025-2026image-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.

text
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, done

Real 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-pushed 1.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:18 and gets the linux/arm64 manifest from the same tag a CI x86 runner uses.
ProductHow 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 / nerdctlNative OCI content store and snapshotters; Kubernetes nodes use it through CRI
KubernetesPulls through the node's runtime; image: name@sha256:... "pins the code that you run"
GHCR, ECR, Docker Hub, Harbor, GitLab container registrySpeak the OCI distribution spec; OCI 1.1 referrers support varies (cosign falls back to a tag schema)
docker buildx imagetools inspect / crane / orasRead 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".

One image, many containers: layers are shared, read-only, and only ever addedmerged/ (what the process sees as /)union of everything below; upper wins on conflictscontainer layer = upperdir (read-write)gone when the container is removedL4 RUN rm /tmp/big.tar (whiteout .wh.big.tar)L3 RUN curl -o /tmp/big.tar ... (say, +300 MB)L2 COPY app /appL1 FROM debian:trixie-slim (base layers)L1 to L4 = lowerdir stack, read-only, content-addressedby digest, shared by every image and container that uses themcopy-on-write (OverlayFS copy_up)first write to /app/config.yml copies the WHOLEfile up from lowerdir, then modifies the copydeleting in a later layer hides, never freesL3 still ships its bytes in every pull; L4 only addsa whiteout entry. Fix: download, use and delete inONE RUN, or do it in a build stage you discard.identitymanifest lists compressed layer digests;config lists uncompressed DiffIDs (rootfs.diff_ids)
text
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 layer

Real 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/storage pays the copy-up cost on the first write of each file; the files survive docker restart but 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.
StorageBehaviour
Docker overlay2 (classic store)lowerdir per layer, upperdir per container, merged mount
Docker 29+ / containerd image storeSame OverlayFS idea through containerd snapshotters (overlayfs snapshotter)
Kubernetes nodes (containerd, CRI-O)Overlay snapshotters; container layer is ephemeral storage counted against the pod
Podman / Buildahoverlay 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".

text
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.

ToolContext 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 bakePer-target context and named contexts (contexts = { src = "..." })
GitHub Actions build-push-actionUses 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. ARG before the first FROM is in the global scope and can parameterise FROM (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 COPY for local files (hadolint DL3020: "Use COPY instead of ADD for files and folders"); use ADD --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-RUN or as ARG.
  • EXPOSE documents ports, default TCP (EXPOSE 8080/tcp, EXPOSE 53/udp); -P publishes 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). MAINTAINER is deprecated in favour of LABEL 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.
text
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 exists

Real 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").

FeatureDockerfile 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 --link1.4Layer independent of earlier layers; rebase without rebuild
ADD --checksum1.6sha256 for HTTP, commit SHA for Git
RUN --mount=type=secret,env=1.10Secret as an environment variable
COPY --exclude / --parents1.19 / 1.20Filters and parent-directory preservation
Build checks (docker build --check, # check=error=true)BuildKit with the Dockerfile frontendDocker 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.

text
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
ENTRYPOINTCMDdocker run img runsdocker run img x runs
none["app","serve"]app servex
["app"]["serve"]app serveapp x
["app"]noneappapp 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 serveapp 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.

RuntimeWhat it sends on stopGrace period knob
DockerSTOPSIGNAL (default SIGTERM), then SIGKILLdocker stop -t, --stop-timeout, --stop-signal
KubernetesSIGTERM (or the image STOPSIGNAL where supported), then SIGKILLterminationGracePeriodSeconds, preStop hook
Docker ComposeSame as Dockerstop_grace_period, stop_signal
php-fpm official imageSTOPSIGNAL 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.

text
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 Service

Real 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).

ImageDefault userNon-root option
gcr.io/distroless/*root (latest):nonroot tag, UID 65532
php:*-fpmmaster as root, pool workers as www-data--user www-data / USER www-data (documented for FPM variants)
nginx:*master as rootnginxinc/nginx-unprivileged images, or listen on > 1024
golang, node, alpine, debianrootuseradd/adduser -D then USER
dunglas/frankenphprootuseradd + 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.

text
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 it

Real 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.

RuntimeUses image HEALTHCHECK?
Docker Engine / Compose / SwarmYes
KubernetesNo (probes in the pod spec)
AWS ECSTask-definition healthCheck; it maps to Docker's HEALTHCHECK and overrides the image's ("override any Docker health checks that exist in the container image")
PodmanYes (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, COPY and RUN --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 ARG causes 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."
  • WORKDIR respects SOURCE_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>.
You edit main.go and rebuild. Which steps run again?Order A: context first (slow)Order B: manifests first (fast)FROM golang:1.27-trixie CACHEDCOPY . . checksum changedRUN go mod download re-runsRUN go build re-runsFROM golang:1.27-trixie CACHEDCOPY go.mod go.sum ./ CACHEDRUN go mod download CACHEDCOPY . . checksum changedRUN --mount=type=cache go build re-runs, warmRules (Docker build cache invalidation docs):1. Once one step misses, every later step in that stage misses too.2. COPY/ADD compare file metadata checksums (not mtime); RUN compares only the command string.3. An ARG misses on first use, not on definition. Secret values never invalidate the cache.4. A cache mount survives a miss: the compiler still finds its old objects in /root/.cache/go-build.

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).

text
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).

BuilderLocal cacheExternal cache
BuildKit (docker driver)Always oninline, local, registry, gha "only if you have enabled the containerd image store"
BuildKit (docker-container, kubernetes, remote drivers)Per builderinline, registry, local, gha, s3 (experimental), azblob (experimental)
GitHub Actionsnone between runstype=gha or type=registry,ref=...:buildcache
GitLab CInone 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:

MountExamplePersists?Use for
type=cache--mount=type=cache,target=/root/.cache/go-buildAcross builds on that builder, never in the imageGo build cache, /go/pkg/mod, Composer, npm, apt
type=bind--mount=type=bind,source=go.sum,target=go.sumNo ("read-only by default"; writes discarded)Files needed by one step only
type=secret--mount=type=secret,id=composer_auth,env=COMPOSER_AUTHNoTokens, auth.json, cloud credentials
type=ssh--mount=type=ssh + docker build --ssh defaultNogit clone of private repos
type=tmpfs--mount=type=tmpfs,target=/tmpNoScratch 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).

text
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).

ToolNotes
docker buildBuildKit through the docker driver; output loaded into the local image store
docker buildx buildSame, plus drivers (docker-container, kubernetes, remote, Docker Build Cloud), --platform, --push, --cache-to, --attest
docker buildx bakeDeclarative multi-target builds (HCL/JSON/Compose files)
Kaniko, Buildah, koBuild 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.

Multi-stage: build with everything, ship almost nothingstage "build"FROM --platform=$BUILDPLATFORM golang:1.27-trixieGo toolchain, gcc, git, apt, a shellCOPY go.mod; go mod downloadCOPY . . (source code)CGO_ENABLED=0 GOOS=$TARGETOSGOARCH=$TARGETARCH go buildcache mounts: /go/pkg/mod, /root/.cache/go-build(kept by BuildKit, never in any image)stage "test" (FROM build)go vet ./... and go test ./...built only with --target test (unused stages are skipped)COPY --from=build/out/orders-apistage "runtime" = the shipped imageFROM gcr.io/distroless/static-debian13:nonrootca-certificates, tzdata, /etc/passwd, /tmpno shell, no package manager/orders-api (static, stripped)USER 65532:65532HEALTHCHECK CMD ["/orders-api","healthcheck"]ENTRYPOINT ["/orders-api"] (PID 1)one image index: linux/amd64 + linux/arm64left behind on purposecompiler, source, module cache, .git,build secrets, test binaries
text
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.

LanguageBuild stageRuntime stage
Go (cgo off)golang:1.27-trixiedistroless/static-debian13:nonroot or scratch
Go (cgo on)golang:1.27-trixiedistroless/base-debian13 (glibc)
PHP/Laravelphp:8.4-fpm-trixie + Composer, node:22-alpine for assetsphp:8.4-fpm-trixie with vendor + nginx:1.28-alpine with public/
JavaJDK imagedistroless/java21-debian13
Nodenode with dev depsnode 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". static contains ca-certificates, "A /etc/passwd entry for a root user", "A /tmp directory" and tzdata; base adds glibc and libssl; cc adds 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 official php:*-fpm images.
  • 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=0 explicitly so net and os/user use 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".
text
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 debug

Real 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.

Needscratchdistroless staticdistroless basealpinedebian-slim
Static Go, no TLSYesYesOverkillOverkillOverkill
Static Go, HTTPS + time zonesAdd certs + tzdataYesOverkillYesYes
cgo / glibc binariesNoNoYesRisky (musl)Yes
Shell for docker execNo:debug only:debug onlyYesYes
Package manager in imageNoNoNoapkapt
PHP-FPMNoNoNophp:*-fpm-alpinephp:*-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.

text
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 returns

Real 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.

TechniqueEffectCost
Multi-stageToolchains and caches never shipNone worth naming
Cache mounts instead of caches in layersPackage caches never shipNeeds BuildKit
One RUN for download + use + deleteNo hidden bytesLonger RUN lines
--no-install-recommends, apk add --no-cacheFewer packagesYou list dependencies yourself
Smaller base (distroless/static)Smallest runtimeNo shell
-ldflags "-s -w", -trimpath (Go)Smaller, path-free binaryNo symbols for debuggers
--squash (legacy, experimental)One layerNo 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".

text
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 signed

Real 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-determinismFix
Timestamps in config and filesSOURCE_DATE_EPOCH + rewrite-timestamp=true
Moving base tagsFROM image:tag@sha256:...
Package mirrorsPinned 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 commitDocker 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:

  1. 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/binfmt and binfmt_misc.
  2. Multiple native nodes: docker buildx create --append with an amd64 and an arm64 node (or Docker Build Cloud).
  3. Cross-compilation: FROM --platform=$BUILDPLATFORM for the build stage, then use TARGETOS/TARGETARCH. These automatic args "are defined in the global scope so are not automatically available inside build stages": redeclare them with ARG 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".

text
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 tag

Real 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.

StrategyDockerfile changesSpeedGood for
QEMUNoneSlowest for compilationInterpreted stacks, quick starts, small RUNs
Native nodes / Build CloudNoneNativePHP/Python/Node images that compile extensions
Cross-compile (Go, Rust)--platform=$BUILDPLATFORM, TARGET* argsNativeGo 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".

text
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 now

Real 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 kindMoves?Use for
latestYes, every pushLocal experiments only
1, 1.4 (major/minor)YesHumans who want patches automatically
1.4.2 (full semver)Should not (enforce with immutable tags)Release identity
sha-<commit>NoTraceability from image to commit
main, pr-123YesPreview environments
@sha256:... digestNeverDeployments, 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:

RegistryName formatAuth from CINotable
Docker Hubdocker.io/library/nginx, docker.io/<user>/<repo>Personal access tokenPull rate limits above; official images live under library/
GHCR (GitHub Container Registry)ghcr.io/<owner>/<image>GITHUB_TOKEN with packages: writeLink 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 roleTag immutability, lifecycle policies, scanning, pull-through cache
Google Artifact Registry / Azure ACR<region>-docker.pkg.dev/..., <name>.azurecr.io/...Workload identity / OIDCSame OCI API
GitLab container registryregistry.gitlab.com/<group>/<project>CI_JOB_TOKENBuilt into GitLab CI
Harbor, Artifactory, Nexus, registry:2 / distributionyour domainRobot accountsPrivate registry, proxy cache (mirror), replication
text
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 it

Real 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.

text
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 rescanning

Real 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.

ArtefactDocker / BuildKitGitHubSigstore
SBOM--sbom=true (SPDX via BuildKit's scanner)build-push-action sbom: truecosign attest --type spdxjson
Provenance--provenance=mode=min (default) / mode=maxprovenance: mode=max; artifact attestationscosign attest --type slsaprovenance
Signaturen/a (use cosign or Notation)OIDC token (id-token: write)cosign sign, cosign verify
StorageAttestation manifests in the indexRegistry referrersOCI 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 RUN scripts. 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 as JSONArgsRecommended and exits non-zero on violations; # check=error=true makes 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:., or grype sbom:./sbom.json to 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.
text
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)
ToolInputTypical CI use
hadolintDockerfilePre-build lint, docker run --rm -i hadolint/hadolint < Dockerfile
Docker build checksDockerfiledocker build --check .
TrivyImage, filesystem, repo, SBOMaquasecurity/trivy-action with exit-code: "1"
Grype (+ Syft)Image, directory, SBOMgrype sbom: on the SBOM the build produced
Docker ScoutImage (Docker Hub, local)Docker Hub / Desktop dashboards, CLI
diveImage layersSize/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, on debian:trixie-slim): CMD ["php-fpm"], EXPOSE 9000, STOPSIGNAL SIGQUIT, pools run as www-data; zz-docker.conf sets daemonize = no and "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 via docker-php-ext-install, docker-php-ext-enable, pecl install (pin versions), or the install-php-extensions project.
  • 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_consumption 128, interned_strings_buffer 8, max_accelerated_files 10000, revalidate_freq 2.
  • 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, then composer 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> with trixie, bookworm or alpine; worker mode via FRANKENPHP_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-requests recycles 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 + supervisord image, which breaks the one-process-per-container rule Docker's best practices recommend: "Each container should have only one concern").
text
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
ModelContainersProsCons
Nginx + php-fpm (sidecar or separate service)2Standard, each image does one thing, Nginx serves static filesTwo images to version together; public/ copied into both
FrankenPHP (classic mode)1One image, HTTP/2/3, automatic HTTPS (Caddy)Newer; ops teams know Nginx better
FrankenPHP + Octane (worker mode)1App booted once: far less per-request workShared state between requests; memory leaks need --max-requests
Apache + mod_php (php:*-apache)1SimplestProcess-per-request model; less common for Laravel at scale
Nginx + php-fpm + supervisord in one image1One artefactSeveral 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.

text
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 layer

A 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 ​

InstructionWhat is comparedChanges that cause a miss
FROMResolved base digestNew base digest (only re-resolved with --pull or when not local)
RUNCommand string + parent + build args in use + mount specsText 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=bindLike COPY for the bound filesBound file change
RUN --mount=type=secretSecret id and target, never the valueId or path change
WORKDIRPath + SOURCE_DATE_EPOCHEpoch change
ENV, LABEL, USER, EXPOSEInstruction textValue 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):

json
{
  "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:

bash
# 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:dev

Attestation 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 ​

KnobWhereDefaultNotes
HEALTHCHECK --interval / --timeout / --start-period / --start-interval / --retriesDockerfile30s / 30s / 0s / 5s / 3--start-interval needs Engine 25.0+
STOPSIGNALDockerfileSIGTERMdocker run --stop-signal overrides
--mount=type=cache,sharing=Dockerfilesharedlocked for apt; private for exclusive copies
--mount=type=secret,mode=Dockerfile0400, uid 0env= since Dockerfile 1.10
--cache-to ...,mode=buildxminmax caches intermediate stages too
--provenance=mode=buildxmin (on by default)max includes build-arg values
--sbombuildxoffSPDX JSON in-toto attestation
BUILDX_NO_DEFAULT_ATTESTATIONSenvunsetDisables default provenance
compression= / compression-level=--output type=imagegzipzstd 0-22, gzip/estargz 0-9
rewrite-timestamp=--output type=imagefalseApply SOURCE_DATE_EPOCH to file mtimes
SOURCE_DATE_EPOCHbuild arg / envunsetDockerfile 1.5, BuildKit 0.11
--platformbuildxbuilder's platformComma list for multi-arch
opcache.validate_timestampsphp.ini10 in immutable images
opcache.memory_consumption / max_accelerated_filesphp.ini128 / 10000Raise for big apps (classmap size)
Docker Hub pulls per 6 hregistry100 anonymous per IP, 200 PersonalPro/Team/Business unlimited (fair use)
Tag lengthregistrymax 128 chars[a-zA-Z0-9_][a-zA-Z0-9._-]{0,127}

Error messages you will actually see ​

MessageMeaningFix
You have reached your pull rate limit. You may increase the limit by authenticating and upgrading (HTTP 429)Docker Hub pull limitdocker login in CI, mirror base images
429 Too Many Requests (short body)Docker Hub abuse limitSlow 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 attestationsEnable the containerd image store or use docker-container driver
ImageTagAlreadyExistsExceptionECR immutable tagsNew tag per build (that is the point)
E: Package 'php-XXX' has no installation candidateThe php image blocks Debian's PHP packagesUse docker-php-ext-install/pecl, not apt install php-*
Lint Rule 'JSONArgsRecommended': JSON arguments recommended for CMD to prevent unintended behavior related to OS signalsBuild check on shell-form CMDExec form
x509: certificate signed by unknown authority (Go on scratch)No CA bundle in the imagedistroless/static, or COPY /etc/ssl/certs/ca-certificates.crt
container ... is unhealthy / Compose dependency failed to startHEALTHCHECK 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-dataExpected; 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):

dockerfile
# 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-api

After ​

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.

go
// 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
}
go
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")
	}
}
text
module academy/docker-images-dockerfiles

go 1.24

The 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.

dockerfile
# 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"]
text
# 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*
.dockerignore

The 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):

yaml
# .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 golang images have gcc, so a native build inside them links against glibc. Always set CGO_ENABLED=0 for static/scratch images, and check with go version -m binary | grep CGO_ENABLED.
  • What cgo-free changes. With cgo off, net uses the pure-Go DNS resolver and os/user reads /etc/passwd directly, which is why distroless ships a passwd file. If you need cgo (SQLite via mattn/go-sqlite3, some crypto libraries), use distroless/base or cc.
  • 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; .dockerignore excludes .git, so in the image that data is absent and the COMMIT build arg carries it instead (-buildvcs=false makes the omission explicit).
  • Size flags. -s -w drop the symbol table and DWARF; -trimpath removes 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=readonly and a committed go.sum keep 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 default docker stop timeout is 10 s; Kubernetes terminationGracePeriodSeconds defaults 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.

dockerfile
# 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-fpm

After ​

One Dockerfile, two runtime targets (app = php-fpm, web = Nginx), with Composer and Vite in their own stages:

dockerfile
# 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/public

The entrypoint caches config at start-up (when the real environment exists) and execs so php-fpm is PID 1:

bash
#!/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 "$@"
ini
; 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
nginx
# 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;
    }
}
text
# 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*
.dockerignore

A minimal Compose file for the two containers (Compose itself is taught in Running Containers):

yaml
# 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: 10s

The single-container alternative: FrankenPHP with Octane, non-root on an unprivileged port, health-checked through /up with PHP itself:

dockerfile
# 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 freezes env() 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 /up by default ("will return a 200 HTTP response if the application has booted without exceptions"), configured with health: '/up' in bootstrap/app.php; it is the natural target for Compose health checks and Kubernetes probes:
php
<?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/ and bootstrap/cache/ need to be writable; logs should go to stderr (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 app image with a different command: CMD ["php","artisan","queue:work","--max-time=3600"] (exec form so SIGTERM reaches the worker) and CMD ["php","artisan","schedule:work"]. Laravel documents --max-time ("process jobs for the given number of seconds and then exit") and presents schedule:work for running the scheduler in the foreground without cron; production setups may instead run schedule:run from cron.
  • Octane caveat. The app stays in memory, so static state and singletons leak between requests; Laravel's Octane docs cover --max-requests and 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, the dunglas/frankenphp images "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 ​

ProblemSolutionHowAdvantageCost / limit
Every build re-downloads dependenciesManifest-first ordering + cache mountsCOPY go.mod go.sum / composer.lock before source; --mount=type=cacheMinutes become secondsNeeds BuildKit; cache is per builder
CI has no cacheExternal cache--cache-to type=registry,...,mode=max / type=ghaWarm builds on fresh runnersCache export time and storage
Image is hugeMulti-stage + smaller baseToolchain in build stage, distroless/slim runtimeSmaller pulls, fewer CVEsNo shell in distroless
Secrets in layers or historySecret mountsRUN --mount=type=secret,id=... + --secretNever stored, not in provenanceChanging a secret does not bust cache
App ignores docker stopExec form + signal handlingENTRYPOINT ["app"], exec "$@", tini/--initGraceful drainsMust also handle SIGTERM in code
Runs as rootUSER with numeric UIDUSER 65532:65532, COPY --chownPasses runAsNonRoot, smaller blast radiusPorts < 1024 need a capability
Wrong architectureMulti-arch index--platform linux/amd64,linux/arm64, cross-compileOne name for every hostEmulation is slow for compiled stacks
"Same tag, different code"Digests + immutable tagsDeploy @sha256:; ECR IMMUTABLEExact rollbacksNeed tooling to bump digests
Docker Hub 429sAuthenticate and mirrordocker login, pull-through cacheStable CIOne more registry to run
Unknown origin of an imageProvenance + signature--provenance=mode=max, cosign sign by digest, admission verifyPolicy-enforced trustKey/OIDC setup, policy maintenance
Health check always failingSelf-probeCMD ["/app","healthcheck"], php -rWorks without curl or shellOne 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 ​

dockerfile
# 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-dist
bash
COMPOSER_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 ​

WorkloadRecommended baseExtra techniqueReason
Go service, CGO_ENABLED=0gcr.io/distroless/static-debian13:nonroot-trimpath -ldflags "-s -w"Smallest useful base with certs, tzdata, passwd
Go CLI with no TLS or time zonesscratchEmbed time/tzdata if neededNothing to patch
Go with cgo (SQLite, librdkafka)gcr.io/distroless/base-debian13 or ccSame Debian release as the build stageglibc ABI match
Laravel on php-fpmphp:8.4-fpm-trixie + nginx:1.28-alpineProduction ini, OPcache tuned, non-root FPMOfficial, maintained, glibc
Laravel with Octanedunglas/frankenphp:1-php8.4-trixiepcntl, non-root, SERVER_NAME=:8000One process serves HTTP and PHP
Tools image for CI jobsdebian:trixie-slim or alpine:3.23Pin package versionsNeeds a shell and a package manager

Which tags ​

SituationTags to pushWhat to deploy
Release from a Git tag v1.4.21.4.2, 1.4, 1, sha-<commit>Digest of that build
Main branchmain, sha-<commit>Digest (GitOps tool writes it back)
Pull request previewpr-<n>Digest; delete tag on merge
Base images you consume(theirs)FROM name:tag@sha256:... bumped by bot

Which registry setup ​

Team / platformRegistryWhy
GitHub-centric, open sourceGHCRGITHUB_TOKEN, repo linking, free public images
AWS workloads (EKS, ECS)ECR (+ pull-through cache for Docker Hub)IAM auth, immutability, in-region pulls
GitLab-centricGitLab container registryCI_JOB_TOKEN, built-in cleanup policies
Air-gapped or multi-cloudHarbor / ArtifactoryProxy cache, replication, robot accounts, signing policy
Public distributionDocker Hub (+ GHCR mirror)Discoverability; mind pull limits for your users

Which PHP serving model ​

SituationModelReason
Existing Nginx expertise, classic LaravelNginx + php-fpm, two containersWell understood, static files from Nginx
One image per service wanted, HTTP/3, automatic TLSFrankenPHP (classic mode)One process, Caddy built in
Latency-sensitive API, app is stateless-safeFrankenPHP or Swoole/RoadRunner with OctaneBoot once, serve many requests
Kubernetes podNginx sidecar + php-fpm in one pod, or FrankenPHPSidecar 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:

text
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 layer

Provisioning 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 ​

ScaleBuildsImages and registryDeploys
1x (one team, one VM)Local docker build, then a single CI jobDocker Hub or GHCR, semver tagsCompose, pinned tags
10x (several teams, one cluster)CI with registry cache (mode=max), multi-arch, build checks and scanning as gatesGHCR/ECR, immutable release tags, lifecycle rules, base images maintained centrallyHelm/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 buildsRegional replicas, pull-through caches, referrers replicated, SBOM inventory queried centrallySigned-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) ​

bash
cd docs/snippets/platform/docker-images-dockerfiles/go-service
gofmt -l . ; go vet ./... ; go test -race -count=1 ./...
# ok  	academy/docker-images-dockerfiles	1.421s

2. What CGO_ENABLED=0, -s -w and cross-compilation do (ran on the host) ​

bash
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=arm64

Two 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):

bash
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=1

4. Build, inspect and compare the two Dockerfiles (expected, not run) ​

bash
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) ​

bash
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 violations

6. Multi-arch index and attestations (expected, not run; the sample below is Docker's documented output for alpine) ​

bash
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/v8

7. Rate-limit headers, scan and sign (expected, not run; header sample from Docker's pull-limit docs) ​

bash
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.com

Common misconceptions ​

BeliefReality
RUN rm in a later step shrinks the imageIt adds a whiteout; the earlier layer's bytes still ship. Delete in the same RUN or use a discarded stage
EXPOSE publishes a portDocumentation only; -p/-P or a Service publishes
latest is the newest versionIt is the default tag name; it moves on every push and is not ordered
A tag identifies fixed contentOnly 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 containerIt 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 HEALTHCHECKIt uses its own probes; HEALTHCHECK is for Docker, Compose and Swarm
Alpine is always the best small basemusl 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 imagesExperimental, legacy builder only, loses layer sharing; multi-stage is Docker's recommended alternative
apt-get update in a cached layer gives current packagesThe cache key is the command string; the week-old index is reused
An amd64 image runs anywhereOnly on amd64 (or under emulation); otherwise exec format error
Zero scanner findings means secureScanners match package versions; they do not see your code or unpackaged binaries
Signing a tag protects the deploymentSignatures cover a digest; deploy and verify by digest
Running as root in a container is harmlessUID 0 against the kernel and mounted paths; add USER with a numeric UID

Cheat sheet ​

TopicRemember
Image anatomyindex -> manifest per platform -> config + ordered layers; everything by digest
LayersRead-only, additive; whiteouts hide, never free; container layer is copy-on-write, survives stop/start, deleted with the container
Cache orderRarely-changing first: base, system packages, lock files, dependency install, source, build
Cache rulesFirst miss invalidates the rest of the stage; RUN keyed by command string; COPY by file checksum (not mtime)
BuildKit mountscache for package caches, bind for one-step files, secret for tokens, ssh for private Git
Multi-stageBuild with everything, COPY --from only the artefact; --target picks a stage
Go imageCGO_ENABLED=0 -trimpath -ldflags "-s -w", FROM --platform=$BUILDPLATFORM, distroless static nonroot
PID 1Exec form, exec "$@" in scripts, --init/tini for children, handle SIGTERM in code
USERNumeric UID:GID, writable dirs via COPY --chown
HEALTHCHECKDefaults 30s/30s/0s/5s/3; exit 0/1 (2 reserved); self-probe in shell-less images
TagsHumans read tags (1.4.2, 1.4, sha-...); machines deploy digests; releases immutable
RegistriesAuthenticate CI; Docker Hub anonymous 100 pulls / 6 h per IP; mirror base images
Supply chainDefault min provenance; add --sbom=true; mode=max exposes build args; cosign by digest
Scanninghadolint + docker build --check before; Trivy/Grype/Scout after; rescan deployed digests
PHPphp-fpm + Nginx (never publish 9000) or FrankenPHP/Octane; production ini; OPcache validate_timestamps=0; Composer --no-dev + authoritative classmap; config:cache at start
ReproducibleSOURCE_DATE_EPOCH, rewrite-timestamp=true, bases by digest, pinned packages

Self-check: questions & answers ​

Show:
  • 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 ​

TermMeaning
OCI image specOpen Container Initiative standard for image index, manifest, config and layers (v1.1, 2024)
Image index / manifest listJSON listing one manifest per platform (plus attestation manifests) under one digest
Image manifestJSON 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
LayersTar changesets stacked in order; base at index 0
DiffID / ChainIDDigest of an uncompressed layer / compound digest identifying a stack of layers
Digestsha256:<hex> of content; immutable identity of a blob, manifest or index
Union filesystemSeveral directories presented as one merged tree
OverlayFSLinux union filesystem used by Docker's overlay2 and containerd snapshotters (lowerdir, upperdir, merged)
Copy-on-writeA 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 contextThe files sent to the builder; the only files COPY can read
.dockerignorePattern file excluding paths from the build context; last matching line wins, ! re-includes
Dockerfile instructionsFROM, RUN, COPY, ADD, WORKDIR, ENV, ARG, EXPOSE, LABEL, USER, HEALTHCHECK, ENTRYPOINT, CMD, STOPSIGNAL, SHELL, VOLUME, ONBUILD
FROMStarts a stage from a base image (tag and/or digest, optional --platform, AS name)
RUNExecutes a command at build time and commits a layer; supports --mount
COPY vs ADDCOPY copies local/stage files; ADD also fetches URLs and Git repos and extracts local tars
WORKDIRSets (and creates) the working directory for later instructions
ENV vs ARGENV persists into containers; ARG is build-time only but recorded in history/provenance
EXPOSEDocuments listening ports; does not publish
LABELImage metadata; use org.opencontainers.image.* keys
USER and non-rootDefault user/group for later steps and the container; use a numeric non-zero UID
HEALTHCHECKDocker's in-container probe; exit 0 healthy, 1 unhealthy
ENTRYPOINT vs CMDThe executable vs its default arguments (CMD alone is the whole default command)
Exec form vs shell formJSON array run directly vs string run under /bin/sh -c
PID 1 and signalsThe first process in the namespace; no default signal actions, must reap children
tiniMinimal init that forwards signals and reaps zombies; Docker's --init uses it as docker-init
STOPSIGNALSignal docker stop sends (default SIGTERM; php-fpm images use SIGQUIT)
Layer cachingReusing a step's previous result when the instruction and inputs match
Cache invalidation orderFirst miss invalidates all later steps in the stage; order instructions by change frequency
BuildKitDocker's build engine: LLB graph, concurrency, mounts, attestations; default builder
buildxDocker CLI plugin driving BuildKit (drivers, --platform, --push, --cache-to, bake)
LLB / frontendBuildKit'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 buildsSeveral FROM stages in one Dockerfile; later stages copy artefacts from earlier ones
Builder patternPre-17.05 two-Dockerfile workflow (build image, extract artefact) replaced by multi-stage
scratchThe empty base image
distrolessGoogle's minimal images without shell or package manager (static, base, cc, language runtimes; :nonroot, :debug)
Static Go binaryA Go executable with no dynamic libc dependency, built with CGO_ENABLED=0
CGO_ENABLED=0Disables cgo; pure-Go net and os/user, static output
alpine vs debian-slim vs distrolessmusl + BusyBox + apk vs glibc + apt vs no shell and no package manager
muslThe C library used by Alpine; differs from glibc in DNS, locale and ABI details
Image sizeSum of all layer blobs (compressed on the registry, uncompressed on disk)
Image squashing mythsThe belief that --squash is the right size fix; it is experimental, legacy and loses layer sharing
diveTool that browses layers and scores wasted space; CI=true gives pass/fail
Reproducible buildsSame source gives the same bytes and digest
SOURCE_DATE_EPOCHStandard variable (seconds since 1970) that build tools use instead of "now"
Multi-arch / platformsOne image name for several os/arch[/variant] targets
QEMU emulationRunning foreign-architecture binaries through binfmt_misc user-mode emulation during builds
Cross-compilationCompiling for the target platform on the build platform ($BUILDPLATFORM to $TARGETPLATFORM)
Tagging strategyThe set of tags pushed per build (semver, commit, branch) and which one is deployed
latestThe default tag name; mutable and unordered
Semantic tags1.4.2, 1.4, 1 for one build; the shorter ones move forward
Immutable tagsRegistry setting that rejects pushing an existing tag (ECR ImageTagAlreadyExistsException)
RegistriesServers implementing the OCI distribution spec: Docker Hub, GHCR, ECR, GitLab, Harbor, Artifactory
Docker HubDocker's public registry; pull rate limits per 6 hours by account type
GHCRGitHub Container Registry, ghcr.io, authenticated with GITHUB_TOKEN in Actions
ECRAmazon Elastic Container Registry; IAM auth, tag immutability, lifecycle policies
Private registryA registry you run or rent (Harbor, registry:2, Artifactory), often as a pull-through cache
push/pullUpload missing blobs then the manifest / fetch manifest then missing blobs
Rate limitsDocker Hub: 100 anonymous pulls per IPv4 or IPv6 /64 per 6 h, 200 for Personal; HTTP 429
ReferrersOCI 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)
SBOMSoftware Bill of Materials; BuildKit emits SPDX JSON with --sbom=true
Provenance attestationsSLSA-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
hadolintDockerfile linter (DL rules) using ShellCheck for RUN scripts
Build checksdocker build --check rules such as JSONArgsRecommended; # check=error=true fails builds
php-fpm imagesOfficial php:*-fpm images: FastCGI on 9000, STOPSIGNAL SIGQUIT, www-data pools
Composer in multi-stageComposer binary copied from composer:2, lock files first, --no-dev, authoritative classmap
opcachePHP bytecode cache; enabled in official images; validate_timestamps=0 for immutable code
FrankenPHPPHP application server written in Go on Caddy; classic and worker modes; dunglas/frankenphp images
OctaneLaravel package that boots the app once and serves requests from memory (FrankenPHP, Swoole, RoadRunner)
Nginx sidecar vs single containerNginx + php-fpm as two containers (or one pod) vs one FrankenPHP container

References ​

Built by Morteza Negahi