How to Set the Working Directory in Docker

How to Set the Working Directory in Docker

If one exists, the working directory of a process in computing is a directory in a linked hierarchical file system that is dynamic to each process. In Docker, we can set our working directory by editing our Dockerfile and adding the key WORKDIR.

This article will discuss changing our current and default working directory in Docker.

the WORKDIR in Docker

The WORKDIR command in the Dockerfile determines the working directory for any RUN, CMD, ENTRYPOINT, COPY, and ADD instructions that come after it. We can use the WORKDIR instruction multiple times in a Dockerfile.

If we provide a relative path, it will be relative to the path of the previous WORKDIR instruction.

For example:

WORKDIR /usr
WORKDIR src/serv
RUN sampleserv

The output of the final sampleserv command in this Dockerfile would be /usr/src/serv.

The WORKDIR instruction can resolve environment variables previously specified with the ENV instruction. However, we can only use environment variables explicitly set in the Dockerfile.

ENV DIRPATH=/usr
WORKDIR $DIRPATH/$DIRNAME
RUN sampleserv

The final sampleserv command’s output in this Dockerfile would be /usr/$DIRNAME.

The default working directory is the root directory or / if not specified. In reality, if you aren’t creating a Dockerfile from scratch (FROM scratch), the base image you’re using may have already configured the WORKDIR.

Therefore, we recommend explicitly setting your WORKDIR to prevent accidental activities in unknown folders.

We should always use absolute paths for your WORKDIR for clarity and reliability. Also, we should use WORKDIR instead of increasing instructions like RUN cd … && sample-code, which are hard to read, troubleshoot, and maintain.

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