让非 root 用户在 Docker 中写入 linux 主机

Let non-root user write to linux host in Docker

我创建了一个 OpenSuse 42.3 docker 容器映像,它只有一个用户,我们称之为 'streamuser'。我希望这是每当有人从我的图像创建容器时处于活动状态的用户。我已将主机的主目录挂载到 streamuser 的主目录。我遇到的问题是,如果我 运行 Docker 主机上的 Docker 容器,streamuser 无法向主机目录写入任何内容。这是因为 streamuser 不与主机共享相同的 UID 和 GID。有没有一种干净的方法来解决这个问题,避免我将图像中的默认用户帐户设置为 root 帐户?如果我在容器中以 root 身份登录,那么我可以写入 linux 主机,但这是不可取的。

我的 docker 电话是:

docker run  -it -d --name ${containerName}  --user="streamuser"         \
    --workdir="/home/streamuser" --volume="${home}:/home/streamuser"    \
    ${imageName}  /bin/bash -rcfile /opt/Codebase/image_env_setup_v206.sh

我看到有人使用 --volume 选项将主机密码、sudoers 等文件传递到容器的解决方案。我不喜欢这个选项,因为它会覆盖我在容器中制作的环境,而且它看起来像是一个笨拙的解决方案。

我的docker文件是:

FROM opensuse:42.3

RUN zypper update -y && \
    zypper install -y \
    sudo \
    vim \
    gcc-fortran \
    infinipath-psm-devel \
    openmpi \
    openmpi-devel \
    openmpi-libs \
    hdf5-openmpi \
    blas-devel \
    blas-devel-static \
    lapack-devel \
    which

RUN echo "root:streamuser_2017" | chpasswd
RUN useradd -m streamuser
RUN passwd -d streamuser
CMD /bin/bash

RUN mkdir -p -m0755 \
    /opt/codeA/lib \
    /opt/codeA/bin \
    /opt/codeB/lib \
    /opt/codeC/lib \
    /opt/codeC/bin \
    /opt/petsc/lib

USER streamuser
WORKDIR /home/streamuser

RUN source $HOME/.bashrc

COPY ./Docker/critical_dependencies/codeA_lib/* /opt/codeA/lib/
COPY ./Docker/critical_dependencies/codeA_bin/* /opt/codeA/bin/
COPY ./Docker/critical_dependencies/codeB_lib/* /opt/codeB/lib/
COPY ./Docker/critical_dependencies/petsc_lib/* /opt/petsc/lib/
COPY ./lib/* /opt/codeC/lib/
COPY ./bin/* /opt/codeC/bin/
COPY ./Docker/image_env_setup_v206.sh /opt/codeC

RUN source /opt/codeC/image_env_setup_v206.sh

您可以在您的 Dockerfile 映像中添加 fixuid (by Caleb Lloyd)。
moby/moby issue 7198:

We have created a workaround for this issue that changes a Docker container's user/group and file permissions that were set at build time to the UID/GID that the container was started with at runtime.

The project and install instructions are at: https://github.com/boxboat/fixuid

Example:

  • Docker container was built using user/group dockeruser:dockergroup as UID/GID 1000:1000.
  • Host is running as UID/GID 1001:1002.
  • Image is run with docker run -u 1001:1002.

fixuid will:

  • change dockeruser UID to 1001
  • change dockergroup GID to 1002
  • change all file permissions for old dockeruser:dockergroup to 1001:1002
  • update $HOME inside container to dockeruser $HOME
  • now container and host UID/GID match and files created in the container on host mounts will match.

It can run as the ENTRYPOINT or as part of a startup script. It is installed in the container as a binary owned by root with the setuid bit, and escalates privileges to make the appropriate changes. It should only be used in development containers.