✦ For everyone, free.

Practical knowledge for real and everyday life

Home

4.2.2.1 WORKDIR Directory Creation

A focused guide to WORKDIR Directory Creation, connecting core concepts with practical Docker and container operations.

WORKDIR directory creation refers to the fact that the WORKDIR instruction automatically creates the specified directory if it does not already exist, removing the need for a separate, explicit step to create it before switching into it.

Automatic Creation Without a Separate mkdir

Unlike a plain shell cd, which fails if the target directory does not exist, WORKDIR creates any missing directories in the path automatically before switching into it.

WORKDIR /app/data

Even if neither /app nor /app/data exists in the base image, this single instruction creates both, then makes /app/data the current working directory for everything that follows.

Why This Removes a Common Source of Error

Without this automatic creation, a Dockerfile would need an explicit RUN mkdir -p /app/data before attempting to switch into that directory, introducing an additional instruction and an additional opportunity for a typo or ordering mistake.

RUN mkdir -p /app/data
WORKDIR /app/data
WORKDIR /app/data

Both produce the same result, but the second is simpler and cannot fail due to forgetting the directory creation step.

Creating Nested Directories in One Step

Because the entire path is created if needed, a deeply nested directory structure can be established in a single WORKDIR instruction, rather than requiring intermediate directories to be created one at a time.

WORKDIR /opt/myapp/config/environments
Verifying the Created Directory

After a build, the existence and permissions of a directory created this way can be confirmed directly.

docker run --rm myapp ls -ld /app/data
Why This Behavior Matters

The automatic directory creation behavior of WORKDIR is a small but genuinely useful convenience, reducing the number of instructions needed to establish a clean, organized directory structure inside an image without sacrificing correctness or requiring extra verification steps.