0
0
Dockerdevops~5 mins

RUN instruction for executing commands in Docker - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: RUN instruction for executing commands
O(n)
Understanding Time 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?

Scenario Under Consideration

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.

Identify Repeating Operations

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.
How Execution Grows With Input

As you add more RUN instructions, the total build time grows roughly in direct proportion.

Input Size (n)Approx. Operations
2 RUN commands2 command executions
5 RUN commands5 command executions
10 RUN commands10 command executions

Pattern observation: Doubling the number of RUN instructions roughly doubles the total execution time.

Final Time Complexity

Time Complexity: O(n)

This means the total time grows linearly with the number of RUN commands you add.

Common Mistake

[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.

Interview Connect

Understanding how build steps add up helps you write efficient Dockerfiles and shows you think about performance in real projects.

Self-Check

"What if we combined multiple commands into a single RUN instruction? How would the time complexity change?"