部署容器时安装的pip包不可用

Installed pip packages are not available when deploying the container

在我的 Dockerfile 中我有:

FROM python:3.7
RUN apt update
RUN apt install -y git

RUN groupadd -g 1001 myuser
RUN useradd -u 1001 -g 1001 -ms /bin/bash myuser
USER 1001:1001
USER myuser
WORKDIR /home/myuser

COPY --chown=myuser:myuser requirements.txt ./

ENV PYTHONPATH="/home/myuser/.local/lib/python3.7/site-packages:.:$PYTHONPATH"
RUN python3.7 -m pip install -r requirements.txt
COPY --chown=myuser:myuser  . .

ENV PATH="/home/myuser/.local/bin/:$PATH"

ENV HOME=/home/myuser
ENV PYTHONHASHSEED=1
EXPOSE 8001
CMD [ "python3.7", "app.py" ]

在构建过程中,pip list 正确显示所有库:

basicauth       0.4.1
pip             21.1.1
python-dateutil 2.8.1
pytz            2019.1
PyYAML          5.1.1
requests        2.22.0
setuptools      56.0.0
six             1.16.0
urllib3         1.25.11
wheel           0.36.2

但是一旦 OpenShift 部署了容器,我只安装了以下库:

WARNING: The directory '/home/myuser/.cache/pip' or its parent directory is not owned or is not writable by the current user. The cache has been disabled. Check the permissions and owner of that directory. If executing pip with sudo, you should use sudo's -H flag.
Package    Version
---------- -------
pip        21.1.1
setuptools 56.0.0
wheel      0.36.2

CMD 命令按预期运行,但安装了 none 个包...

Traceback (most recent call last :
File "app.py", line 16, in ‹module>
import requests
ModuleNotFoundError: No module named 'requests'

修改后的 Dockerfile 更符合标准做法:

FROM python:3.7

RUN apt update && \ 
    apt install -y --no-install-recommends git && \
    rm -rf /var/lib/apt/lists/*

WORKDIR /app
COPY requirements.txt .
RUN python3.7 -m pip install -r requirements.txt
COPY . .

ENV PYTHONHASHSEED=1
USER nobody
CMD [ "python3.7", "app.py" ]

我合并了初始 RUN 图层以获得较小的图像,并在退出图层之前清理了 apt 列表。包以 root 身份全局安装,然后只有在它更改为运行时用户之后。在这种情况下,除非您非常明确地需要一个 homedir,否则我会坚持使用 nobody/65534 作为表达“低权限运行时用户”的标准方式。

请记住,OpenShift 会覆盖容器级 USER 信息 https://www.openshift.com/blog/a-guide-to-openshift-and-uids