What is WORKDIR in Dockerfile: Simple Explanation and Usage
WORKDIR instruction in a Dockerfile sets the working directory for any following commands in the image build process. It works like changing the current folder in a terminal, so commands run inside that directory by default.How It Works
The WORKDIR instruction tells Docker to switch to a specific folder inside the container before running any commands that come after it. Think of it like opening a folder on your computer before you start working on files inside it. If the folder does not exist, Docker will create it automatically.
This means you don't have to write long paths for every command. Instead, you set the folder once with WORKDIR, and all commands run as if you are inside that folder. It helps keep your Dockerfile clean and easy to read.
Example
This example shows how WORKDIR sets the folder for commands that follow.
FROM alpine:3.18
WORKDIR /app
RUN touch example.txt
RUN ls -lWhen to Use
Use WORKDIR whenever you want to run commands inside a specific folder in your Docker image. It is especially useful when you copy files, install packages, or run scripts that expect to be in a certain directory.
For example, if your app code lives in /app, setting WORKDIR /app means you can run commands like npm install or python main.py without typing the full path every time.
Key Points
- WORKDIR sets the default folder for following commands in the Dockerfile.
- If the folder does not exist, Docker creates it automatically.
- You can use multiple
WORKDIRinstructions; each one changes the current directory. - It helps keep commands shorter and Dockerfiles cleaner.
Key Takeaways
WORKDIR sets the working directory for all following Dockerfile commands.WORKDIR makes your Dockerfile commands simpler and easier to read.WORKDIR instructions.