Prerequisites:
To follow along with the tutorial, you need the following:
- Installed Docker on the host machine
- Basic knowledge of Docker and Dockerfile syntax
The Basics
Let us start with the basics and discuss what the WORKDIR instruction means.
In a Dockerfile, the WORKDIR directive allows us to set the working directory for any subsequent instructions.
This means that when we run a container from an image built with a Dockerfile containing WORKDIR, the container’s default working directory is set to the specified path.
You can think of the equivalent of the “cd” command in Unix systems.
Using the WORKDIR directive can help prevent the relative-path related errors when running the commands inside the container.
The following shows the syntax for the WORKDIR instruction:
Where the “path/to/directive” specifies an absolute or relative path to the directory that you wish to set as the “cwd”.
Basic Usage
Consider the following Dockerfile example that defines the instructions to run a Node.JS application:
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
EXPOSE 3000
CMD [ "npm", "start" ]
In the given example, we use the WORKDIR directive to set the current working directory to “/app”. This means that all the subsequent commands run inside the “/app” directory.
Using Relative Paths
Docker also allows us to use the relative paths with the WORKDIR directive. For example, suppose we have a project layout as follows:
├── Dockerfile
├── src/
└── public/
In the Dockerfile, we can set the WORKDIR as a relative path as shown in the following example:
WORKDIR /app
COPY src/ .
In this case, the WORKDIR instruction sets the working directory to “/app” relative to the root directory of the container.
Using Multiple WORKDIR Directives
As you can guess, we can use multiple WORKDIR instructions in the same Dockerfile. This allows us to quickly change the current working directory in single steps.
WORKDIR /app
RUN touch config.ini
# Change the working directory
WORKDIR /data
RUN touch logging.yml
In the given example, we start by defining the current working directory to “/app” using the first WORKDIR entry. We then execute the commands to create a new file inside the “/app” directory.
Next, we change the current working directory to “/data” and create a new file in that directory.
Conclusion
In this tutorial, we learned how to work with the WORKDIR instruction within the Dockerfile to change the current working directory for all subsequent commands.