首页 > 解决方案 > 在 Docker 构建中使用 pip install 时出现 ModuleNotFoundError

问题描述

因此,我遇到了许多讨论这个特定问题的线程,但无法真正找到适合我的修复方法。

我在根目录的 requirements.txt 文件中总结了以下要求

stripe==2.51.0
bottle==0.12.18

我的 src/app.py 以

from bottle import route, run, template, get, post, request, response, static_file
import stripe

# rest of the code I assume isn't relevant

我正在使用 Dockerfile 构建图像,如下所示:

#  build 1
FROM python:3.8.5 AS builder
COPY requirements.txt .
RUN python -m pip install --user -r requirements.txt

# build 2
FROM python:3.8.5-slim
COPY --from=builder /root/.local/bin /root/.local
COPY ./src .

EXPOSE 8080
ENV PATH=/root/.local:$PATH
CMD [ "python", "app.py" ]

即使我--user将根路径添加到最终路径中,我仍然会遇到以下错误:

ModuleNotFoundError: No module named 'bottle'

我也 - 我认为 - 在安装我的包和运行它们时使用相同的解释器,所以我真的不知道如何解决这个问题。

任何指向正确方向的指针将不胜感激。

非常感谢各位!

标签: dockerbuildpipdockerfilerequirements.txt

解决方案


进行以下更改:

COPY --from=builder /root/.local /root/.local
ENV PATH=/root/.local/bin:$PATH

建议:使用slim-buster,你的 Dockerfile 可以这样结束:

FROM python:3.8.5-slim-buster AS base

FROM base AS builder
COPY requirements.txt .
RUN python -m pip install --user -r requirements.txt

FROM base AS release
COPY --from=builder /root/.local /root/.local
COPY ./src .
EXPOSE 8080
ENV PATH=/root/.local/bin:$PATH
CMD [ "python", "app.py" ]

推荐阅读