liveBook · Manning

Multistage build

As explained in Fast by Default

A multi-stage build uses separate image-building and runtime stages so that only runtime artifacts are copied into the final image.

A multistage build separates image construction from runtime delivery. Build stages retain compilers, package managers, development headers, and toolchains; the final stage contains only application code and runtime dependencies. section 8.2.1

Implement the pattern with separate FROM statements: build in a full image, then copy required artifacts into a smaller runtime image. Copying only needed files also excludes tests, documentation, and development configuration. section 8.2.1

Apply the same structure across language ecosystems:

  • Compile Go code in a golang image and copy the binary into a minimal image. section 8.2.1
  • Build Node.js applications in a full node image, then copy built output into node-slim without npm, devDependencies, or build scripts. section 8.2.1
  • Build Java and .NET applications in JDK or SDK images, then copy the JAR or published output into runtime-only images. section 8.2.1

Checkout API

A checkout API replaced a 1.3GB production layer by compiling native Python extensions in python:3.11, then copying installed packages and application code into python:3.11-slim. section 8.2.1

Listing 8.8 A multi-stage Dockerfile for removing build tools from production
# Build stage with all the tools
FROM python:3.11 AS builder                     #A
WORKDIR /app
COPY requirements.txt ./
RUN pip install --user -r requirements.txt \
    && rm -rf /root/.cache/pip                  #B
 
 
# Production stage with only what's needed
FROM python:3.11-slim                           #C
WORKDIR /app
COPY --from=builder /root/.local /root/.local   #D
COPY . .                                        #E
ENV PATH=/root/.local/bin:$PATH
CMD ["python", "app.py"]

Inspect a complete Dockerfile pattern with a tool-rich builder stage, a slim production stage, and COPY --from artifact transfer. section 8.2.1

How Fast by Default covers it

How deep it goes
Explains Dockerfile stages, artifact copying, and language-specific applications without detailing image-layer internals.
Examples
Uses a checkout API, Python native extensions, Go binaries, Node.js output, Java JARs, and .NET published output.
What it assumes
Assumes familiarity with Dockerfiles, FROM statements, application dependencies, and container image stages.
What you can do after
Builds smaller runtime images by transferring only required artifacts from a full build environment.
How it connects
Connects Dockerfiles with container images, build tools, runtime dependencies, base images, and image size.

Also explained in

Compare how 3 books explain multistage build →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Fast by Default. The section links point to the parts of the book it draws on.