JsonMind
Encoding & Text17 min readUpdated Nov 17, 2026

Docker Multi-Stage Builds: Smaller, Hardened, Reproducible Images

Separate build and runtime stages, copy only artifacts, order layers for cache reuse, pin base images by digest, mount secrets safely, and verify the final image.

JMBy JsonMind EngineeringLast reviewed: Nov 17, 2026Reviewed against primary specifications and linked sources.
Quick answer

A multi-stage Docker build compiles in a throwaway stage and copies only the runtime artifact into the final image. Pin base images by digest, order layers around lockfiles, use BuildKit cache and secret mounts, run as non-root with no shell, and enforce size, content, signal, and CVE checks in CI.

Key takeaways
  • A multi-stage build is a trust-boundary tool: the final image should contain the artifact and its runtime dependencies, not the toolchain that produced it.
  • Copy lockfiles before source so dependency layers survive everyday code changes, and keep package-manager caches out of the final filesystem.
  • BuildKit cache mounts speed up repeated builds without adding layers; secret mounts keep tokens out of image history and provenance.
  • Pin base images by digest, run as a numeric non-root user, use exec-form entrypoints, and test a read-only root filesystem.
  • Verify with docker history, filesystem listings, SBOM attestations, and a CVE scan; a successful build is not the same as a safe image.

Multi-stage builds are usually introduced as a way to shrink images, and that framing hides the more useful benefit: they let you compile in an environment that is allowed to be dirty and ship an environment that is not. A builder stage can contain a compiler, a package manager, test fixtures, and repository history. The final stage should contain the application artifact, its runtime libraries, certificates, and the configuration contract the operator expects. Everything else is either waste or attack surface.

Docker images accumulate whatever the build touched. A node_modules directory copied from a CI cache, a Debian package index left behind by an interrupted install, or a .npmrc file with a registry token all travel with the image. Multi-stage builds give you a place to put those things, but they do not remove them automatically.

What multi-stage builds actually solve

A Dockerfile with several FROM instructions is a graph of stages. Each stage has its own filesystem and its own cache key, and a COPY --from=<stage> instruction copies selected files from an earlier stage into the current one. BuildKit builds only the stages required by the target, so a documentation or test stage that nobody depends on is skipped rather than executed.

That execution model is the real feature. The build environment can be large, slow, and privileged, while the runtime environment stays small and boring. The build can use a full Debian image with a compiler, git, and test tooling; the runtime can use a distroless image with a single binary. The build can install private dependencies with a token; the runtime never sees the token as a layer.

The boundary is only real if the copy is narrow. A common anti-pattern declares two stages and then uses the builder as the runtime: the second stage is FROM build and the runtime inherits the source tree, the development dependencies, the package-manager cache, and everything else the build left behind. The same problem appears when a Dockerfile copies an entire root directory with COPY --from=build / / or copies /app when only /app/dist is needed. A useful test is to ask what the runtime process would do with each directory; if the answer is "nothing", it does not belong in the final stage.

Building in one stage, shipping from another

Name the build stage and copy a specific artifact out of it. The following Dockerfile builds a static Go binary in a full toolchain image and ships it on a distroless base. The runtime stage contains the binary, the CA certificates and timezone data that the base image provides, and a non-root user. It contains no compiler, no shell, and no package manager.

# syntax=docker/dockerfile:1.7
FROM golang:1.23-bookworm AS build
WORKDIR /src
ENV CGO_ENABLED=0 GOFLAGS=-trimpath

COPY go.mod go.sum ./
RUN --mount=type=cache,target=/go/pkg/mod \
    go mod download

COPY . .
RUN --mount=type=cache,target=/go/pkg/mod \
    --mount=type=cache,target=/root/.cache/go-build \
    go build -trimpath -ldflags="-s -w -buildid=" -o /out/server ./cmd/server

FROM gcr.io/distroless/static-debian12:nonroot
COPY --from=build /out/server /server
USER 65532:65532
EXPOSE 8080
ENTRYPOINT ["/server"]

Several details are deliberate. CGO_ENABLED=0 produces a static binary, which is what static-debian12 expects. -trimpath removes local filesystem paths from the binary, and -buildid= removes a build identifier that would otherwise vary between otherwise identical builds. The RUN instructions use cache mounts so module downloads and compiler output do not become layers. The final COPY --from=build copies one file, not a directory tree. USER 65532:65532 uses the numeric non-root user that distroless provides; a name would only work if the image had a matching /etc/passwd entry.

