首页 > 解决方案 > 如何将 sudo 特权用户和组添加到 docker 容器中

问题描述

我正在尝试写我的第一个Dockerfile. 但我失败得很惨。我只是想避免在容器内使用root用户。这是我手动执行的操作,如何使用 来实现这些步骤Dockerfile

启动 ubuntu 基础镜像:
docker run -dit --name "my-container" -p 3000:3000 ubuntu:16.04

输入它:
docker exec -it my-container /bin/bash

然后我正在执行以下步骤:

export DEBIAN_FRONTEND=noninteractive *(without adding these there were many error, warnings while installing packages)*
apt-get update && apt-get install -y sudo curl git
adduser myuser
usermod -aG sudo myuser
su myuser
cd ~

我的用户已设置。所以我再也不会重新登录到 root 用户,而是使用我新创建的用户。然后我安装 nodejs、yarn 包管理器,最后克隆我的 repo 并运行代码。

curl -sL https://deb.nodesource.com/setup_8.x | sudo -E bash - *(These steps asks user sudo password)*
sudo apt-get install -y nodejs
curl -sS https://dl.yarnpkg.com/debian/pubkey.gpg | sudo apt-key add -
echo "deb https://dl.yarnpkg.com/debian/ stable main" | sudo tee /etc/apt/sources.list.d/yarn.list
sudo apt-get update && sudo apt-get install yarn
git clone https://github.com/myaccount/myrepo.git
cd myrepo
yarn install
yarn build
yarn start

这是我打算用这张图片做的基本例程。
在这里,我试图将我的步骤复制到Dockerfile

FROM ubuntu:16.04
ARG DEBIAN_FRONTEND=noninteractive
RUN apt-get update && \
    apt-get install -y sudo curl git
RUN useradd -ms /bin/bash myuser && echo "myuser:myuser" | chpasswd && adduser myuser sudo (I just copy pasted this line from other question)
USER myuser
WORKDIR /home/myuser
RUN curl -sL https://deb.nodesource.com/setup_8.x | sudo -E bash - && \
    sudo apt-get install -y nodejs && \
    curl -sS https://dl.yarnpkg.com/debian/pubkey.gpg | sudo apt-key add - && \
    echo "deb https://dl.yarnpkg.com/debian/ stable main" | sudo tee /etc/apt/sources.list.d/yarn.list && \
    sudo apt-get update && sudo apt-get install yarn && \
    sudo rm -rf /var/lib/apt/lists/*
RUN git clone https://github.com/myaccount/myrepo.git && \
    cd myrepo && \
    yarn install && \
    yarn build
CMD ["yarn", "start"]
EXPOSE 3000

但它在步骤 7/10 上给了我这个错误:
sudo: no tty present and no askpass program specified
The command '/bin/sh -c curl -sL https://deb.nodesource.com/setup_8.x | sudo -E bash - && sudo apt-get install -y nodejs && curl -sS https://dl.yarnpkg.com/debian/pubkey.gpg | sudo apt-key add - && echo "deb https://dl.yarnpkg.com/debian/ stable main" | sudo tee /etc/apt/sources.list.d/yarn.list && sudo apt-get update && sudo apt-get install yarn && sudo rm -rf /var/lib/apt/lists/*' returned a non-zero code: 1

很抱歉这么长的帖子,请让我对此有所了解

标签: ubuntudockerdocker-composedockerfile

解决方案


你得到一个明确的错误:

sudo: no tty present and no askpass program specified

如果您要搜索确切的错误消息,您会发现当您的sudoers配置requiretty设置了标志时会发生这种情况。您可以在手册页的SUDOERS OPTIONS部分阅读更多相关信息。

然而:

我什至需要费心创建新用户吗?在容器内以 root 用户身份运行就可以了吗?

root构建过程中运行绝对没问题。在某些情况下,您可能希望创建一个非 root 用户以在运行容器时使用,但sudo在您的容器中使用没有意义Dockerfile(因为您已经在运行 as root)。

如何在图像中添加 sudo 特权新用户和组。

您已经在做正确的事情:创建一个新用户并将该用户添加到sudoers组中。


推荐阅读