WORKDIR instruction for directory in Docker - Time & Space Complexity
We want to understand how the time to set a working directory in Docker changes as the directory path length or complexity grows.
How does Docker handle the WORKDIR instruction when given different directory paths?
Analyze the time complexity of the following Dockerfile snippet.
FROM alpine:latest
WORKDIR /app
WORKDIR logs
WORKDIR /var/www/html
This snippet sets the working directory multiple times, using both absolute and relative paths.
Look at how Docker processes each WORKDIR instruction.
- Primary operation: Resolving the directory path for each WORKDIR instruction.
- How many times: Once per WORKDIR instruction in the Dockerfile.
As the directory path length increases, Docker must process more parts of the path.
| Input Size (path depth) | Approx. Operations |
|---|---|
| 1 (e.g., /app) | 1 operation |
| 3 (e.g., /var/www/html) | 3 operations |
| 10 (e.g., /a/b/c/d/e/f/g/h/i/j) | 10 operations |
Pattern observation: The time to resolve the directory grows linearly with the number of directory levels.
Time Complexity: O(n)
This means the time to process the WORKDIR instruction grows in a straight line as the directory path gets longer.
[X] Wrong: "Setting WORKDIR always takes the same time no matter how long the path is."
[OK] Correct: Docker must process each directory level in the path, so longer paths take more steps.
Understanding how simple instructions like WORKDIR scale helps you reason about build times and Dockerfile efficiency in real projects.
"What if we used multiple relative WORKDIR instructions instead of one long absolute path? How would the time complexity change?"