Docker Tutorial 0/48 lessons ~6 min read Lesson 20

    Multi-Stage Builds

    Multi-stage builds let you use one image to compile/build and a smaller image to run — the build tools never ship to production.

    Course progress0%
    Focus
    15 guided sections
    Practice signal
    Examples included
    Career prep
    Interview Q&A included

    Introduction

    Multi-stage builds let you use one image to compile/build and a smaller image to run — the build tools never ship to production. Final images go from 1 GB to <100 MB.

    Purpose of this lesson

    This lesson teaches Multi-Stage Builds as an engineering decision: what problem it solves, when to use it, how to implement it safely, and what signals tell you it is failing.

    Understanding the topic

    Use this whenever you create or review an application image. Build quality affects deploy speed, security exposure, reproducibility, CI cost, and how quickly engineers can diagnose failures.

    Core concepts to understand:

    • Multiple FROM statements; later stages can COPY --from=<stage>.
    • Name stages with AS for clarity.
    • Final image only contains what you copy into it.
    • Works for any language: Go, Java, Node, Python, Rust.

    Visual explanation

    Architecture or command flow to keep in mind:

    dockerfile
    # Stage 1 — build
    FROM node:20-alpine AS build
    WORKDIR /app
    COPY package*.json ./
    RUN npm ci
    COPY . .
    RUN npm run build
    # Stage 2 — runtime
    FROM nginx:1.27-alpine
    COPY --from=build /app/dist /usr/share/nginx/html
    EXPOSE 80
    CMD ["nginx", "-g", "daemon off;"]

    Step-by-step explanation

    1. Start from a trusted, pinned base image and document why it fits the runtime.
    2. Order Dockerfile instructions from least-changing dependency metadata to most-changing source files so the cache stays useful.
    3. Build locally with BuildKit, inspect layers with docker history, and run the image with the same command CI will use.
    4. Test shutdown behavior, health checks, non-root execution, and runtime configuration before pushing the image.
    5. Tag with an immutable version or git SHA, scan the image, and promote the same artifact through environments.

    Informative example

    Use the example below as a working baseline, then verify the runtime behavior instead of assuming the command or file is correct.

    dockerfile
    # Stage 1 — build
    FROM node:20-alpine AS build
    WORKDIR /app
    COPY package*.json ./
    RUN npm ci
    COPY . .
    RUN npm run build
    # Stage 2 — runtime
    FROM nginx:1.27-alpine
    COPY --from=build /app/dist /usr/share/nginx/html
    EXPOSE 80
    CMD ["nginx", "-g", "daemon off;"]

    A production-minded check usually includes docker ps, docker logs, docker inspect, and one validation from outside the container such as curl, a database connection, or a registry pull.

    bash
    # Verification loop for Multi-Stage Builds
    docker ps -a
    docker logs --tail=100 <container-name>
    docker inspect <container-or-image-name>
    docker system df

    Real-world use

    A typical React/Vite app drops from ~900 MB (node + sources + deps) to ~25 MB (nginx + built assets) with one multi-stage build.

    Enterprise use cases

    In a mature engineering organization, Multi-Stage Builds is documented as a repeatable pattern with approved base images, ownership labels, CI checks, security expectations, rollback notes, and troubleshooting commands. The difference between a tutorial and production practice is that every container decision must be observable, reviewable, and reversible.

    Best practices

    • Always multi-stage for compiled languages.
    • Use the smallest possible runtime base (alpine, distroless).
    • Name your stages — easier to read in CI logs.

    Common mistakes

    • Forgetting --from and shipping the build stage to prod.

    Debugging tips

    • Use docker build --progress=plain when BuildKit output hides the failing build step.
    • Run the image with a temporary shell or overridden command to inspect files, users, environment, and entrypoint behavior.
    • Check docker history for accidental secrets, unexpectedly large layers, and cache-busting instructions.

    Optimization strategies

    • Copy dependency lock files before source files so dependency installation remains cached during code edits.
    • Use multi-stage builds to keep compilers, package managers, test tools, and source maps out of runtime images.
    • Adopt BuildKit cache mounts for npm, Maven, pip, Go, or cargo dependencies in CI.

    Advanced interview questions

    Interview Prep

    Practice concise answers, then expand each card for the explanation.

    3 questions
    1QuestionWhy use multi-stage builds?+

    Answer

    A strong answer for Multi-Stage Builds should define the concept, explain the Docker component involved, give one real use case, and name at least one failure mode plus the command you would use to investigate it.
    2QuestionHow do you copy from a previous stage?+

    Answer

    A strong answer for Multi-Stage Builds should define the concept, explain the Docker component involved, give one real use case, and name at least one failure mode plus the command you would use to investigate it.
    3QuestionWhat's a distroless image?+

    Answer

    A strong answer for Multi-Stage Builds should define the concept, explain the Docker component involved, give one real use case, and name at least one failure mode plus the command you would use to investigate it.

    Hands-on exercise

    Create a small lab for Multi-Stage Builds: run the example, inspect the created Docker object, intentionally introduce one mistake, and record the command that reveals the failure. The goal is not just to make the happy path work; it is to build operational reflexes.

    bash
    # Hands-on lab scaffold
    mkdir -p docker-multi-stage-builds-lab
    cd docker-multi-stage-builds-lab
    # Add the Dockerfile, compose.yml, or command from this lesson.
    # Then run one happy-path test and one broken-path test.
    docker version
    docker info
    docker system df

    Summary

    Multi-Stage Builds matters because Docker is not only a packaging tool; it is a runtime, build, networking, storage, and delivery workflow. Treat each lesson as a production habit: make it repeatable, inspectable, secure, and easy to debug.

    Ready to mark this lesson complete?Track your journey across the entire course.