Multi-stage builds concept in Docker - Time & Space Complexity
We want to understand how the time to build a Docker image changes when using multi-stage builds.
How does adding more stages affect the total build time?
Analyze the time complexity of the following Dockerfile snippet using multi-stage builds.
FROM node:18 AS builder
WORKDIR /app
COPY package.json .
RUN npm install
COPY . .
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 take time.
- Primary operation: Running
npm installandnpm run buildin the builder stage. - How many times: Each command runs once per build, but the build stage can be cached.
The build time grows mainly with the size of the source code and dependencies.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 files | Short install and build time |
| 100 files | Longer install and build time |
| 1000 files | Much longer install and build time |
Pattern observation: Build time increases roughly with the amount of code and dependencies.
Time Complexity: O(n)
This means the build time grows roughly in direct proportion to the size of the input code and dependencies.
[X] Wrong: "Adding more stages always multiplies the build time by the number of stages."
[OK] Correct: Each stage runs only once and can reuse cached results, so build time depends mostly on the largest stage, not the number of stages.
Understanding how build time scales with input helps you explain Docker build efficiency and caching in real projects.
What if we added a third stage that runs tests after the build? How would the time complexity change?