The WORKDIR instruction sets the working directory for any subsequent RUN, CMD, ENTRYPOINT, COPY, and ADD instructions in the Dockerfile.
The WORKDIR instruction defines the current working directory for all following instructions in the Dockerfile. If the directory doesn't exist, it will be created automatically. This is essential for organizing application files and ensuring that commands execute in the correct location. Once set, all relative paths in subsequent instructions are resolved relative to this working directory.
Using WORKDIR is strongly recommended over using RUN cd ... commands because it provides a cleaner, more maintainable way to set the working directory. Each WORKDIR instruction can be relative to the previous one, and it automatically handles directory creation. The directory path can include environment variables set earlier in the Dockerfile, making it flexible for different configurations.
Eliminates repetitive cd commands in RUN instructions, making the Dockerfile cleaner and easier to read
Automatically creates directories if they don't exist, avoiding explicit mkdir commands
Works consistently with COPY and ADD relative paths, ensuring files land where expected
Sets the initial working directory for the container when it starts, affecting CMD and ENTRYPOINT
Can use environment variables, enabling dynamic path configuration