Sub topic 11
Example: Node.js and Python runtime images
This chapter applies multi-stage builds to two interpreted languages. It assumes you can read a Dockerfile, know FROM ... AS and COPY --from, and have a small Node.js or Python app to build. Interpreted languages differ from Go in one important way: the runtime must be in the final image, so the final stage cannot be empty. The goal is to leave behind everything the runtime does not need.
What differs from a compiled language
A Go build produces one static binary, so the final image can be scratch. Node.js and Python programs need an interpreter at runtime, plus their installed dependencies. That changes what the build stage is for.
- Node.js: the build stage installs all dependencies, including dev dependencies such as TypeScript, bundlers and test tools. It then compiles or bundles the source into a
distfolder. The final stage needs only production dependencies anddist. - Python: there is usually no compile step. The build stage exists to install packages, some of which need compilers or header files to build. The final stage needs only the installed packages.
In both cases the pattern is the same: do the heavy work in one stage, then copy a small, well-defined set of artifacts into a slim runtime stage.
Node.js example
This Dockerfile builds a TypeScript or bundled app and runs the compiled output.
FROM node:20 AS build
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build
FROM node:20-slim
WORKDIR /app
ENV NODE_ENV=production
COPY package*.json ./
RUN npm ci --omit=dev
COPY --from=build /app/dist ./dist
USER node
CMD ["node", "dist/index.js"]Walking through the build stage
FROM node:20 AS build starts from the full Debian-based Node image and names the stage build. This image includes compilers and common build tools, which helps when a dependency has a native addon that must be compiled.
COPY package*.json ./ comes before COPY . . on purpose. Docker caches each layer, and a layer is reused only if its inputs are unchanged. The manifest files change rarely, so the npm ci layer stays cached until you add or update a dependency. If you copied all the source first, every code edit would reinstall every package.
npm ci installs exactly what package-lock.json specifies and fails if the lock file and package.json disagree. That makes builds reproducible. It also deletes any existing node_modules first, which is another reason to keep node_modules out of the build context (see the .dockerignore chapter).
RUN npm run build produces the dist folder. Dev dependencies such as the compiler were needed for this step, and nothing after it needs them.
Walking through the runtime stage
FROM node:20-slim starts a new stage from a smaller image. Nothing from the build stage carries over unless you copy it explicitly.
ENV NODE_ENV=production makes many libraries choose production behavior. Setting it before npm ci is harmless here because --omit=dev already excludes dev dependencies.
RUN npm ci --omit=dev installs only production dependencies, reading the same manifest files. This is the second install, and it is the price of a small image. The alternative is to copy node_modules from the build stage and prune it. That avoids a second download but copies dev-only files unless you prune carefully, so the clean install is easier to reason about.
COPY --from=build /app/dist ./dist brings in only the built output.
USER node switches to the unprivileged user that the official Node images already define. CMD ["node", "dist/index.js"] uses the exec form, so Node runs as the main process and receives signals such as SIGTERM directly.
Python example
Python packages install into a directory tree. If you put that tree in a virtual environment at a known path, you can copy the whole directory to another stage.
# syntax=docker/dockerfile:1
FROM python:3.12-slim AS build
WORKDIR /app
RUN python -m venv /opt/venv
ENV PATH="/opt/venv/bin:$PATH"
COPY requirements.txt .
RUN --mount=type=cache,target=/root/.cache/pip pip install -r requirements.txt
FROM python:3.12-slim
ENV PATH="/opt/venv/bin:$PATH"
WORKDIR /app
COPY --from=build /opt/venv /opt/venv
COPY . .
USER nobody
CMD ["python", "app.py"]Walking through the Python build
The first line, # syntax=docker/dockerfile:1, selects the current Dockerfile frontend so that RUN --mount is available. It must be the first line of the file. Cache mounts are covered in detail in a later chapter. Here, it keeps pip's download cache outside the image layers, so repeated builds are faster and the cache adds no size to the image.
python -m venv /opt/venv creates a virtual environment. ENV PATH="/opt/venv/bin:$PATH" puts it first on the path, so pip and python resolve to the environment's copies. This replaces the usual "activate" step, which does not persist between RUN instructions.
COPY requirements.txt . followed by pip install mirrors the Node ordering: the install layer is rebuilt only when requirements.txt changes.
In the final stage, COPY --from=build /opt/venv /opt/venv copies the installed packages. The final stage also uses python:3.12-slim, and this matters. A virtual environment holds symlinks and scripts that point at the interpreter path it was created with. If the runtime stage used a different Python version or a different base distribution, the environment could break. Use the same Python image tag in both stages.
COPY . . copies your application source. It comes after the venv copy, so code edits do not invalidate the package layer.
USER nobody runs the process without root privileges.
When packages need a compiler
Many popular packages ship prebuilt wheels, so pip install needs no compiler. Some do not, and they need gcc and header files at install time. This is where Python multi-stage builds pay off most. Install the compiler in the build stage only:
# syntax=docker/dockerfile:1
FROM python:3.12-slim AS build
RUN apt-get update \
&& apt-get install -y --no-install-recommends build-essential \
&& rm -rf /var/lib/apt/lists/*
RUN python -m venv /opt/venv
ENV PATH="/opt/venv/bin:$PATH"
COPY requirements.txt .
RUN pip install -r requirements.txt
FROM python:3.12-slim
ENV PATH="/opt/venv/bin:$PATH"
WORKDIR /app
COPY --from=build /opt/venv /opt/venv
COPY . .
USER nobody
CMD ["python", "app.py"]The compiler and the apt package lists exist only in the build stage. The final image gets the compiled extension files inside the venv but not the toolchain. If a package links to a system library such as libpq, the matching runtime library, not the development headers, must be installed in the final stage.
Comparing the results
Build the final image and the build stage separately, then compare sizes. The --target flag stops the build at a named stage.
docker build -t myapp:small .
docker build --target build -t myapp:build .
docker image ls myapp
docker history myapp:smallThe build image is typically several times larger than the final one, because it contains the full base image, dev dependencies or compilers, and caches. Exact numbers depend on your app, so measure rather than assume. docker history shows the size each layer adds, which tells you where to look next if the final image is still large.
Common mistakes
| Mistake | Effect | Fix |
|---|---|---|
| `COPY . .` before the dependency install | Every code change reinstalls all packages | Copy manifest files first, install, then copy source |
| Using `npm install` instead of `npm ci` | Builds can differ between runs | Use `npm ci` with a committed lock file |
| Forgetting `--omit=dev` in the runtime stage | Dev dependencies ship in the final image | Use `npm ci --omit=dev` |
| Different Python tags in the two stages | Broken venv or import errors for compiled packages | Use the same tag in both stages |
| Copying the whole build stage with `COPY --from=build /app .` | Source, dev dependencies and tooling leak into the final image | Copy only the specific artifacts |
| Leaving the default `root` user | Compromised process runs with full privileges in the container | Add `USER node` or `USER nobody` |
| Missing `.dockerignore` | Local `node_modules` or `.venv` overwrite installed ones | Ignore local dependency folders |
Choosing between slim and other bases
The examples use -slim images because they keep the Debian C library, so prebuilt packages work without changes. Alpine images are smaller, but they use musl instead of glibc. Python wheels built for glibc generally do not install on Alpine, so pip may compile packages from source, which slows builds and can erase the size gain. For Node, Alpine works for many apps, but native addons can need extra care. Pick Alpine only after testing your own dependencies. Distroless images such as the Node and Python variants have no shell or package manager, which reduces the attack surface but makes debugging harder.
Exercise
A Node.js multi-stage build installs dependencies with npm ci in the build stage and then runs COPY --from=build /app . into a node:20-slim stage. The image is still large and contains TypeScript. What is wrong, and how do you fix it?
Show answer
Copying the whole /app directory brings the dev dependencies in node_modules, the TypeScript source and config files into the final image, so the second stage saves nothing. Instead, run npm ci --omit=dev in the runtime stage (after copying the manifest files) and copy only /app/dist from the build stage with COPY --from=build /app/dist ./dist.
Exercise
Your Python image builds fine, but at startup the app fails with an import error for a package with a compiled extension. The build stage uses python:3.12 and the runtime stage uses python:3.12-slim. Name one likely cause and a fix.
Show answer
The virtual environment was built against a different base image than the one it runs on, so the interpreter path or system libraries it expects may not match, and the compiled extension may need a system library that the slim image lacks. Use the same base image tag in both stages, and install any required runtime libraries (not development headers) in the final stage.
Exercise
Why does the Dockerfile copy package*.json and run the install before COPY . .?
Show answer
Docker reuses a cached layer only when its inputs are unchanged. The manifest files change rarely, so the install layer stays cached across most builds. If the source were copied first, any code edit would invalidate the install layer and reinstall every dependency.