The example uses readable tags for the base images so the structure is easy to follow. A release pipeline should resolve those tags to digests and build with FROM image@sha256:..., which section 5 covers. The Dockerfile formatter is useful before review: formatting does not improve security, but consistent instruction layout makes cache-ordering mistakes and accidental broad copies easier to spot.

COPY --from preserves the source stage's permissions unless --chown overrides them, so a binary built as root can still be executable by a non-root user. COPY --link creates an artifact-only layer independently of its parent, which helps when the base image changes; it is an optimization, not a security control. Neither flag helps if the copied directory contains test binaries or fixtures, so build one target per stage.

Layer cache order and lockfile discipline

Every Dockerfile instruction creates a layer whose cache key includes the parent layer and the instruction inputs. A COPY or ADD instruction invalidates the cache when the copied files change. This is why the order of instructions matters more than the number of layers: a single COPY . . before npm ci makes every source edit invalidate the dependency install.

The standard shape is:

  1. Copy only the manifest and lockfile.
  2. Install dependencies.
  3. Copy the rest of the source.
  4. Build.

For Node.js that means COPY package.json pnpm-lock.yaml ./ followed by pnpm install --frozen-lockfile, then COPY . .. Go uses COPY go.mod go.sum ./ and go mod download; Python copies its requirements or lockfile and installs into a virtual environment; Rust copies Cargo.toml and Cargo.lock and fetches dependencies before the real source arrives. The lockfile is part of the cache key on purpose. If it changes, the dependency layer should rebuild; if only source changes, the dependency layer should be reused. A Dockerfile that runs npm install without a lockfile, or copies the lockfile after COPY . ., throws that property away. In CI, use --frozen-lockfile, npm ci, pip install --require-hashes, or the equivalent so the build cannot resolve a different dependency graph than the one tested.

