Squashing layers in Docker - Time & Space Complexity
When building Docker images, squashing layers combines multiple steps into one. This affects how the build time grows as you add more steps.
We want to see how the time to build changes when squashing layers in Docker.
Analyze the time complexity of the following Dockerfile snippet using layer squashing.
FROM ubuntu:latest
RUN apt-get update && apt-get install -y curl
RUN curl -o file.txt http://example.com/file.txt
RUN echo "Hello World" > /hello.txt
RUN rm -rf /var/lib/apt/lists/*
This Dockerfile has multiple RUN commands that create separate layers. Squashing merges these layers into one.
Look for repeated steps that add layers during build.
- Primary operation: Each RUN command creates a new layer.
- How many times: Number of RUN commands equals number of layers before squashing.
As you add more RUN commands, the build time grows roughly with the number of layers.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | Build time for 10 layers |
| 100 | Build time for 100 layers |
| 1000 | Build time for 1000 layers |
Pattern observation: More layers mean more steps to process, so build time grows linearly with layers.
Time Complexity: O(n)
This means build time grows in direct proportion to the number of layers or RUN commands.
[X] Wrong: "Squashing layers makes build time constant no matter how many commands there are."
[OK] Correct: Squashing reduces the number of layers but each command still runs, so build time still grows with the number of commands.
Understanding how Docker build time grows helps you explain trade-offs in image size and build speed. This skill shows you can think about efficiency in real projects.
What if we combined all RUN commands into a single RUN command without squashing? How would the time complexity change?