通常,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


当前回答

如果SUDO或apt-get在容器内不可访问,您可以在运行的容器中使用下面的选项。

docker exec -u root -it f83b5c5bf413 ash

“f83b5c5bf413”是我的容器ID,这里是我的终端的工作示例:

其他回答

主要思想是,您需要根据容器创建一个根用户。

主要命令:

RUN echo "bot:bot" | chpasswd
RUN adduser bot sudo

第一个将字面值bot:bot发送给chpasswd, chpasswd创建了用户bot,密码为bot, chpasswd做的是:

The chpasswd command reads a list of user name and password pairs from standard input and uses this information to update a group of existing users. Each line is of the format:

user_name:password

By default the supplied password must be in clear-text, and is encrypted by chpasswd. Also the password age will be updated, if present.

我假设第二个命令将用户bot添加为sudo。

完整的docker容器来玩:

FROM continuumio/miniconda3
# FROM --platform=linux/amd64 continuumio/miniconda3

MAINTAINER Brando Miranda "me@gmail.com"

RUN apt-get update \
  && apt-get install -y --no-install-recommends \
    ssh \
    git \
    m4 \
    libgmp-dev \
    opam \
    wget \
    ca-certificates \
    rsync \
    strace \
    gcc \
    rlwrap \
    sudo

# https://github.com/giampaolo/psutil/pull/2103

RUN useradd -m bot
# format for chpasswd user_name:password
RUN echo "bot:bot" | chpasswd
RUN adduser bot sudo

WORKDIR /home/bot
USER bot
#CMD /bin/bash

如果SUDO或apt-get在容器内不可访问,您可以在运行的容器中使用下面的选项。

docker exec -u root -it f83b5c5bf413 ash

“f83b5c5bf413”是我的容器ID,这里是我的终端的工作示例:

刚刚明白。正如regan指出的,我必须将用户添加到sudoers组。但主要原因是我忘记更新存储库缓存,所以apt-get找不到sudo包。现在起作用了。以下是完整的代码:

FROM ubuntu:12.04

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

RUN useradd -m docker && echo "docker:docker" | chpasswd && adduser docker sudo

USER docker
CMD /bin/bash

如果您有一个以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

这可能不适用于所有映像,但有些映像已经包含根用户,例如jupyterhub/singleuser映像。对于这个图像,它很简单:

USER root
RUN sudo apt-get update