Poetry can be a bit hard to set up a Dockerfile for. This is because Poetry has many ways of storing its virtual environment.
I prefer to not modify any defaults if I can. With Poetry however, you cannot just run poetry install
. The packages need to be available when using the Dockerfile. By setting POETRY_VIRTUALENVS_CREATE
to false, and POETRY_HOME
to a known dir in the PATH, the installation target is set to a global one.
To not bust the cache on a code change, the installation of the dependencies and the copying of project files is split. Poetry provides the flags --no-root --no-directory
to do this. [1]
Here's the Dockerfile:
FROM python:3.12 ENV POETRY_NO_INTERACTION=1 \ POETRY_VIRTUALENVS_CREATE=false \ POETRY_CACHE_DIR='/var/cache/pypoetry' \ POETRY_HOME='/usr/local' \ POETRY_VERSION=2.1 WORKDIR /app COPY pyproject.toml poetry.lock ./ RUN pip install poetry==$POETRY_VERSION && poetry install --only main --no-root --no-directory COPY . /app RUN poetry install --only main ... your CMD