Multi-stage for different environments in Docker - Time & Space Complexity
We want to understand how the build time changes when using multi-stage Dockerfiles for different environments.
How does the number of build steps grow as we add more stages or complexity?
Analyze the time complexity of the following multi-stage Dockerfile snippet.
FROM node:18 AS base
WORKDIR /app
COPY package.json .
RUN npm install
FROM base AS development
COPY . .
CMD ["npm", "run", "dev"]
FROM base AS production
COPY . .
RUN npm run build
CMD ["npm", "start"]
This Dockerfile builds two environments: development and production, sharing common steps in the base stage.
Look for repeated steps or commands that run multiple times.
- Primary operation: Running
npm installin the base stage. - How many times: Once, shared by both development and production stages.
As the number of stages or environment setups increases, the build time grows mostly by the unique steps per stage.
| Input Size (n) | Approx. Operations |
|---|---|
| 2 stages | Base install + 2 environment-specific steps |
| 5 stages | Base install + 5 environment-specific steps |
| 10 stages | Base install + 10 environment-specific steps |
Pattern observation: The shared base step runs once, while unique steps add linearly with the number of stages.
Time Complexity: O(n)
This means build time grows linearly with the number of environment stages you add.
[X] Wrong: "Adding more stages will multiply the entire build time by the number of stages."
[OK] Correct: Because shared steps like npm install run only once and are reused, not repeated for each stage.
Understanding how multi-stage builds scale helps you explain efficient Dockerfile design and build optimization in real projects.
What if we duplicated the npm install step in each stage instead of sharing it? How would the time complexity change?