How to Change Working Directory Command in Docker

How to Change Working Directory Command in Docker

In Docker, we can not seamlessly run terminal commands if we have not created and started the container and did not exec inside the container’s shell. One example of these commands is changing the working directory.

Changing the working directory is essential if we need to install a component in a specific directory. This article will discuss methods to change the working directory in Docker.

Change Working Directory in Docker

The following commands we will tackle are not primary commands but entries we will use when preparing our Dockerfile. If we can recall, we can use the Dockerfile to automate the creation of containers when running the docker build command.

In the following section, we will discuss two ways of changing the working directory via the Dockerfile.

Use the RUN Command

We can run a terminal script using the RUN command. Then, inside our Dockerfile, we can insert an entry like the below to change our working directory.

RUN cd /dev

Before running other commands, we can change the working directory with the cd command. However, we do not need to add a new RUN entry to the Dockerfile to run multiple commands.

We can use and append various commands with just one RUN line.

Example Code:

RUN cd /dev && git clone sample.git && pip install -r requirements.txt

We can run multiple commands with the AND (&&) operator. For example, the following command will only run if the previous command behind it is successful.

In this case, if the git clone commands fail, our pip install command will not execute. However, there is a more straightforward way if we change the working directory inside the container.

Use the WORKDIR Command

Like the RUN command, we can add the WORKDIR command inside our Dockerfile to change the working directory once the container is up and running.

WORKDIR "/dev"

The WORKDIR command is considered a Dockerfile best practice when writing build files for Docker. This scenario happens because the above command makes it easier to read and distinguish from executed commands on the container.

WORKDIR "/dev"
RUN git clone sample.git && pip install -r requirements.txt
Marion Paul Kenneth Mendoza avatar Marion Paul Kenneth Mendoza avatar

Marion specializes in anything Microsoft-related and always tries to work and apply code in an IT infrastructure.

LinkedIn

Related Article - Docker Directory