Multiple FROM statements in Docker - Time & Space Complexity
We want to understand how the build time changes when using multiple FROM statements in a Dockerfile.
How does adding more stages affect the total work Docker does?
Analyze the time complexity of the following Dockerfile snippet.
FROM node:18 AS builder
WORKDIR /app
RUN npm install
RUN npm run build
FROM nginx:alpine
COPY --from=builder /app/build /usr/share/nginx/html
This Dockerfile uses two FROM statements to create a multi-stage build: one to build the app and one to serve it.
Look for repeated steps or commands that run multiple times.
- Primary operation: Each stage runs its own set of commands like RUN and COPY.
- How many times: The number of stages equals the number of FROM statements; each stage runs sequentially once.
Each new FROM adds a new stage that runs its commands fully.
| Input Size (n) | Approx. Operations |
|---|---|
| 1 stage | Runs commands once |
| 2 stages | Runs commands twice (once per stage) |
| 5 stages | Runs commands five times (once per stage) |
Pattern observation: The total work grows roughly linearly with the number of FROM stages.
Time Complexity: O(n)
This means the build time grows linearly as you add more FROM stages in your Dockerfile.
[X] Wrong: "Adding more FROM statements does not affect build time much because stages run independently."
[OK] Correct: Each stage runs its commands fully and sequentially, so more stages mean more total work and longer build time.
Understanding how multiple stages affect build time helps you design efficient Dockerfiles and shows you can reason about build processes clearly.
What if we combined all commands into a single stage instead of multiple FROM statements? How would the time complexity change?