Named build stages in Docker - Time & Space Complexity
We want to understand how the time to build a Docker image changes when using named build stages.
Specifically, how does the build time grow as the number of stages or commands increases?
Analyze the time complexity of the following Dockerfile snippet using named build stages.
FROM node:18 AS builder
WORKDIR /app
COPY . .
RUN npm install
RUN npm run build
FROM nginx:alpine
COPY --from=builder /app/build /usr/share/nginx/html
This Dockerfile builds a Node.js app in one stage, then copies the build output to a smaller image in the final stage.
Look for repeated steps or commands that affect build time.
- Primary operation: Running commands like
npm installandnpm run buildinside the builder stage. - How many times: Each command runs once per build stage; no loops or recursion here.
As the number of build stages or commands increases, the total build time grows roughly by adding each command's time.
| Input Size (n) | Approx. Operations |
|---|---|
| 2 stages, 3 commands | 3 command runs + 1 copy |
| 5 stages, 10 commands | 10 command runs + 4 copies |
| 10 stages, 20 commands | 20 command runs + 9 copies |
Pattern observation: Build time grows roughly linearly with the number of commands and stages.
Time Complexity: O(n)
This means build time increases in a straight line as you add more commands or stages.
[X] Wrong: "Using named build stages makes the build time stay the same no matter how many stages there are."
[OK] Correct: Each stage runs its commands fully, so more stages or commands add more work and time.
Understanding how build stages affect build time helps you explain Dockerfile efficiency clearly and shows you can reason about build processes.
"What if we cached the results of some stages? How would that change the time complexity?"