Learn Docker With My Newest Course

Dive into Docker takes you from "What is Docker?" to confidently applying Docker to your own projects. It's packed with best practices and examples. Start Learning Docker →

Docker Tip #46: Using WORKDIR to Cleanup Your Dockerfile


If you find yourself frequently changing directories in your Dockerfile then you may want to look into using WORKDIR. Here's how.

The WORKDIR instruction allows you to set a specific path in one spot, and then most instructions (RUN and COPY to name a few) will execute in the context of that WORKDIR.

Let’s say this were your old Dockerfile that didn’t use WORKDIR:
FROM python:3.8.3-slim-buster

RUN mkdir /app

COPY requirements.txt /app/requirements.txt
RUN cd /app && pip install -r requirements.txt

COPY . /app

CMD ["gunicorn", "-c", "python:config.gunicorn", "foo.app:create_app()"]

Yikes, you had to repeat the /app path in so many spots.

You can drastically improve the above Dockerfile by leveraging WORKDIR:
FROM python:3.8.3-slim-buster

# We don't even need to run mkdir /app since WORKDIR will make it for us.

COPY requirements.txt requirements.txt
RUN pip install -r requirements.txt

COPY . .

CMD ["gunicorn", "-c", "python:config.gunicorn", "foo.app:create_app()"]

The key there is setting WORKDIR /app. Everything after that point will execute from the /app directory.

You can think of it as doing a cd but the directory you change into will persist between instructions. You can even have more than 1 WORKDIR in your Dockerfile if you need it.

Here’s an example of using multiple WORKDIRs:
WORKDIR /foo/bar

RUN pwd

The above pwd command would resolve to /foo/bar/baz.

Free Intro to Docker Email Course

Over 5 days you'll get 1 email per day that includes video and text from the premium Dive Into Docker course. By the end of the 5 days you'll have hands on experience using Docker to serve a website.