This article will describe:
- What is the Purpose/Goal of WORKDIR in the Dockerfile?
- What is Default WORKDIR?
- How to Specify the WORKDIR in Dockerfile?
What is the Purpose/Goal of WORKDIR in the Dockerfile?
The WORKDIR is the instruction in the Dockerfile that specifies the working directory for the subsequent commands. When a container is started from an image built from a Dockerfile, the working directory of the container is set to the value defined by the WORKDIR instruction.
There are multiple advantages to setting the working directory, such as simplifying the process of writing relative paths in subsequent instructions since they will be relative to the specified working directory. This reduces the risk of errors in specifying file paths and makes the Dockerfile more understandable. Moreover, it ensures that files or directories created by subsequent instructions are placed in the correct directory.
What is Default WORKDIR?
The root directory “/” is the default WORKDIR if it is not specified in the Dockerfile. All instructions after the WORKDIR instruction in a Dockerfile will run relative to the root directory. However, users can override the default value by defining an alternative directory in the WORKDIR instruction.
How to Specify the WORKDIR in Dockerfile?
Users can use the WORKDIR instructions to specify any working directory in a Dockerfile. The syntax for using the WORKDIR instruction is as follows:
Here, “/path/to/directory” is the absolute or relative path to the directory that the user wants to set as the working directory. Docker will make a new directory if there is no existing directory.
Example
Let us take an example to see the method of defining a working directory in Dockerfile:
WORKDIR /app
COPY . .
CMD ["./app.py"]
In this example,
- The “WORKDIR” specifies the working directory to “/app”.
- The “COPY” instruction copies the current directory’s content to the “/app” directory in the present container.
- Finally, the “CMD” instruction specifies that when the container is started, it should run the “app.py” script located in the “/app” directory.
Conclusion
The WORKDIR is the instruction in the Dockerfile that specifies the working directory for the subsequent commands. Any commands that are run, any files that are created, or any files that are changed will be relative to the working directory. It simplifies the process of writing relative paths in subsequent instructions, reduces the risk of errors in specifying file paths, and makes the Dockerfile more understandable.