🐳 Docker Beginner

What is the WORKDIR instruction in Dockerfile?

Answer

WORKDIR sets the working directory for all subsequent Dockerfile instructions (RUN, CMD, ENTRYPOINT, COPY, ADD) and for the container's default shell when you docker exec -it container bash. If the directory doesn't exist, WORKDIR creates it automatically. Usage: WORKDIR /app. All following instructions execute relative to this path. Best practices: always set WORKDIR explicitly rather than relying on the root directory or using cd in RUN commands. Prefer absolute paths (starting with /) for clarity. WORKDIR can be set multiple times in a Dockerfile — each new WORKDIR is relative to the previous if a relative path is given. Example Dockerfile structure: FROM node:20-alpine\nWORKDIR /app\nCOPY package*.json ./\nRUN npm ci\nCOPY . .\nEXPOSE 3000\nCMD ["node", "app.js"]. All COPY instructions use /app as the base — COPY package*.json ./ copies to /app/package*.json. The CMD runs from /app. Why not use RUN mkdir /app && cd /app? Because cd in RUN only affects that RUN layer; WORKDIR persists across all subsequent layers.