WORKDIR instruction in a Dockerfile

WORKDIR instruction in a Dockerfile

  • The WORKDIR instruction sets the current working directory for any RUN, CMD, ENTRYPOINT, COPY and ADD instructions.
  • If the WORKDIR doesn’t exist, it will be created automatically.
  • In simple, It runs a mkdir command if the directory doesn’t exist and then cd into the directory.
  • WORKDIR also resolves environment variables. So we can use variables without hardcoding repeated paths.

The most commonly misused docker instruction is below

RUN mkdir /app
WORKDIR /app

The WORKDIR instruction will automatically create the directory if it doesn’t exist. There is no need to create it explicitly.

Examples:

WORKDIR /app

Using Environment variable,

ENV APPROOT /app
WORKDIR $APPROOT

A simple flask application using WORKDIR for setting working directory

FROM python:3.8.0

# set working directory
WORKDIR /app

# add requirements
COPY ./requirements.txt /app/requirements.txt

# install requirements
RUN pip install -r requirements.txt

# copy source code to /app
COPY . /app

# run server
CMD python main.py

# expose 
EXPOSE 5000