Image size and minimal base images in Docker - Time & Space Complexity
We want to understand how the size of a Docker image grows when we choose different base images.
How does the choice of base image affect the total image size as we add more layers?
Analyze the time complexity of the following Dockerfile snippet.
FROM alpine:latest
RUN apk add --no-cache curl
COPY app /app
RUN chmod +x /app/start.sh
CMD ["/app/start.sh"]
This Dockerfile uses a minimal base image and adds a few layers for app setup.
Look for repeated steps that add to image size.
- Primary operation: Each Dockerfile instruction creates a new layer.
- How many times: Four instructions add layers here (FROM, RUN, COPY, RUN).
As we add more instructions, the image size grows roughly by the size of each added layer.
| Input Size (number of layers) | Approx. Image Size |
|---|---|
| 2 | Small (minimal base + 1 layer) |
| 5 | Moderate (minimal base + 4 layers) |
| 10 | Larger (minimal base + 9 layers) |
Pattern observation: Image size grows roughly linearly with the number of layers added.
Time Complexity: O(n)
This means the total image size grows in direct proportion to the number of layers added.
[X] Wrong: "Using a minimal base image always makes the image size constant regardless of added layers."
[OK] Correct: Even with a small base, each added layer increases the image size, so size grows with added instructions.
Understanding how image size grows helps you build efficient containers and shows you think about resource use clearly.
"What if we combined multiple RUN commands into one? How would that affect the image size growth?"