Restarting containers in Docker - Time & Space Complexity
We want to understand how the time to restart containers changes as the number of containers grows.
How does restarting many containers affect the total time taken?
Analyze the time complexity of the following code snippet.
for container in $(docker ps -q); do
docker restart $container
echo "Restarted container $container"
done
This script lists all running containers and restarts each one, printing a message after each restart.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Restarting each container one by one inside a loop.
- How many times: Once for each running container (n times).
As the number of containers increases, the total time grows roughly in direct proportion.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 restarts |
| 100 | 100 restarts |
| 1000 | 1000 restarts |
Pattern observation: Doubling the number of containers doubles the total restart operations.
Time Complexity: O(n)
This means the time to restart containers grows linearly with the number of containers.
[X] Wrong: "Restarting multiple containers happens all at once, so time stays the same no matter how many containers there are."
[OK] Correct: Each container restart is done one after another, so total time adds up with each container.
Understanding how operations scale with input size helps you explain system behavior clearly and shows you can reason about real-world scripts.
"What if we restarted all containers in parallel instead of one by one? How would the time complexity change?"