簡體   English   中英

運行docker和詩時出現ModuleNotFoundError

[英]ModuleNotFoundError when running docker and poetry

我在嘗試運行我的容器時遇到錯誤,它說它在嘗試導入時找不到模塊。 具體來說:

ModuleNotFoundError: No module named 'sentry_sdk'

下面是我的 DockerFile 是多階段構建的,好像是按照控制台 output 安裝了所有的包。

###############################################
# 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

這是第一行,其中 package 不是容器上的默認安裝,因此這可能與 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中。 當我在 Dockerfile 中使用 CMD 啟動應用程序時,它無法在 venv 中找到 uvicorn,因此轉到基本安裝並從那里運行。 當我將 uvicorn 添加到 venv 時,一切正常。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM