RUN instruction for executing commands in Docker - Time & Space Complexity
We want to understand how the time it takes to run commands inside a Docker image grows as we add more commands.
How does adding more commands affect the total build time?
Analyze the time complexity of the following Dockerfile snippet using RUN instructions.
FROM ubuntu:latest
RUN apt-get update && apt-get install -y curl
RUN echo "Hello World"
RUN mkdir /app
RUN touch /app/file1 /app/file2 /app/file3
This snippet runs several commands one after another during the image build.
Look for repeated command executions or loops.
- Primary operation: Each RUN instruction executes commands sequentially.
- How many times: The number of RUN instructions equals the number of command groups run.
As you add more RUN instructions, the total build time grows roughly in direct proportion.
| Input Size (n) | Approx. Operations |
|---|---|
| 2 RUN commands | 2 command executions |
| 5 RUN commands | 5 command executions |
| 10 RUN commands | 10 command executions |
Pattern observation: Doubling the number of RUN instructions roughly doubles the total execution time.
Time Complexity: O(n)
This means the total time grows linearly with the number of RUN commands you add.
[X] Wrong: "Adding more RUN commands won't affect build time much because they run fast."
[OK] Correct: Each RUN command adds extra steps and time, so more commands mean longer builds.
Understanding how build steps add up helps you write efficient Dockerfiles and shows you think about performance in real projects.
"What if we combined multiple commands into a single RUN instruction? How would the time complexity change?"