0
0
DockerConceptBeginner · 3 min read

What is WORKDIR in Dockerfile: Simple Explanation and Usage

The 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.

dockerfile
FROM alpine:3.18
WORKDIR /app
RUN touch example.txt
RUN ls -l
Output
total 0 -rw-r--r-- 1 root root 0 Apr 27 00:00 example.txt
🎯

When 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 WORKDIR instructions; 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.
If the directory does not exist, Docker creates it automatically.
Using WORKDIR makes your Dockerfile commands simpler and easier to read.
You can change the working directory multiple times with multiple WORKDIR instructions.