By default, Poetry will install virtual environment in the venvs directory in the subdirectory with hashed name, e.g. apex-q4124gfga.py3.6.

I wanted to create a virtual environment in Docker multi-stage build so it can be copied in the other stage with single command. For that I needed that the name is known beforehand.

To fix this, I used an approach described here:

If you are trying to control the virtual environment path in a Dockerfile, the canonical method is:

RUN python -m venv /path/to/app/venv
ENV PATH="/path/to/app/venv/bin:$PATH" VIRTUAL_ENV=/path/to/app/venv
RUN poetry install

Setting PATH and VIRTUAL_ENV has the effect of activating the virtual environment and causing all following RUN lines to use that environment; all your poetry and python commands will ‘just work.‘

My code:

ARG VENV_PATH="/opt/.venv"
 
...
 
# Set a directory for virtual environment. Setting `VIRTUAL_ENV` and `PATH environment 
# variables has the effect of activating the virtual environment for all subsequent
# poetry and python commands.
# More on this here: https://github.com/python-poetry/poetry/issues/263#issuecomment-1404129650
ARG VENV_PATH
RUN python -m venv ${VENV_PATH}
ENV VIRTUAL_ENV=${VENV_PATH}
ENV PATH="${VENV_PATH}:${PATH}" 

When analyzing with Docker Dive the packages were indeed installed properly in the specified directory /opt/.venv: