How to Write Multi-Stage Docker Builds
Compile in one stage and copy only the runtime artifacts into a smaller final image, with cached dependency layers.
On this page
Introduction
A naive Dockerfile installs build tools, compiles the application, and leaves everything in one image. The final image then contains compilers, package manager caches and source files that are useless at runtime, multiplying its size and its attack surface. Multi-stage builds compile in one stage and copy only the runtime artifacts into a smaller final stage, so the image ships what it needs and nothing more. This article covers the stages, how to order layers so dependencies cache, how to keep the final image minimal, and the mistakes that reintroduce bloat.
Why One Stage Is Too Big
A single-stage build has to include the toolchain to compile the code, and most of that toolchain is not needed to run the result. The image carries the compiler, the package manager’s cache, build-time dependencies and the source. Every extra package is a larger download, a longer start, and an additional vulnerability to patch. In a container that is pulled to many nodes, the size multiplies across the fleet.
Multi-stage builds separate the concerns: an early stage has the toolchain and produces the artifact, and a later stage starts from a minimal base and copies only the artifact. The final image does not contain the compiler because the compiler ran in a stage that was discarded.
A Multi-Stage Dockerfile
The build stage installs dependencies and compiles; the runtime stage copies the compiled output and the production dependencies. Use a minimal base for the runtime stage, such as a slim or distroless image, and run as a non-root user. The COPY instruction with –from pulls the artifact from the named build stage.
# syntax=docker/dockerfile:1.7
# ---- build stage ----
FROM node:22-bookworm-slim AS build
WORKDIR /app
COPY package.json pnpm-lock.yaml ./
RUN corepack enable && pnpm install --frozen-lockfile
COPY . .
RUN pnpm build && pnpm prune --prod
# ---- runtime stage ----
FROM node:22-bookworm-slim AS runtime
WORKDIR /app
ENV NODE_ENV=production
COPY --from=build /app/node_modules ./node_modules
COPY --from=build /app/dist ./dist
COPY --from=build /app/package.json ./
USER node
EXPOSE 8080
CMD ["node", "dist/server.js"]
Layer Ordering for Cache
Docker caches a layer if the instruction and its inputs are unchanged. Copying the lockfile and installing dependencies before copying the source means the dependency layer is reused whenever only source changes, which is the common case. If the source is copied first, any change invalidates the dependency install and every build reinstalls everything. Order from least to most frequently changing.
Combine the dependency manifest and lockfile into one COPY so a change to either invalidates the install, and keep the install command on its own layer. Use a build cache mount for the package manager store so even an install that has to run reuses downloaded packages across builds. This is the same content-addressed caching idea applied inside the image build.
# syntax=docker/dockerfile:1.7
FROM node:22-bookworm-slim AS build
WORKDIR /app
# Cache mount keeps the pnpm store across builds; the store is not in the image.
COPY package.json pnpm-lock.yaml ./
RUN --mount=type=cache,target=/root/.local/share/pnpm/store \
corepack enable && pnpm install --frozen-lockfile
# Source is copied after dependencies so a source change does not reinstall.
COPY . .
RUN pnpm build
Keeping the Final Image Minimal
Copy only what runtime needs: the compiled output, the production dependencies, and any static assets. Never copy the build stage’s source or its development dependencies. Prune development dependencies in the build stage so the runtime stage copies a production tree. Use a distroless or slim base to avoid shells and package managers that runtime does not use.
Run as a non-root user so a compromise inside the container has fewer privileges. Set the working directory, expose only the port you use, and prefer an exec-form command so the process receives signals directly and can shut down gracefully. A shell-form command wraps the process in a shell that may swallow the termination signal.
Secrets and Build Arguments
Never bake secrets into a layer with ARG or ENV, because they persist in the image history and are readable by anyone who pulls it. Use a build secret mount so the value is available only during the instruction that needs it and is not written to any layer. Build arguments that are not secrets can be used for configuration, but treat anything sensitive as a secret mount.
A build that needs a registry token should pass it as a secret mount to the install command, not as an environment variable, so the token is not in the image. The same applies to any private key used to fetch dependencies. The layer history is the threat model: whatever a layer writes is in the image forever.
Common Pitfalls
Copying the whole build stage with COPY –from=build /app /app drags in the source and dev dependencies, defeating the separation. Copy specific paths. A .dockerignore that omits node_modules, .git and test artifacts keeps the build context small and prevents a local node_modules from overwriting the one built in the image.
Building on a full base image for convenience bloats the runtime image, so use a minimal base and install only what runtime needs. Pinning the base by digest rather than by a mutable tag makes the build reproducible, so a base image update does not silently change your image. Finally, do not run the build as root in the runtime stage; create and use a non-root user.
Conclusion
Multi-stage builds compile in one stage and ship only the runtime artifacts in a smaller final stage. Order layers so dependencies cache and only source changes invalidate the cheap layers, use a build cache mount for the package store, copy specific paths into a minimal non-root runtime, and pass secrets as build secret mounts rather than arguments. Add a .dockerignore and pin the base by digest. Then the image is small, starts fast, has a smaller attack surface, and rebuilds quickly when only the code changed.
Sources: Docker: multi-stage builds, Docker: build cache, Docker: build secrets.
FAQ
- Why copy the lockfile and install dependencies before copying the source?
- So the dependency layer caches when only source changes. Docker invalidates a layer when its inputs change; if the source is copied first, every source edit invalidates the install and every build reinstalls everything.
- How do I pass a secret to a build without baking it into the image?
- Use a build secret mount rather than ARG or ENV. The secret is available only during the instruction that needs it and is not written to any layer, so it does not persist in the image history.
Report a problem with this articleOpens a pre-filled issue on GitHub.