Targeting specific stages in Docker - Time & Space Complexity
When building Docker images with multiple stages, it's important to know how targeting a specific stage affects build time.
We want to understand how the build time changes as the number of stages grows.
Analyze the time complexity of this multi-stage Dockerfile snippet.
FROM node:18 AS base
RUN npm install
FROM base AS build
RUN npm run build
FROM build AS test
RUN npm test
FROM build AS final
CMD ["node", "app.js"]
This Dockerfile has four stages. We can target any stage to build only up to that point.
Look for repeated steps or commands that run multiple times.
- Primary operation: Running each stage's commands sequentially during build.
- How many times: Once per stage up to the targeted stage.
As the number of stages increases, building a specific stage requires running all previous stages too.
| Number of Stages (n) | Approx. Commands Run |
|---|---|
| 2 | 2 |
| 4 | 4 |
| 10 | 10 |
Pattern observation: The build time grows roughly in direct proportion to the number of stages built.
Time Complexity: O(n)
This means the build time grows linearly with the number of stages you build up to.
[X] Wrong: "Building a later stage only runs that stage's commands."
[OK] Correct: Docker must run all earlier stages first to prepare the environment, so build time includes all previous stages.
Understanding how build time scales with stages helps you design efficient Dockerfiles and explain your choices clearly in real projects.
"What if Docker cached some stages? How would that affect the time complexity when targeting a specific stage?"