Multi-Stage Builds: Shrinking Images from Gigabytes to Megabytes
Docker multi-stage builds keep compilers and dev dependencies out of production images. See Go, Node.js, Java and Python examples.
FROM instructions in one Dockerfile. Early stages have everything needed to compile and test: SDKs, compilers, dev dependencies. The final stage starts from a small runtime image and copies in only the built artifact with COPY --from. Nothing from the build stages ships unless you copy it. A Go service drops from roughly 800 MB to under 20 MB, a Java service sheds its JDK and Maven cache, and a Node app leaves its dev dependencies and build tooling behind, with a smaller attack surface as a bonus.
A Go service’s image is 1.1 GB. It contains the Go toolchain, the module cache, the source code, git and a full Debian userland. The program that actually runs in production is a single 14 MB binary. Every deploy pulls the rest across the network, and every vulnerability scan reports dozens of CVEs in compilers and libraries the service never uses.
Before multi-stage builds, teams fixed this with a “builder pattern”: one Dockerfile to compile, a shell script to copy the artifact out, and a second Dockerfile to package it. Multi-stage builds put both halves in one Dockerfile. Each FROM starts a new stage, stages can be named, and a later stage can copy files from an earlier one. Only the last stage, or the one you target, becomes the image.
The shape of every multi-stage build
# Stage 1: everything needed to build
FROM some-sdk AS build
...compile, test...
# Stage 2: only what is needed to run
FROM small-runtime
COPY --from=build /path/to/artifact /app/
CMD ["/app/artifact"]
Because image size is determined only by the final stage’s layers, there is no need for the cleanup gymnastics described in Dockerfile fundamentals. The build stage can be as messy and cache-heavy as it likes.
Go: a static binary on a tiny base
# syntax=docker/dockerfile:1
FROM golang:1.20 AS build
WORKDIR /src
COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN CGO_ENABLED=0 GOOS=linux go build -trimpath -ldflags="-s -w" -o /out/api ./cmd/api
FROM gcr.io/distroless/static-debian11:nonroot
COPY --from=build /out/api /api
USER nonroot:nonroot
ENTRYPOINT ["/api"]
With CGO_ENABLED=0, Go produces a statically linked binary with no dependency on the C library, so the runtime image needs almost nothing: the distroless static image provides CA certificates, time zone data and a non-root user in a few megabytes. The golang:1.20 build image is around 800 MB; the final image is the size of your binary plus a couple of megabytes. You could even use FROM scratch, but then you must copy in CA certificates yourself or every HTTPS call fails.
Node.js: leave dev dependencies behind
# syntax=docker/dockerfile:1
FROM node:18-bullseye-slim AS deps
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci
FROM deps AS build
COPY . .
RUN npm run build \
&& npm prune --omit=dev
FROM node:18-bullseye-slim AS runtime
ENV NODE_ENV=production
WORKDIR /app
COPY --from=build --chown=node:node /app/node_modules ./node_modules
COPY --from=build --chown=node:node /app/dist ./dist
COPY --chown=node:node package.json ./
USER node
CMD ["node", "dist/server.js"]
The build stage installs everything, including TypeScript, bundlers and test frameworks, compiles to dist, then prunes dev dependencies. The runtime stage copies only compiled JavaScript and production modules. Source TypeScript, test files, .git and build caches never reach production. For TypeScript projects with large dev toolchains, this often cuts the image by half or more.
Java: build with the JDK, run with the JRE
# syntax=docker/dockerfile:1
FROM maven:3.9-eclipse-temurin-17 AS build
WORKDIR /src
COPY pom.xml .
RUN mvn -B dependency:go-offline
COPY src ./src
RUN mvn -B package -DskipTests
FROM eclipse-temurin:17-jre
WORKDIR /app
COPY --from=build /src/target/billing-api.jar app.jar
RUN useradd --system --uid 10001 app
USER app
ENTRYPOINT ["java", "-jar", "/app/app.jar"]
The Maven image carries the JDK, Maven and the local repository of downloaded dependencies, often well over a gigabyte once cached. The JRE runtime image carries only what is needed to run a JAR. Copying pom.xml and resolving dependencies before copying src keeps the slow dependency download cached until the POM changes.
Python: build wheels, install them clean
# syntax=docker/dockerfile:1
FROM python:3.11 AS build
WORKDIR /src
COPY requirements.txt .
RUN pip wheel --wheel-dir /wheels -r requirements.txt
FROM python:3.11-slim
WORKDIR /app
COPY --from=build /wheels /wheels
RUN pip install --no-cache-dir /wheels/* && rm -rf /wheels
COPY . .
USER nobody
CMD ["gunicorn", "-b", "0.0.0.0:8000", "app:app"]
Packages with C extensions need compilers and header files to build. The full python:3.11 image has them; the slim image does not. Building wheels in the first stage and installing the finished wheels in the slim stage gives you compiled dependencies without the compiler.
Using stages for more than size
Dev, test and production from one file
FROM node:18-bullseye-slim AS base
WORKDIR /app
COPY package*.json ./
FROM base AS dev
RUN npm install
CMD ["npm", "run", "dev"]
FROM base AS test
RUN npm ci
COPY . .
RUN npm test
FROM base AS prod
RUN npm ci --omit=dev
COPY . .
CMD ["node", "server.js"]
docker build --target dev -t billing-api:dev .
docker build --target test . # fails the build if tests fail
docker build --target prod -t billing-api:1.2.0 .
--target stops the build at the named stage. With BuildKit, now the default builder, stages that the target does not depend on are skipped entirely, so building prod does not run the test stage unless you ask for it. The legacy builder ran every stage in order, which made multi-target Dockerfiles slow.
Copying from any image
COPY --from also accepts an image name, which is a clean way to pull a single binary out of another image without installing it:
COPY --from=busybox:1.36 /bin/wget /usr/local/bin/wget
Measuring the result
docker image ls billing-api
docker history billing-api:1.2.0
Compare sizes before and after, and check docker history to confirm that only the runtime stage’s layers made it into the image. Remember that size is not the only win: fewer packages mean fewer CVEs reported by scanners and less for an attacker to use if the application is compromised.
Frequently Asked Questions
What is a multi-stage Docker build?
It is a Dockerfile with several FROM instructions, each starting a stage. Earlier stages compile and test the application with full toolchains, and the final stage starts from a small runtime image and copies in only the built artifacts with COPY –from. Only the final stage becomes the image.
How much smaller do images get with multi-stage builds?
It depends on the language. Statically compiled Go services commonly go from hundreds of megabytes to a size close to the binary itself. Java services drop the JDK and build caches, and Node and Python services drop dev dependencies and compilers, often halving the image or better.
Can I build only one stage of a multi-stage Dockerfile?
Yes. docker build –target STAGE_NAME stops at that stage. With BuildKit, stages that the target does not depend on are skipped, which makes one Dockerfile practical for dev, test and production images.
Do intermediate stages end up in the final image?
No. Only the layers of the final or targeted stage are part of the image. Intermediate stages are kept in the build cache to speed up later builds but are not pushed or pulled with the image.
Build fat, ship thin
Multi-stage builds remove the trade-off between a convenient build environment and a lean runtime. Give the build stage every tool it wants, give the runtime stage only the artifact and what it needs to run, and choose that runtime base carefully, which is exactly the decision covered in Alpine, slim or distroless. For the full reference, see the multi-stage builds guide and the Docker build best practices guide. Related reading on this site: build cache and .dockerignore and image scanning.
Originally posted on 21 March 2023 and post last modified on 21 March 2023