I have been building some python Docker images recently. Best practice is obviously not to run containers as root user and remove sudo privileges from the non-privileged user.
But I have been wondering what's the best way to go about this.
Here is an example 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"]
So my questions are:
Is installing packages with apt-get as root ok or should these be installed with the non-privileged user (with sudo which later should be removed)?
Best location to install these packages, i.e. /usr/local/ (as default when installing as root) or would it be preferable to install in user home?
When installing python packages with pip as root, I get the following warning
WARNING: Running pip as the 'root' user can result in broken permissions and conflicting behaviour with the system package manager. It is recommended to use a virtual environment instead: https://pip.pypa.io/warnings/venv(However I don't need a venv since the docker image is already isolated for a single service, so I guess I can just ignore that warning).Anything else I am missing or should be aware of?
NB: the bind mounted workspace is only for development, for a production image I would copy the necessary files/artifacts into the image/container.
Thanks