Dockerizing Python Poetry Applications
Poetry meets Docker
--
Poetry is one of the new and more elegant dependency management tools Python has at its disposal. In my opinion, its the unofficial successor to pipenv which hasn’t had a major update in a while and is probably dead? Being a relatively new tool, there isn’t much documentation out there regarding dockerizing an application using Poetry. It’s actually a fairly simple process but took me a while to get working due to the lack of documentation. I recently dockerized my steam game recommendations engine which uses embeddings to make recommendations. You can play around with it here. I’ll be using this project’s Docker file as an example:
FROM python:3.7RUN mkdir /app COPY /app /app
COPY pyproject.toml /app WORKDIR /app
ENV PYTHONPATH=${PYTHONPATH}:${PWD} RUN pip3 install poetry
RUN poetry config virtualenvs.create false
RUN poetry install --no-dev
As you can see its a fairly simple file but there a few lines which are critical for dockerizing this application:
COPY pyproject.toml /app
This line copies the dependencies of my app into the working directory of my container. Make sure this is done otherwise:
- Poetry will think this is a new project
- You will have to install the dependencies again individually
Next, the PYTHONPATH was set and poetry installed with pip. The following line is the most important line in this dockerfile:
RUN poetry config virtualenvs.create false
This line ensures when packages are installed with Poetry a virtual environment is NOT created first. You’re already in a virtual environment by using a docker image, there's no need to build another environment unless you really want to inception your application of course.
Finally the last line:
RUN poetry install --no-dev
Installs all the required packages minus the development packages, also don’t forget to add your application’s Entrypoint
if it needs one. That’s it! You now have a dockerized Poetry application, hopefully, this has saved you plenty of time compared to the hours of hair pulling it cost me.