Dockerizing Python application

Small size Docker image

The example below discusses a Dockerfile allowing to build a small size Python application Docker image. The idea is to use a two-stage building process and use the pip --user option allowing to install dependencies only locally for a user.

FROM python:3.8 as builder
WORKDIR /app
ADD requirements.txt /app/
RUN pip install --user -r requirements.txt

FROM python:3.8-slim
WORKDIR /app
COPY --from=builder /root/.local /root/.local
ENV PATH=/root/.local/bin:$PATH
ADD . /app/

CMD ["/app/application.py"]

Explanation:

  • FROM python:3.8 as builder - a full-size Python image is used at building stage,
  • WORKDIR /app - set /app as the working directory in the image,
  • ADD requirements.txt /app/ - copy requirements.txt to the /app directory in the image,
  • RUN pip install --user -r requirements.txt - install dependencies to the local user directory,
  • FROM python:3.8-slim - the final image is based on the Python slim one, which is optimally sized,
  • COPY --from=builder /root/.local /root/.local - copy only the dependencies installation from the building stage,
  • ENV PATH=/root/.local/bin:$PATH - update PATH environment variable in the final image,
  • ADD . /app/ - copy the application code source to the final image,
  • CMD ["/app/application.py"] - run the application.