Copying from build stage to final stage in Docker - Time & Space Complexity
When building Docker images with multiple stages, copying files from one stage to another is common.
We want to understand how the time to copy grows as the number or size of files increases.
Analyze the time complexity of this Dockerfile snippet.
FROM node:18 AS build
WORKDIR /app
COPY package.json .
RUN npm install
COPY . .
RUN npm run build
FROM nginx:alpine
COPY --from=build /app/build /usr/share/nginx/html
This copies the build output from the build stage to the final image.
Look for repeated actions that affect time.
- Primary operation: Copying files from the build stage to the final stage.
- How many times: Once per file or directory copied during the COPY command.
The time to copy grows as the number and size of files increase.
| Input Size (number of files) | Approx. Operations (copy actions) |
|---|---|
| 10 | 10 copy operations |
| 100 | 100 copy operations |
| 1000 | 1000 copy operations |
Pattern observation: The copying time grows roughly in direct proportion to the number of files.
Time Complexity: O(n)
This means the time to copy grows linearly with the number of files copied.
[X] Wrong: "Copying from build stage is instant regardless of files."
[OK] Correct: Each file must be copied, so more files take more time.
Understanding how copying scales helps you reason about build times and image size in real projects.
What if we copied a single large file instead of many small files? How would the time complexity change?