4.2.2.3 WORKDIR Command Location
A focused guide to WORKDIR Command Location, connecting core concepts with practical Docker and container operations.
WORKDIR command location refers to where, within a Dockerfile, the WORKDIR instruction should be placed relative to other instructions, since its position determines which subsequent instructions are affected by the working directory it establishes.
Placing WORKDIR Before Instructions That Depend On It
WORKDIR only affects instructions that come after it in the file; anything earlier in the Dockerfile is unaffected, which means it needs to be placed deliberately before the first instruction that should be relative to it.
FROM python:3.12-slim
COPY requirements.txt /tmp/requirements.txt
WORKDIR /app
COPY . .
Here, the first COPY uses an absolute path because WORKDIR had not yet been set at that point in the file, while the second COPY, occurring after WORKDIR /app, resolves relative to /app.
A Common Convention: Setting WORKDIR Early
Many Dockerfile authors set WORKDIR immediately after FROM, establishing a consistent working directory for the entire remainder of the file and avoiding any ambiguity about path resolution later on.
FROM node:20-alpine
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
CMD ["node", "server.js"]
Changing WORKDIR Mid-File for Multi-Part Builds
In more complex Dockerfiles, particularly multi-stage builds, WORKDIR is sometimes set again partway through, intentionally switching the working directory for a distinct phase of the build.
WORKDIR /src
COPY . .
RUN make build
WORKDIR /output
RUN cp /src/bin/app .
Why the Instruction's Position Matters
Because WORKDIR's effect only applies going forward from where it appears, placing it incorrectly — too late, or not at all before instructions that assume a particular working directory — is a common source of subtle build mistakes, particularly when a Dockerfile is edited or reorganized over time.
docker build --progress=plain -t myapp .
Reviewing detailed build output can help confirm exactly which directory each instruction actually operated in, useful for catching this kind of positional mistake.
Why This Matters
Deliberately considering where WORKDIR is placed, rather than treating its position as incidental, keeps a Dockerfile's path resolution behavior predictable and easy to reason about for anyone reading or modifying it later.