The WORKDIR instruction
- Docker & Kubernetes course
- Beginner
- Lesson 59/82
- 4 min
Learn to set the container working directory with WORKDIR.
The WORKDIR instruction
WORKDIR sets the directory where the following RUN, CMD, ENTRYPOINT, COPY and ADD instructions run. If the directory doesn't exist it is created. RUN cd /app doesn't work, because each RUN runs in a new shell:
# wrong: cd doesn't carry over to the next line
RUN cd /app
RUN npm install # runs in /
# right
WORKDIR /app
RUN npm installRelative WORKDIR
WORKDIR can be used several times; relative paths are appended to the previous one. Using absolute paths improves readability:
WORKDIR /app
WORKDIR src # now /app/src
RUN pwd # /app/srcWORKDIR becomes the starting directory when you enter the container with docker exec.
Practice Installing in the right directory
Write a Dockerfile based on node:20-alpine: WORKDIR /app; copy the package*.json files to ./; run npm ci --omit=dev; copy the whole project; CMD is node server.js in exec form.
Starter code
# buraya yazSample solution
FROM node:20-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci --omit=dev
COPY . .
CMD ["node", "server.js"]Expected output
[+] Building 2.9s (8/8) FINISHED => naming to docker.io/library/web:latest done
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which directory do RUN cd /app followed by RUN ls list?
- The previous WORKDIR (/ by default) Correct answer
- /app
- It errors
- Empty output
Explanation: Each RUN instruction is a separate shell process.
2 Set the directory for the following instructions.
____ /app
WORKDIR /app
Explanation: RUN cd isn't persistent; WORKDIR is.
3 Match.
| Term | Meaning |
|---|---|
WORKDIR /app |
Sets and creates the directory |
RUN cd /app |
Only for that RUN |
WORKDIR src |
Relative: appended to the previous |
docker exec |
Starts in WORKDIR |