Dockerfile - Use WORKDIR the right way
WORKDIR is the most commonly misused instuction in a dockerfile. Learn the WORKDIR instruction in a dockerfile and its proper usage.
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 words, 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
The WORKDIR instruction will automatically create the directory if it doesn't exist. There is no need to create it explicitly.
Using Environment variable,
ENV APPROOT /app
A simple flask application using WORKDIR for setting working directory
# set working directory
# 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
Originally published on idiotinside.com
If you find this article helpful, please do like and comment on this article. If you have any suggestions or feedbacks, feel free to comment.
Stay tuned for upcoming articles. Subscribe to the newsletter and Connect with me on twitter to get my future articles.
Did you find this article valuable?
Support Suresh Kumar by becoming a sponsor. Any amount is appreciated!