Building images with docker build - Time & Space Complexity
When building Docker images, it's important to understand how the time to build grows as the image instructions increase.
We want to know how the build time changes when we add more steps or files.
Analyze the time complexity of the following Dockerfile snippet.
FROM python:3.12-slim
COPY requirements.txt /app/
RUN pip install -r /app/requirements.txt
COPY src/ /app/src/
RUN python /app/src/setup.py install
CMD ["python", "/app/src/main.py"]
This Dockerfile builds an image by copying files and running commands to install dependencies and set up the app.
Look for steps that repeat or scale with input size.
- Primary operation: Running commands like
pip installand copying files. - How many times: Each RUN or COPY runs once, but the time depends on the number of files or packages.
As the number of files or packages grows, the time to copy or install grows roughly in proportion.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 files/packages | Short time to copy and install |
| 100 files/packages | About 10 times longer to copy and install |
| 1000 files/packages | About 100 times longer to copy and install |
Pattern observation: The build time grows roughly linearly with the number of files or packages processed.
Time Complexity: O(n)
This means the build time increases roughly in direct proportion to the number of files or packages involved.
[X] Wrong: "Adding more files won't affect build time much because Docker caches layers."
[OK] Correct: While caching helps, the first build or changes to files still require copying and processing all those files, so build time grows with input size.
Understanding how build time grows helps you explain trade-offs in image design and optimization clearly and confidently.
"What if we split the Dockerfile into multiple smaller images and build them separately? How would the time complexity change?"