Course contentsShow
← Cloud and Infrastructure
Lesson 1004 of 2,98920. Docker in DepthFree lesson

WORKDIR: Setting Working Directory

Understand WORKDIR instruction for defining container working directory and path resolution across instructions.

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 WORKDIR multiple times; each changes the context.
  • Relative paths: WORKDIR backend after WORKDIR /app results in /app/backend.
  • Auto-creation: If /app/backend doesn'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.