Docker Tip #46: Using WORKDIR to Cleanup Your Dockerfile
![blog/cards/docker-tips-and-tricks.jpg](/assets/blog/cards/docker-tips-and-tricks-92efa4f3cccffb29a7369417a3f9e884a77a918d152a0d2c1636c064a4dd2169.jpg)
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.
WORKDIR /app
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
WORKDIR baz
RUN pwd
The above pwd
command would resolve to /foo/bar/baz
.