A single-stage Dockerfile for a Node.js application can easily produce an image over 1 GB: the full node base image, every devDependency, TypeScript compilers, test fixtures, and source files all ship to production. Docker multi-stage builds fix this with a simple idea — use one stage as a factory that builds your application, then copy only the finished artifacts into a second, minimal stage. The final image contains the application and its runtime dependencies, and nothing else.

The payoff is concrete: smaller images pull faster in CI/CD and Kubernetes, use less registry storage, and present a smaller attack surface because compilers and build tools never reach production. In this guide you will learn how docker multi-stage builds work, build optimized Node.js and Python images step by step, compare the sizes, and avoid the most common mistakes. For broader Dockerfile hygiene, pair this with our Dockerfile best practices.
Prerequisites
- Docker Engine 20.10 or newer installed (
docker --versionto check). Multi-stage builds have been stable since Docker 17.05, so any modern install works. - Basic familiarity with writing a Dockerfile and running
docker build. - A sample Node.js or Python project to containerize — or follow along with the examples below.
How Docker Multi-Stage Builds Work
A multi-stage Dockerfile contains two or more FROM instructions. Each FROM starts a new stage that can be named with AS:
FROM node:22 AS builder
# ... build steps happen here ...
FROM node:22-slim AS production
COPY --from=builder /app/dist ./dist
# ... only runtime setup here ...
Docker executes every stage but ships only the last stage as the final image. Intermediate stages are discarded after their outputs are copied out with COPY --from=<stage>. You can reference a stage by its name (builder) or by its zero-based index, but names are far more readable.
You can also build a single stage for debugging without running the whole pipeline:
docker build --target builder -t my-app:builder .
This is invaluable when a build step fails — you get a shell-able image of exactly the stage that broke. The official Docker documentation on multi-stage builds covers the full syntax if you want to go deeper.
Node.js Multi-Stage Build Example
Here is a production-ready multi-stage Dockerfile for a Node.js application that compiles TypeScript to dist/. The build stage installs everything including devDependencies; the runtime stage installs only production dependencies on a slim base:
# ---------- Stage 1: build ----------
FROM node:22 AS builder
WORKDIR /app
# Copy dependency manifests first for better layer caching
COPY package.json package-lock.json ./
RUN npm ci
# Copy source and compile
COPY . .
RUN npm run build
RUN npm prune --omit=dev
# ---------- Stage 2: production runtime ----------
FROM node:22-slim AS production
WORKDIR /app
ENV NODE_ENV=production
# Copy only what the app needs to run
COPY --from=builder /app/dist ./dist
COPY --from=builder /app/node_modules ./node_modules
COPY --from=builder /app/package.json ./package.json
# Drop privileges: never run as root in production
RUN groupadd -r appgroup && useradd -r -g appgroup appuser
USER appuser
EXPOSE 3000
CMD ["node", "dist/server.js"]
Why this layout works: package.json and package-lock.json change far less often than application code, so copying them first keeps the expensive npm ci layer cached across rebuilds. npm prune --omit=dev in the builder strips devDependencies after the compile step, so the runtime stage never sees TypeScript, linters, or test runners. The node:22-slim base is a fraction of the size of the full node:22 image.
Build it and check the size:
docker build -t my-node-app .
docker images my-node-app
A typical Express + TypeScript app drops from roughly 1.1 GB with a naive single-stage Dockerfile to about 200–250 MB with this multi-stage version.
Python Multi-Stage Build Example
Python apps benefit the same way, especially when dependencies need compilation (C extensions for packages like psycopg, cryptography, or numpy). The builder stage carries the compilers; the runtime stage carries only the installed wheels:
# ---------- Stage 1: builder ----------
FROM python:3.12 AS builder
WORKDIR /app
COPY requirements.txt .
# Install into a user-local directory so the output is easy to copy
RUN pip install --user --no-cache-dir -r requirements.txt
# ---------- Stage 2: production runtime ----------
FROM python:3.12-slim AS production
WORKDIR /app
# Bring over the installed packages, nothing else from the builder
COPY --from=builder /root/.local /root/.local
ENV PATH=/root/.local/bin:$PATH
ENV PYTHONUNBUFFERED=1
COPY . .
RUN useradd -m -u 1000 appuser
USER appuser
EXPOSE 5000
CMD ["python", "app.py"]
Two notes on this pattern. First, pip install --user puts everything under /root/.local, which makes the COPY --from=builder a single clean operation — no hunting through site-packages paths. Second, python:3.12-slim is roughly 50 MB versus over 1 GB for the full python:3.12 image, so the win is dramatic even before you consider the removed compilers. If you use a virtual environment instead of --user, copy the whole venv directory and set PATH to its bin — the mechanics are identical.
The COPY –from Syntax, Explained
COPY --from is the glue of docker multi-stage builds. Its forms:
COPY --from=builder /app/dist ./dist— copy from a named earlier stage.COPY --from=0 /app/dist ./dist— copy from a stage by index (fragile; prefer names).COPY --from=builder --chown=appuser:appgroup /app/dist ./dist— set ownership during the copy, avoiding a separateRUN chownlayer.
You can also copy from an external image without defining a stage at all — handy for pulling a binary out of a published image:
COPY --from=composer:2 /usr/bin/composer /usr/bin/composer
One subtlety: each COPY --from creates a new layer in the final image, so copying ten separate directories costs ten layers. Group related files or copy a parent directory when you can, and remember that files copied from a builder stage carry their original permissions — use --chown or --chmod if the runtime user differs.
Build Cache Tips for Docker Multi-Stage Builds
Multi-stage builds are only fast if Docker can reuse cached layers. Follow these ordering rules:
- Copy dependency manifests before source code.
package.json/requirements.txtfirst,RUNthe install, thenCOPY . .. A code change then rebuilds only the layers after the install. - Put the least-frequently-changing instructions earliest. Base image choice, system package installs, and user creation belong at the top of each stage.
- Use BuildKit cache mounts for package managers. With BuildKit enabled,
RUN --mount=type=cache,target=/root/.npm npm cikeeps the npm cache between builds without bloating the image. - Keep a
.dockerignorefile. Excludingnode_modules,.git, test fixtures, and local virtual environments prevents cache invalidation from files you never meant to copy. - Do not
COPY . .before installing dependencies. This is the single most common cache-killer: every keystroke invalidates the dependency layer and forces a full reinstall.
Comparing Image Sizes
Numbers make the case better than adjectives. Build both variants of the same application and compare:
docker build -t my-app:single -f Dockerfile.single .
docker build -t my-app:multi -f Dockerfile.multi .
docker images my-app --format "table {{.Tag}}\t{{.Size}}"
Typical results for a small Node.js API:
- Single-stage (
node:22, all dependencies, source, build tools): ~1.1 GB - Multi-stage (
node:22-slimruntime, pruned dependencies): ~220 MB
That is roughly an 80% reduction. In a Kubernetes cluster pulling images to dozens of nodes, or a CI pipeline pushing on every commit, the time and bandwidth savings compound quickly. Smaller images also mean fewer installed packages for vulnerability scanners to flag — a real security benefit, not just a cosmetic one.
Troubleshooting Common Multi-Stage Build Mistakes
- “COPY failed: no such file or directory” with
--from. The source path must exist in the named stage. Stage names are case-sensitive, and the path is absolute inside that stage’s filesystem — double-check both. - Runtime errors about missing modules. You probably copied the built output but forgot
node_modules, or pruned production dependencies that are actually needed at runtime. Verify withdocker run --rm my-app ls node_modules. - Native modules built for the wrong libc. If the builder is Debian-based (
node:22) and the runtime is Alpine (node:22-alpine), compiled addons built against glibc will fail on musl. Keep builder and runtime on the same libc family — easiest is using-slimvariants of the same Debian base for both stages. - Permission denied as non-root user. Files copied from the builder are owned by root. Either add
--chownto theCOPY --fromor create the user and set ownership before switching withUSER. - Secrets baked into the image. Build arguments and copied
.envfiles persist in image layers. Pass secrets at runtime via environment variables or a secrets manager — neverCOPYthem in, in any stage. - Build is slow despite caching. Check layer order (manifests before source), add a
.dockerignore, and confirm BuildKit is active (DOCKER_BUILDKIT=1) so cache mounts work.
Once your optimized image builds cleanly, the next step is shipping it — see our walkthrough on how to push a Docker image to Docker Hub.
Conclusion
Docker multi-stage builds turn the Dockerfile from a single linear script into a small pipeline: a build stage with all the tools, and a runtime stage with only the results. You have seen the pattern applied to Node.js and Python, learned the COPY --from mechanics, tuned the build cache, and measured an ~80% size reduction.
Adopt this as your default for every production Dockerfile. Start from the examples above, adjust the copied paths to your project’s layout, keep builder and runtime on the same OS family, and always run the final image as a non-root user. Your registries, your CI pipelines, and your security scanners will all thank you.