multi-stage-builds.md
| source_path | references/multi-stage-builds.md |
|---|---|
| source_sha256 | e89dd46aacaceef1c77bf376c9411fe261dc6832938a3dfa3a88bef4d79f2b8a |
| source_url | https://github.com/docker/skills/blob/ce4693b88722334625780ca8e9d54201b2d96f6d/skills/docker-build-strategies/references/multi-stage-builds.md |
| supporting_skill_id | 40167 |
| upstream_revision | ce4693b88722334625780ca8e9d54201b2d96f6d |
Multi-Stage Build Patterns
Multi-stage builds separate build-time toolchains from the runtime image. Every language has a common pattern.
General structure
# syntax=docker/dockerfile:1
# Stage 1: build
FROM <sdk-image> AS build
WORKDIR /src
RUN --mount=type=bind,source=<dependency-manifest>,target=<dependency-manifest> \
<install-dependencies>
COPY . .
RUN <compile-or-bundle>
# Stage 2: runtime
FROM <minimal-base> AS runtime
WORKDIR /app
COPY --from=build --chown=appuser:appgroup /src/<artifact> .
USER appuser
ENTRYPOINT ["./artifact"]
Go
Go produces static binaries, so the runtime stage can use scratch or distroless.
# syntax=docker/dockerfile:1
FROM golang:1.23-alpine AS build
WORKDIR /src
RUN --mount=type=bind,source=go.mod,target=go.mod \
--mount=type=bind,source=go.sum,target=go.sum \
--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 \
CGO_ENABLED=0 go build -ldflags="-s -w" -o /app/server ./cmd/server
FROM gcr.io/distroless/static-debian12:nonroot AS runtime
WORKDIR /app
COPY --from=build --link /app/server .
USER nonroot:nonroot
EXPOSE 8080
ENTRYPOINT ["./server"]
Key points:
- Use
CGO_ENABLED=0for a fully static binary when cgo is not needed. - Use
-ldflags="-s -w"to strip debug symbols and reduce binary size. - Cache both
/go/pkg/mod(downloaded modules) and/root/.cache/go-build(compilation cache). - Bind-mount
go.mod/go.suminto thego mod downloadstep instead ofCOPY-ing them;go mod downloadalone doesn't rewrite them. The full sourceCOPY . .that follows still brings them into the image for the build step. - Distroless static images include a built-in
nonrootuser. - For
GOPRIVATEmodules fetched via Git SSH, use--mount=type=sshinstead of baking keys or tokens. Populateknown_hostsinside the sameRUN, pair the git-config rewrite with the download so the config does not persist into later stages, and setGOPRIVATEinline sogo mod downloadskips the public proxy and checksum database (GOPRIVATEimpliesGONOSUMDBandGONOPROXY):
Invoke withRUN --mount=type=ssh \ --mount=type=cache,target=/go/pkg/mod \ mkdir -p -m 0700 /root/.ssh && \ ssh-keyscan -t ed25519 github.com >> /root/.ssh/known_hosts && \ git config --global url."[email protected]:".insteadOf "https://github.com/" && \ GOPRIVATE="github.com/your-org/*" go mod downloaddocker buildx build --ssh default ., which forwards the SSH agent of the shell that runs the build. TheRUN --mount=type=sshstep can use every key thatssh-add -llists. To expose only this build's key, runssh-agent bashin an interactive terminal, thenssh-add <key-file>, and run the build in that shell. To pass an unencrypted key file directly without an agent, use--ssh default=<key-file>; BuildKit rejects passphrase-protected keys in this form.
Node.js
Node.js applications require the Node runtime, so use a slim base for the runtime stage.
# syntax=docker/dockerfile:1
FROM node:22-alpine AS deps
WORKDIR /src
RUN --mount=type=bind,source=package.json,target=package.json \
--mount=type=bind,source=package-lock.json,target=package-lock.json \
--mount=type=secret,id=npmrc,target=/root/.npmrc,required=false \
--mount=type=cache,target=/root/.npm \
npm ci --omit=dev
FROM node:22-alpine AS build
WORKDIR /src
RUN --mount=type=bind,source=package.json,target=package.json \
--mount=type=bind,source=package-lock.json,target=package-lock.json \
--mount=type=secret,id=npmrc,target=/root/.npmrc,required=false \
--mount=type=cache,target=/root/.npm \
npm ci
COPY . .
RUN npm run build
FROM node:22-alpine AS runtime
WORKDIR /app
RUN addgroup --system --gid 1001 appgroup && \
adduser --system --uid 1001 --ingroup appgroup appuser
COPY --from=deps --chown=appuser:appgroup /src/node_modules ./node_modules
COPY --from=build --chown=appuser:appgroup /src/dist ./dist
COPY --from=build --chown=appuser:appgroup /src/package.json .
USER appuser
EXPOSE 3000
ENTRYPOINT ["node", "dist/index.js"]
Invoke with the registry credential mounted only during npm ci:
docker buildx build --secret id=npmrc,src=<path-to-.npmrc> .
Key points:
- Use a separate
depsstage that installs only production dependencies (--omit=dev). - Use a
buildstage with all dependencies for compilation/bundling. - Copy production
node_modulesfrom thedepsstage, not thebuildstage. - Bind-mount
package.json/package-lock.jsonintonpm ciinstead ofCOPY-ing them —npm cinever writes the lockfile back. UseCOPYinstead if the install command can mutate it (e.g.npm installwithout a matching lockfile). - Never
COPY .npmrc— registry credentials must be mounted with--mount=type=secret, not copied into a layer. - If the project uses a bundler that produces a standalone output (e.g., Next.js standalone mode), copy only the standalone output and skip
node_modulesentirely.
Python
Python applications use a virtual environment to isolate dependencies. Copy the venv into the runtime stage.
# syntax=docker/dockerfile:1
FROM python:3.13-slim AS build
WORKDIR /src
RUN python -m venv /opt/venv
ENV PATH="/opt/venv/bin:$PATH"
RUN --mount=type=bind,source=requirements.txt,target=requirements.txt \
--mount=type=secret,id=pip-conf,target=/etc/pip.conf,required=false \
--mount=type=cache,target=/root/.cache/pip \
pip install --no-compile -r requirements.txt
COPY . .
FROM python:3.13-slim AS runtime
WORKDIR /app
RUN addgroup --system --gid 1001 appgroup && \
adduser --system --uid 1001 --ingroup appgroup appuser
COPY --from=build --chown=appuser:appgroup /opt/venv /opt/venv
COPY --from=build --chown=appuser:appgroup /src /app
ENV PATH="/opt/venv/bin:$PATH"
USER appuser
EXPOSE 8000
ENTRYPOINT ["python", "-m", "uvicorn", "main:app", "--host", "0.0.0.0"]
Key points:
- Build the virtual environment in the build stage and copy it whole into the runtime stage.
- Set
PATHto use the venv in both stages. - Use
--no-compileduring pip install to skip.pycgeneration (Python will compile at first import). - Bind-mount
requirements.txtinto thepip installstep instead ofCOPY-ing it —pip install -rdoesn't write the file back. - For Poetry or PDM projects, export to
requirements.txtfirst or use the tool's built-in export. - For private package indexes, pass
pip.confvia--mount=type=secret,id=pip-conf,target=/etc/pip.confinstead ofCOPY pip.conf(which would leak into a layer). Invoke withdocker buildx build --secret id=pip-conf,src=<path-to-pip.conf> .; the user's pip config usually lives at~/.config/pip/pip.conf(XDG path, pip ≥ 19.1) or the legacy~/.pip/pip.conf.
Java
Java applications compile to JARs. Use a JDK for building and a JRE for runtime.
# syntax=docker/dockerfile:1
FROM eclipse-temurin:21-jdk-alpine AS build
WORKDIR /src
COPY pom.xml .
COPY .mvn .mvn
COPY mvnw .
RUN --mount=type=cache,target=/root/.m2 \
--mount=type=secret,id=maven-settings,target=/root/.m2/settings.xml,required=false \
./mvnw dependency:go-offline -B
COPY src ./src
RUN --mount=type=cache,target=/root/.m2 \
--mount=type=secret,id=maven-settings,target=/root/.m2/settings.xml,required=false \
./mvnw package -DskipTests -B
FROM eclipse-temurin:21-jre-alpine AS runtime
WORKDIR /app
RUN addgroup --system --gid 1001 appgroup && \
adduser --system --uid 1001 -G appgroup appuser
COPY --from=build --chown=appuser:appgroup /src/target/*.jar app.jar
USER appuser
EXPOSE 8080
ENTRYPOINT ["java", "-jar", "app.jar"]
Key points:
- Use
dependency:go-offline(Maven) or a Gradle dependency resolution task to cache dependencies before copying source. - Cache the
.m2or.gradledirectory with a cache mount. - Use a JRE image (not JDK) for the runtime stage.
- For GraalVM native images, the runtime stage can use
scratchor distroless, similar to Go. - For private Maven repositories, pass
~/.m2/settings.xmlvia--mount=type=secret,id=maven-settings,target=/root/.m2/settings.xmlinstead ofCOPY settings.xml. Invoke withdocker buildx build --secret id=maven-settings,src=<path-to-settings.xml> ..
When to add more stages
Add intermediate stages when:
- You need separate dependency resolution (production vs. dev dependencies, as in Node.js).
- You want to run tests in a dedicated stage without polluting the build or runtime stages.
- You are generating assets (CSS, static files) in a separate tool from the main application build.
Name every stage. Never rely on numeric stage indices.
Children
No children yet.
Like how this is organised?
Build your own Memory tree on knowen.md: notes, decisions and tasks in one connected markdown graph, shared with your team and your AI agents.