最近我一直在构建一些Python Docker镜像。最佳实践显然是不要以root用户身份运行容器,并从非特权用户中删除sudo权限。
但是我一直在想最好的方法是什么。
这里是一个示例Dockerfile:
FROM python:3.10
## get UID/GID of host user for remapping to access bindmounts on host
ARG UID
ARG GID
## add a user with same GID and UID as the host user that owns the workspace files on the host (bind mount)
RUN adduser --uid ${UID} --gid ${GID} --no-create-home flaskuser
RUN usermod -aG sudo flaskuser
## install packages as root?
RUN apt update \
&& apt upgrade -y \
&& apt-get install -y --no-install-recommends python3-pip \
#&& [... install some packages ...]
&& apt-get install -y uwsgi-plugin-python3 \
## cleanup
&& apt-get clean \
&& apt-get autoclean \
&& apt-get autoremove --purge -y \
&& rm -rf /var/lib/apt/lists/*
## change to workspace folder and copy requirements.txt
WORKDIR /workspace/web
COPY ./requirements.txt /tmp/requirements.txt
RUN chown flaskuser:users /tmp/requirements.txt
## Install python packages as root?
RUN python3 -m pip install --disable-pip-version-check --no-cache-dir -r /tmp/requirements.txt
RUN chmod -R 777 /usr/local/lib/python3.11/site-packages/*
ENV PYTHONUNBUFFERED 1
ENV PYTHONPATH "${PYTHONPATH}:/workspace/web"
ENV PYTHONPATH "${PYTHONPATH}:/usr/local/lib/python3.10/site-packages"
## change to non-priviliged user to run container
USER flaskuser
CMD ["uwsgi", "uwsgi.ini"]
我的问题如下:
- 使用apt-get以root用户安装软件包是否可行,或者应该使用非特权用户(使用sudo,稍后应该删除)进行安装?
- 最佳位置将这些软件包安装在哪里,例如/usr/local/(作为默认安装时作为root),还是更好地安装在用户主目录中?
- 当使用pip作为root安装Python软件包时,我收到以下警告:
WARNING:使用'root'用户运行pip可能会导致权限破坏和与系统包管理器冲突的行为。建议使用虚拟环境:https://pip.pypa.io/warnings/venv
(但是,由于Docker映像已经为单个服务隔离,因此我认为可以忽略该警告,不需要虚拟环境)。 - 还有什么其他内容我需要了解吗?
谢谢