WORKDIR: Setting Working Directory
What you'll learn: How to use the WORKDIR instruction to define where commands run inside your container.
What is WORKDIR?
Think of WORKDIR as opening a specific folder on your computer before running commands. Instead of typing full paths like /app/src/config/file.txt every time, you "cd" into /app/src/config first, then just reference file.txt.
In a Dockerfile, WORKDIR sets the working directory for any RUN, COPY, ADD, CMD, or ENTRYPOINT instructions that follow it. If the directory doesn't exist, Docker creates it automatically.
Why Use WORKDIR?
Without WORKDIR, all commands execute from the container's root directory (/). This leads to messy, error-prone paths:
FROM ubuntu:22.04
RUN mkdir -p /app/backend
COPY server.js /app/backend/server.js
RUN cd /app/backend && npm install
With WORKDIR, paths become clean and consistent:
FROM ubuntu:22.04
WORKDIR /app/backend
COPY server.js .
RUN npm install
Key Behaviors
- Persistence: Once set, the working directory remains active for all subsequent instructions.
- Multiple declarations: You can call
WORKDIRmultiple times; each changes the context. - Relative paths:
WORKDIR backendafterWORKDIR /appresults in/app/backend. - Auto-creation: If
/app/backenddoesn't exist, Docker creates it.
Example Flow
FROM node:18
WORKDIR /app # Now in /app
COPY package.json . # Copies to /app/package.json
RUN npm install # Runs inside /app
WORKDIR src # Now in /app/src
COPY *.js . # Copies JS files to /app/src
Key Takeaway: WORKDIR sets your container's working directory, making paths shorter, clearer, and less error-prone across all subsequent Dockerfile instructions.