如何在 docker 容器中导入 python 模块 运行 脚本?

How to import python module running script in docker container?

我需要在 docker 容器中 运行 python 脚本。该脚本导入了 psutil 模块。我创建了图像,在 运行 处理它之后出现错误:

File "/usr/src/app/metrics.py", line 1, in <module>
   import psutil
ModuleNotFoundError: No module named 'psutil'

我的脚本在本地有效,因为我通过 "python -m pip install psutil" 命令安装了这个模块。我试图通过以下方式在 docker 文件中模拟此操作:"CMD python -m pip install psutil" 但它不起作用。我究竟做错了什么? Dockerfile 内容:

FROM python:3.8.2-buster
WORKDIR /usr/src/app
COPY metrics.py .
RUN pip install --upgrade pip
CMD python -m pip install psutil
CMD python /usr/src/app/metrics.py

根据https://docs.docker.com/engine/reference/builder/"There can only be one CMD instruction in a Dockerfile. If you list more than one CMD then only the last CMD will take effect."

也许您只想使用另一个 RUN 安装 psutil

FROM python:3.8.2-buster
WORKDIR /usr/src/app
COPY metrics.py .
RUN pip install --upgrade pip
RUN python -m pip install psutil
CMD python /usr/src/app/metrics.py