通常,docker容器使用root用户运行。我想使用一个不同的用户,这是没有问题使用docker的user指令。但是这个用户应该能够在容器内使用sudo。该命令缺失。

下面是一个简单的Dockerfile:

FROM ubuntu:12.04

RUN useradd docker && echo "docker:docker" | chpasswd
RUN mkdir -p /home/docker && chown -R docker:docker /home/docker

USER docker
CMD /bin/bash

运行这个容器,我以用户“docker”登录。当我尝试使用sudo时,没有找到该命令。所以我尝试在我的Dockerfile中使用sudo包安装

RUN apt-get install sudo

这将导致无法定位包sudo


当前回答

如果您有一个以root身份运行的容器,该容器运行一个需要访问sudo命令的脚本(您不能更改),您可以简单地在您的$PATH中创建一个新的sudo脚本,该脚本调用传递的命令。

在Dockerfile中:

RUN if type sudo 2>/dev/null; then \ 
     echo "The sudo command already exists... Skipping."; \
    else \
     echo -e "#!/bin/sh\n\${@}" > /usr/sbin/sudo; \
     chmod +x /usr/sbin/sudo; \
    fi

其他回答

下面是我如何使用ubuntu:18.04的基本映像来设置一个非root用户:

RUN \
    groupadd -g 999 foo && useradd -u 999 -g foo -G sudo -m -s /bin/bash foo && \
    sed -i /etc/sudoers -re 's/^%sudo.*/%sudo ALL=(ALL:ALL) NOPASSWD: ALL/g' && \
    sed -i /etc/sudoers -re 's/^root.*/root ALL=(ALL:ALL) NOPASSWD: ALL/g' && \
    sed -i /etc/sudoers -re 's/^#includedir.*/## **Removed the include directive** ##"/g' && \
    echo "foo ALL=(ALL) NOPASSWD: ALL" >> /etc/sudoers && \
    echo "Customized the sudoers file for passwordless access to the foo user!" && \
    echo "foo user:";  su - foo -c id

上面的代码发生了什么:

创建用户和组foo。 用户foo被加入到foo组和sudo组中。 uid和gid设置为999。 主目录设置为“/home/foo”。 shell被设置为/bin/bash sed命令对/etc/sudoers文件进行内联更新,以允许foo和root用户无密码访问sudo组。 sed命令禁用#includedir指令,该指令将允许子目录中的任何文件覆盖这些内联更新。

如果您有一个以root身份运行的容器,该容器运行一个需要访问sudo命令的脚本(您不能更改),您可以简单地在您的$PATH中创建一个新的sudo脚本,该脚本调用传递的命令。

在Dockerfile中:

RUN if type sudo 2>/dev/null; then \ 
     echo "The sudo command already exists... Skipping."; \
    else \
     echo -e "#!/bin/sh\n\${@}" > /usr/sbin/sudo; \
     chmod +x /usr/sbin/sudo; \
    fi

如何在CentOS上做到这一点还没有答案。 在Centos上,您可以在Dockerfile中添加以下内容

RUN echo "user ALL=(root) NOPASSWD:ALL" > /etc/sudoers.d/user && \
    chmod 0440 /etc/sudoers.d/user

当容器中sudo和apt-get都不可用时,还可以使用命令以根用户身份跳转到正在运行的容器

docker exec -u root -t -i container_id /bin/bash

其他答案对我不起作用。我继续搜索,发现了一篇博客文章,介绍了一个团队如何在docker容器中运行非root。

这是TL;DR版本:

RUN apt-get update \
 && apt-get install -y sudo

RUN adduser --disabled-password --gecos '' docker
RUN adduser docker sudo
RUN echo '%sudo ALL=(ALL) NOPASSWD:ALL' >> /etc/sudoers

USER docker

# this is where I was running into problems with the other approaches
RUN sudo apt-get update 

为此,我使用FROM node:9.3,但我怀疑其他类似的容器基础也可以工作。