ModuleNotFoundError when 运行 docker and poetry

ModuleNotFoundError when running docker and poetry

我在尝试 运行 我的容器时 运行 遇到错误,它说它在尝试导入时找不到模块。具体来说:

ModuleNotFoundError: No module named 'sentry_sdk'

下面是我的DockerFile,是多阶段构建的,好像是根据控制台输出安装了所有的包。

###############################################
# Base Image
###############################################
FROM tiangolo/uvicorn-gunicorn-fastapi:python3.9 as python-base

ENV PYTHONUNBUFFERED=1 \
    PYTHONDONTWRITEBYTECODE=1 \
    PIP_NO_CACHE_DIR=off \
    PIP_DISABLE_PIP_VERSION_CHECK=on \
    PIP_DEFAULT_TIMEOUT=100 \
    POETRY_VERSION=1.1.13 \
    POETRY_HOME="/opt/poetry" \
    POETRY_VIRTUALENVS_IN_PROJECT=true \
    POETRY_NO_INTERACTION=1 \
    PYSETUP_PATH="/opt/pysetup" \
    VENV_PATH="/opt/pysetup/.venv"

# prepend poetry and venv to path
ENV PATH="$POETRY_HOME/bin:$VENV_PATH/bin:$PATH"

###############################################
# Builder Image
###############################################
FROM python-base as builder-base

# install poetry - respects $POETRY_VERSION & $POETRY_HOME
RUN curl -sSL https://install.python-poetry.org | python3 -

# copy project requirement files here to ensure they will be cached.
WORKDIR $PYSETUP_PATH
COPY pyproject.toml ./

# install runtime deps - uses $POETRY_VIRTUALENVS_IN_PROJECT internally
RUN poetry install --no-dev

###############################################
# Production Image
###############################################
FROM python-base as production
COPY --from=builder-base $PYSETUP_PATH $PYSETUP_PATH
COPY . .
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"]

我的主文件的开头如下:

from logging import getLogger
from os import environ
from typing import List

from fastapi import FastAPI
from starlette.status import HTTP_200_OK
from sentry_sdk import init as SentryInit
from sentry_sdk.integrations.asgi import SentryAsgiMiddleware
from sentry_sdk.integrations.sqlalchemy import SqlalchemyIntegration

在线失败:

从 sentry_sdk 导入 init 作为 SentryInit

这是第一行,其中包不是容器上的默认安装,因此这可能与 venv 有关,但我不确定原因或方式。

我的 pyproject.toml 看起来像这样:

[tool.poetry]
authors = ["xxx"]
name = "xxx"
description = "xxx"
version = "xxx"

[tool.poetry.dependencies]
asyncpg = "^0.21.0"
fastapi = "^0.73.0"
pydantic = "^1.9.0"
python = "^3.8.7"
sqlalchemy = "^1.3.22"
databases = "^0.5.5"
sentry-sdk = "^1.5.5"

[tool.poetry.dev-dependencies]
pytest = "^3.4"
httpx = "^0.22.0"

[build-system]
build-backend = "poetry.core.masonry.api"
requires = ["poetry-core>=1.0.0"]

好吧,我明白了,现在我觉得自己很蠢。

这个问题确实与 venv 有关,基本上,uvicorn 安装在基本图像上但没有安装在我的 pyproject.toml 中。所以 poetry 并没有安装在 venv 中。当我使用 CMD 在 Dockerfile 中启动应用程序时,它无法在 venv 中找到 uvicorn,因此转到基本安装并从那里 运行。当我将 uvicorn 添加到 venv 时,一切正常。