System packages need their own discipline. Combine apt-get update and apt-get install in one RUN, install with --no-install-recommends, and delete /var/lib/apt/lists/* in the same instruction. Splitting the update into its own layer lets a cached package index go stale while the install layer still claims to be current. Avoid apt-get upgrade inside the image; the base image digest is where patches belong. Alpine has the same issue with apk update and apk add --no-cache.

Cache scope matters too. A local Docker daemon cache disappears on a new CI runner, so configure a registry-backed cache with --cache-from type=registry,ref=... and --cache-to type=registry,ref=...,mode=max. A build that only succeeds with a warm cache is hiding a missing dependency or an undeclared file.

BuildKit cache mounts without polluting layers

BuildKit cache mounts solve a different problem from layer caching. A layer cache reuses the result of an instruction when its inputs are unchanged; a cache mount keeps a directory between builds even when the instruction runs again, and the directory is not committed to the image. The Go example uses one mount for the module cache and one for the compiler cache. A Node.js build can mount the package-manager store, and a Python build can mount a pip cache.

The syntax is a RUN --mount=type=cache,target=<path> flag. Useful options are id= to separate caches for different toolchains or architectures, sharing=locked when two concurrent builds must not write the same cache directory at once, and mode= when the build user needs a specific permission. A cache mount is visible only during that RUN instruction, so a later instruction cannot read it and the final image cannot inherit it.

Cache mounts are not a substitute for lockfiles. A stale cache can contain a package version that the lockfile no longer references, and a build that relies on the cache can appear to succeed while a clean build fails. Run a periodic --no-cache build, or at least a build on a fresh runner, to verify that every dependency is declared. Treat cache contents as untrusted input if the cache is shared across branches or pull requests; a compromised cache can feed modified compiler output into a build.

BuildKit is the default builder in current Docker releases; older installations may need DOCKER_BUILDKIT=1 or a buildx builder. If a RUN --mount line fails with a syntax error, check the builder and the # syntax=docker/dockerfile:1.7 directive before rewriting the instruction.

Base image strategy: digest pins, distroless, Alpine, and slim

A tag is a mutable pointer. node:22 can point to a different image next week, and latest can point to a different major version without warning. A digest identifies a specific manifest, so FROM node:22-bookworm-slim@sha256:... builds the same bytes until you intentionally update the digest. Use a tool such as docker buildx imagetools inspect or your registry's API to resolve a tag, then let Renovate or Dependabot update the digest in a reviewed pull request. Pin the multi-architecture index digest when you publish for more than one platform; pinning a platform-specific manifest digest silently limits the build to that architecture.

The base image choice is a tradeoff between compatibility, attack surface, and operability. The table below summarizes the common families; sizes are approximate uncompressed sizes for small amd64 images and will vary by release.

FamilyApprox. sizeShelllibcBest forMain tradeoff
distroless/static2 MBNoNoneStatic Go, Rust, or C binariesNo shell or package manager for debugging
distroless/base20 MBNoglibcDynamically linked services with minimal userlandFewer debugging tools than a full distribution
Alpine8 MBYesmuslSmall services and simple shell-based entrypointsmusl can break native modules and DNS assumptions
Debian slim75 MBYesglibcNative dependencies and familiar apt toolingLarger attack surface and image size
Ubuntu78 MBYesglibcVendor-supported workloadsLarger still, with more packages by default

Distroless images remove the shell and package manager, which is a security benefit and an operational cost. You cannot docker exec into a distroless container to run sh, curl, or ps; use an ephemeral debug container in Kubernetes or unpack the image with crane export on the host. Do not add a shell back to production just to make debugging convenient.

Alpine is small because it uses musl libc and BusyBox. That is fine for many Go and Rust binaries, but native addons compiled against glibc, DNS search-domain behavior, and some Java or Python wheels can behave differently. If you choose Alpine, install build dependencies in a virtual package, remove them in the same layer, and test the runtime path. Debian slim keeps glibc and apt, which is often the pragmatic choice for Python, Java, and Node.js services with native modules; remove the apt lists and avoid recommended packages.

A Dockerfile generator is a reasonable starting point for a new service, but a generated file still needs digest pins, a non-root user, a lockfile-aware layer order, and a deliberate base image choice. Treat generation as scaffolding, not as a security review. Whatever family you choose, never deploy :latest; an image reference without a tag or digest is a production incident waiting for a convenient moment.

The build context and .dockerignore

The build context is the set of files sent to the builder. A context that includes node_modules, .git, compiled output, test fixtures, and local environment files makes every build slower and increases the chance that a secret is copied into a layer. .dockerignore is the first line of defense, and it is evaluated independently of .gitignore.

A useful baseline excludes version-control metadata, dependency directories, build output, local environment files, private keys, logs, and editor state. Keep the file in version control and review changes to it like code. Patterns are evaluated in order, and a later negation can re-include a file, so put broad exclusions first and specific exceptions after them. If a build genuinely needs a file that the ignore file excludes, prefer an explicit COPY of a generated artifact or a named build context over weakening the ignore rules for the whole repository.

BuildKit transfers context lazily and may not send files that no instruction reads, which softens the cost of a large context but does not remove the risk. A COPY . . still makes the entire included context part of the cache key, and a secret file that matches no ignore rule can still be copied by a careless instruction. Verify the effective context by building with --no-cache and inspecting the layer that contains the application; if a file is present that the runtime does not need, fix the copy or the ignore file.

Named contexts are useful for monorepos. docker buildx build --build-context shared=../shared lets a Dockerfile copy from a separate directory without sending the entire repository as one context. A Dockerfile can also be read from standard input with docker build -f - . for generated or one-off builds.

Hardening the final image for production

Run the application as a non-root user. A numeric USER is the most portable form because it does not depend on a name existing in /etc/passwd, and Kubernetes can enforce it with runAsNonRoot: true. If the application writes files, give it an explicit writable directory with the right ownership; do not make the whole filesystem writable to avoid a permission error. Some runtimes need HOME set to a writable path; supply that detail deliberately rather than falling back to root.

Make the root filesystem read-only where the application allows it. docker run --read-only --tmpfs /tmp is a good local test, and Kubernetes readOnlyRootFilesystem: true is the production equivalent. Mount only directories that must be writable, such as a cache or upload directory, and keep them off the image layer. An accidental write then fails during testing instead of persisting in production.

Remove the shell and package manager from the final image when you can. Distroless and scratch bases do this by construction. With Alpine or Debian, remove build dependencies in the same layer that installed them, delete package-manager caches, and consider whether apk or apt-get needs to remain. Removing the package manager makes incident response harder, so pair it with an ephemeral debug workflow.

Set the container's security context at the orchestrator level as well: drop Linux capabilities, enable no-new-privileges, use the default seccomp profile or a tighter one, and do not mount the Docker socket. These controls complement the image; they do not replace a non-root user, because a root process with no capabilities can still read world-readable secrets and write to mounted volumes.

Signal handling is part of hardening. A process that runs as PID 1 has special signal semantics, and many runtimes do not install handlers for signals that were not sent to them directly. Use the exec form of ENTRYPOINT so the application, not a shell, receives SIGTERM. If the application spawns children and does not reap them, add tini or dumb-init as the entrypoint and pass the application as arguments. Set STOPSIGNAL SIGTERM explicitly when needed, and test docker stop with a timeout that matches the orchestrator's grace period.

Secrets, signal handling, and reproducible builds

Build secrets are the most common way a hardened image leaks. ARG and ENV are not secret storage. An ARG value can appear in image history, provenance attestations, and CI logs, and an ENV value is stored in the image configuration that anyone who pulls the image can read. A multi-stage build does not automatically sanitize provenance; if a secret is used in a build stage, assume it can be recorded in build metadata even when the final stage does not contain the file.

BuildKit secret mounts are the correct tool. A RUN --mount=type=secret,id=npmrc,target=/root/.npmrc instruction makes the file available only for that command, and docker buildx build --secret id=npmrc,src=$HOME/.npmrc supplies it at build time. The secret is not committed to a layer and is not part of the final filesystem. Use the same pattern for a private Go module token, a Maven settings file, or a signing key, and use --mount=type=ssh for private Git repositories instead of copying an SSH key into the context.

Reproducibility is a related discipline. Pin base images by digest, commit lockfiles, use deterministic compiler flags such as -trimpath and -buildid=, and set SOURCE_DATE_EPOCH when the toolchain honors it. Avoid instructions that embed timestamps or hostnames, and avoid apt-get upgrade and floating package versions. A reproducible build should produce the same digest from the same inputs and the same builder configuration; BuildKit version, base image digest, and build arguments are all inputs. If you cannot achieve bit-for-bit reproducibility, record the inputs and the resulting digest so an auditor can reconstruct the build.

Supply-chain evidence belongs with the image, not in a separate spreadsheet. Build with --sbom=true and --provenance=mode=max to attach an SBOM and provenance attestation to the image index, then scan the digest you actually deploy. docker scout cves, trivy image, or your registry's scanner can fail the pipeline on fixable critical vulnerabilities. Store the report as a CI artifact, sign the image with cosign if your platform supports it, and verify the signature at admission time. The OCI Image Specification defines the manifest and index that make these references portable across registries.

Reading image size with docker history

docker history is the first tool to reach for when an image is larger than expected. docker history --no-trunc --human <image> lists each layer with its size and the command that created it. Look for a single layer that dominates the total, a COPY that brought in a directory you did not intend, or a RUN that installed a toolchain and never removed it. docker image inspect --format '{{.Size}}' <image> gives the total uncompressed size, and docker history --format '{{.Size}}\t{{.CreatedBy}}' is easy to sort in a script.

There are limits to what history can tell you. Layer sizes include files that were later deleted by a whiteout, so a small final filesystem can still sit on top of a large discarded layer. History attributes a layer to the instruction that created it, but a RUN can hide many operations behind one command. For a precise file view, export the container filesystem with docker export, or use dive or crane export for a readable layer view; docker save by itself lists the layer archives, not their contents. Inspect the final stage, not an intermediate stage, and remember that multi-architecture images have different sizes per platform.

Common sources of bloat are build tools left in the runtime stage, package-manager caches, documentation and man pages, test suites and fixtures, duplicate dependency trees, and language runtimes that are not needed at runtime. Compression does not fix the filesystem, but it affects transfer time: registries pull gzip-compressed blobs, so measure the compressed size separately with docker save <image> | gzip -9 | wc -c. For text artifacts such as an SBOM, a build report, or a generated configuration, the gzip tool is a quick way to see how much the payload compresses before you decide whether to publish it alongside the image.

Set a size budget and enforce it in CI. A static Go service can reasonably fit under 25 MB, a Node.js service under 180 MB, and a JVM service under 300 MB, but the right number depends on the runtime and the dependencies. Track the size of the digest you deploy, compare it with the previous release, and treat an unexplained increase as a review item rather than a cosmetic warning.

Verification checklist and pass criteria

Verify the image you are about to deploy, not a local tag that may point somewhere else. The commands below assume an application that exposes a self-test flag and an image tagged app:verify. Adapt the health check to the service, but keep the order: build cleanly, inspect metadata, run read-only, inspect the filesystem, check for secrets, scan, and review the size.

set -euo pipefail
IMAGE=app:verify

docker buildx build --pull --no-cache --sbom=true --provenance=mode=max --tag "$IMAGE" .
docker inspect --format 'user={{.Config.User}} entrypoint={{.Config.Entrypoint}}' "$IMAGE"
docker run --rm --read-only --tmpfs /tmp:rw,noexec,nosuid "$IMAGE" --health-check

cid=$(docker create "$IMAGE")
files=$(mktemp)
trap 'rm -f "$files"; docker rm "$cid" >/dev/null' EXIT
docker export "$cid" | tar -tf - > "$files"
! grep -Eq '(^|/)(gcc|g\+\+|apk|apt-get|npm|pip|yarn)(-[0-9.]+)?$' "$files"

created=$(docker history --no-trunc --format '{{.CreatedBy}}' "$IMAGE")
! grep -Eiq '(password|passwd|api[_-]?key|access[_-]?key|token[=:]|BEGIN [A-Z ]*PRIVATE KEY)' <<<"$created"
docker scout cves "$IMAGE" --only-fixed --exit-code
docker history --no-trunc --human --format '{{.Size}}\t{{.CreatedBy}}' "$IMAGE"

The pass criteria are deliberately objective:

CheckEvidencePass criterion
Runtime userdocker inspect .Config.UserNon-empty and not root, 0, or 0:0
Filesystem contentsdocker export listing or unpacked imageNo compiler, package manager, VCS metadata, tests, or build cache
SecretsHistory, provenance, and filesystem listingNo token, password, or private-key material
Read-only behaviordocker run --read-only with a health checkHealth check passes with only declared writable mounts
Signal handlingdocker stop timing and exit codeProcess exits with 0 or 143 within the grace period, with no orphan
Supply chainSBOM and CVE scan for the deployed digestAttestation present; no fixable critical vulnerabilities
SizeHistory and CI budgetWithin budget; every large layer explained

A build that passes these checks is still not automatically safe: the application can have a vulnerability that no scanner knows about, and the base image can change after you scan it. What the checklist buys you is a consistent, reviewable boundary. The final stage should contain only what the runtime needs, the image should identify exactly which bytes were built, and the pipeline should be able to prove both claims for the digest that reached production.

Frequently asked questions

Does a multi-stage build always produce a smaller image?

No. It removes the toolchain only when the final stage copies artifacts rather than the whole build root. Copying a directory that still contains caches, source, or test data can make a multi-stage image as large as a single-stage one.

Can I use ARG or ENV for build secrets?

No. ARG and ENV values are stored in image metadata and can appear in history, provenance attestations, and CI logs. Use BuildKit secret mounts for tokens, .npmrc files, and private keys, and keep those files in .dockerignore.

Should the final image use Alpine, slim, or distroless?

Choose by runtime need, not size alone. Distroless removes the shell and package manager, Alpine is small but uses musl, and slim keeps glibc and apt. Test native modules, DNS resolution, and certificates on the chosen base before committing to it.

How do I know that no build tools remain in the image?

Inspect the unpacked filesystem or the layer tar listing for compilers, package managers, and cache directories, not just docker history. Run the image with a read-only root filesystem and an exec-form health check, then scan the digest you actually deploy.

Do I still need tini or dumb-init?

Only when the application does not behave correctly as PID 1. An exec-form ENTRYPOINT avoids a shell wrapper, while tini or dumb-init reaps zombies and forwards SIGTERM. Test docker stop and confirm that the process exits within the grace period.

Reviewed against primary specifications and linked sources.

JsonMind guides are written and reviewed by the engineering team. We check each guide against the relevant RFC or vendor documentation, link the primary sources, and update the guide when behavior changes.

Primary sources are linked at the end of each guide.

References

Put this guide into practice

Browse all tools

Open the browser tool. Inputs stay in your browser and are not uploaded to the business server.

Related guides

All guides