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.
WORKDIR instruction allows you to set a specific path in one spot, and then most instructions (
COPY to name a few) will execute in the context of that
Let’s say this were your old Dockerfile that didn’t use WORKDIR:
FROM python:2.7-alpine RUN mkdir /app COPY requirements.txt /app/requirements.txt RUN cd /app && pip install -r requirements.txt COPY . /app CMD /app/gunicorn -b 0.0.0.0:8000 --access-logfile - "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:2.7-alpine # 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 -b 0.0.0.0:8000 --access-logfile - "foo.app:create_app()"
The key there is setting
WORKDIR /app. Everything after that point will execute from the
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
pwd command would resolve to