0
0
Dockerdevops~5 mins

Starting and stopping containers in Docker - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Starting and stopping containers
O(n)
Understanding Time Complexity

We want to understand how the time it takes to start and stop Docker containers changes as we handle more containers.

How does the number of containers affect the total time to start or stop them all?

Scenario Under Consideration

Analyze the time complexity of the following Docker commands used in a script.


for container in $(docker ps -q); do
  docker stop $container
  docker start $container
 done
    

This script stops and then starts each running container one by one.

Identify Repeating Operations

Look for repeated actions in the code.

  • Primary operation: Stopping and starting each container.
  • How many times: Once for each container running on the system.
How Execution Grows With Input

As the number of containers increases, the total time grows because each container is handled separately.

Input Size (n)Approx. Operations
1020 (10 stops + 10 starts)
100200 (100 stops + 100 starts)
10002000 (1000 stops + 1000 starts)

Pattern observation: The total operations grow directly with the number of containers.

Final Time Complexity

Time Complexity: O(n)

This means the time to start and stop containers grows in a straight line with how many containers there are.

Common Mistake

[X] Wrong: "Starting or stopping multiple containers at once takes the same time as one container."

[OK] Correct: Each container needs its own start and stop action, so time adds up with more containers.

Interview Connect

Understanding how operations scale with the number of containers shows you can think about system behavior as it grows, a key skill in real work.

Self-Check

"What if we stopped and started containers in parallel instead of one by one? How would the time complexity change?"