Why use WORKDIR instead of RUN cd in a Dockerfile?
WORKDIR sets the working directory for all later instructions and the running container, and creates it if missing. RUN cd only affects that single RUN line, because each RUN starts a fresh shell.
Explain it simply
Each RUN is a new visit to the office: you walk in fresh at the front desk. If you cd into a cabin during one visit, the next visit starts at the front desk again.
So RUN cd /app followed by RUN npm install installs in the root folder, not in /app. WORKDIR /app fixes this: every later RUN, COPY, CMD and ENTRYPOINT uses /app, and so does docker exec unless you override it. WORKDIR also creates the folder if it does not exist, and relative paths in later instructions resolve against it. You may use WORKDIR several times; relative paths stack on the previous one.
Prefer absolute paths in WORKDIR for clarity.
Example
FROM node:20-alpine
WORKDIR /app
COPY package*.json ./ # lands in /app
RUN npm ci # runs in /app
COPY . .
CMD ["node", "index.js"]What to say in the interview
"WORKDIR sets the directory for every following instruction and for the container at runtime, creating it if needed. RUN cd only lasts for that one RUN, since each RUN is a separate shell."
Common mistakes
- Writing RUN cd /app then expecting the next RUN to be inside /app.