为什么在 Docker 镜像中“pip install”后 python 无法找到所需的模块?

问题描述 投票:0回答:1

我的 Python 存在一个问题,即它在容器中运行时找不到任何依赖项。就我而言,我有一个基于 fastAPI 的应用程序,可以在我的本地计算机上完美运行。当我启动 docker 映像时,只要我不在映像中执行单独的“pip install xyz”,它就会抱怨每个模块。

我有以下 Dockerfile:

# Use the official Python image from the Docker Hub
FROM python:3.12-slim as builder

# Set environment variables
ENV PYTHONDONTWRITEBYTECODE=1
ENV PYTHONUNBUFFERED=1

# Install build dependencies
RUN apt-get update \
    && apt-get install -y --no-install-recommends gcc libpq-dev

# Create a working directory
WORKDIR /app

# Install pipenv and python dependencies in a virtual environment
COPY ./requirements.txt /app/
RUN python3 -m venv venv && bash -c "source venv/bin/activate"
RUN venv/bin/pip3 install -r requirements.txt

# Use the official Python image again for the final stage
FROM python:3.12-slim

# Set environment variables
ENV PYTHONDONTWRITEBYTECODE=1
ENV PYTHONUNBUFFERED=1

# Create a working directory
WORKDIR /app

# Copy installed dependencies from the builder stage
COPY --from=builder /usr/local/lib/python3.12/site-packages /usr/local/lib/python3.12/site-packages
COPY --from=builder /usr/local/bin/pip /usr/local/bin/pip

# Copy the application code
COPY . /app

# Install runtime dependencies (if any)
RUN pip install uvicorn gunicorn

# Expose the port the app runs on
EXPOSE 8000

# Command to run the application
CMD ["gunicorn", "-k", "uvicorn.workers.UvicornWorker", "main:app", "--bind", "0.0.0.0:8000", "--workers", "4"]

我的文件requirements.txt包含所有必需的模块,例如

...
fastapi==0.111.0
fastapi-cli==0.0.4
filelock==3.14.0
...
pydub==0.25.1
Pygments==2.18.0
python-dotenv==1.0.1
python-multipart==0.0.9
PyYAML==6.0.1
requests==2.32.3
rich==13.7.1
...

我用以下方法构建了容器:

docker build -t my-fastapi-app .

我运行容器:

docker run -p 8000:8000 my-fastapi-app

它打印一个长调用堆栈,结尾为:

ModuleNotFoundError: No module named 'requests'

然后我将在 Dockerfile 中使用单独的“pip install”添加模块:

RUN pip install pydub requests

现在它抱怨缺少 fastAPI:

ModuleNotFoundError: No module named 'fastapi'

所以我要添加另一个

pip install
以及 fastAPI 等等。

然后我尝试使用pipenv

COPY ./Pipfile /app
COPY ./Pipfile.lock /app

RUN pip install --upgrade pip \
    && pip install pipenv \
    && pipenv install --deploy --ignore-pipfile

必要的 Pipfile 包含所有必需的模块,但安装后它们仍然丢失。

我以为

pip install -r requirements.txt
会自动完成这一切。但这里的情况并非如此。我的错误在哪里?

我是否必须对“requirements.txt”中列出的所有模块使用单独的“pip install”命令来炸毁我的 Dockerfile?

或者虚拟环境只是搞砸了,Python 虽然安装了但找不到任何模块?

python docker pip fastapi pipenv
1个回答
0
投票

您将东西安装到 virtualenv 中,然后将系统包目录(当时没有这些 deps)复制到运行时容器中。

复制 virtualenv(然后使用它)。

RUN python3 -m venv /venv
RUN /venv/bin/pip3 install -r requirements.txt

# Use the official Python image again for the final stage
FROM python:3.12-slim
# ...
COPY --from=builder /venv /venv
# ...
RUN /venv/bin/python -m pip install uvicorn gunicorn
# ...
CMD ["/venv/bin/gunicorn", "-k", "uvicorn.workers.UvicornWorker", "main:app", "--bind", "0.0.0.0:8000", "--workers", "4"]
© www.soinside.com 2019 - 2024. All rights reserved.