Integrating Python Poetry with Docker

后端 未结 7 428
轻奢々
轻奢々 2021-01-29 17:51

Can you give me an example of a Dockerfile in which I can install all the packages I need from poetry.lock and pyproject.toml into my imag

7条回答
  •  爱一瞬间的悲伤
    2021-01-29 18:31

    This is a minor revision to the answer provided by @Claudio, which uses the new poetry install --no-root feature as described by @sobolevn in his answer.

    In order to force poetry to install dependencies into a specific virtualenv, one needs to first enable it.

    . /path/to/virtualenv/bin/activate && poetry install
    

    Therefore adding these into @Claudio's answer we have

    FROM python:3.9-slim as base
    
    ENV PYTHONFAULTHANDLER=1 \
        PYTHONHASHSEED=random \
        PYTHONUNBUFFERED=1
    
    RUN apt-get update && apt-get install -y gcc libffi-dev g++
    WORKDIR /app
    
    FROM base as builder
    
    ENV PIP_DEFAULT_TIMEOUT=100 \
        PIP_DISABLE_PIP_VERSION_CHECK=1 \
        PIP_NO_CACHE_DIR=1 \
        POETRY_VERSION=1.1.3
    
    RUN pip install "poetry==$POETRY_VERSION"
    RUN python -m venv /venv
    
    COPY pyproject.toml poetry.lock ./
    RUN . /venv/bin/activate && poetry install --no-dev --no-root
    
    COPY . .
    RUN . /venv/bin/activate && poetry build
    
    FROM base as final
    
    COPY --from=builder /venv /venv
    COPY --from=builder /app/dist .
    COPY docker-entrypoint.sh ./
    
    RUN . /venv/bin/activate && pip install *.whl
    CMD ["./docker-entrypoint.sh"]
    

    If you need to use this for development purpose, you add or remove the --no-dev by replacing this line

    RUN . /venv/bin/activate && poetry install --no-dev --no-root
    

    to something like this as shown in @sobolevn's answer

    RUN . /venv/bin/activate && poetry install --no-root $(test "$YOUR_ENV" == production && echo "--no-dev")
    

    after adding the appropriate environment variable declaration.

    The example uses debian-slim's as base, however, adapting this to alpine-based image should be a trivial task.

提交回复
热议问题