BudiBadu Logo
Samplebadu

Dockerfile by Example: Working Directory Configuration

Docker Engine 20.10+

The WORKDIR instruction sets the context for subsequent instructions. This code example illustrates how it simplifies paths and creates directories automatically.

Code

FROM node:18-alpine

# 1. Set the working directory
# Docker creates this directory if it doesn't exist
WORKDIR /usr/src/app

# 2. Subsequent commands run inside this directory
COPY package.json .
# This effectively copies to /usr/src/app/package.json

RUN npm install

# 3. You can change it multiple times (relative paths work)
WORKDIR backend
# Now in /usr/src/app/backend
RUN echo "Hello" > test.txt

Explanation

The WORKDIR instruction sets the working directory for any RUN, CMD, ENTRYPOINT, COPY, and ADD instructions that follow it. It acts like a persistent cd command for the build process. If the specified directory does not exist, Docker creates it automatically, including any necessary parent directories, eliminating the need for explicit mkdir -p commands.

Best practices for WORKDIR include:

  • Always use absolute paths to ensure clarity and predictability
  • Define WORKDIR early to avoid polluting the container's root filesystem
  • Avoid frequent changes to WORKDIR to maintain readability
  • Relative paths are supported but can be confusing if context is lost

Using WORKDIR aligns the build context with the application's expected runtime structure. It simplifies subsequent instructions by allowing the use of relative paths (like COPY . .). While relative paths can be used with WORKDIR itself (e.g., WORKDIR backend moves into a subdirectory), using absolute paths is generally recommended to prevent ambiguity and potential bugs arising from unexpected directory states.

Code Breakdown

5
WORKDIR /usr/src/app establishes the absolute path for the app.
8
COPY package.json . copies file into the current WORKDIR.
14
WORKDIR backend changes context to a subdirectory relative to previous path.
16
RUN echo ... executes in the new /usr/src/app/backend directory.