4.2.2.2 WORKDIR Relative Paths
A focused guide to WORKDIR Relative Paths, connecting core concepts with practical Docker and container operations.
WORKDIR relative paths describes how, once WORKDIR is set, any relative path used in subsequent instructions — in COPY, ADD, RUN, or even another WORKDIR — is resolved relative to the currently established working directory, rather than to the image's filesystem root.
How Relative Paths Resolve After WORKDIR
Once a working directory is set, instructions that accept relative paths interpret them relative to that directory, not relative to /.
WORKDIR /app
COPY requirements.txt .
RUN pip install -r requirements.txt
The . in this COPY instruction refers to /app, not to the filesystem root, because WORKDIR /app was established beforehand.
Stacking Relative WORKDIR Instructions
A WORKDIR instruction using a relative path is itself resolved relative to whatever working directory was previously in effect, allowing nested directory structures to be expressed incrementally.
WORKDIR /app
WORKDIR src
WORKDIR utils
After these three instructions, the current working directory is /app/src/utils, built up incrementally rather than specified all at once.
Why Relying on Relative Paths Without WORKDIR Is Risky
Without an explicitly set working directory, relative paths in various instructions default to the filesystem root, which can produce confusing or unintended results if a Dockerfile author assumes a different default location.
COPY requirements.txt .
Without a preceding WORKDIR, this places requirements.txt directly at the filesystem root, which is rarely the intended location for application files.
Making Relative Path Resolution Predictable
Establishing WORKDIR early and explicitly, before any instructions relying on relative paths, removes ambiguity about where exactly those paths will resolve, making the rest of the Dockerfile easier to read and reason about correctly.
FROM python:3.12-slim
WORKDIR /app
COPY . .
Why Understanding This Resolution Matters
A clear understanding of how WORKDIR affects relative path resolution prevents a common class of subtle Dockerfile bugs, where files end up in unexpected locations simply because the working directory in effect at that point in the file was not what the author assumed.