我正在使用一个Docker映像,它是使用USER命令构建的,以使用一个称为dev的非根用户。 在容器中,我是“dev”,但我想编辑/etc/hosts文件。

所以我需要是根。我正在尝试su命令,但要求我输入根密码。

Docker容器中root用户的默认密码是什么?


当前回答

您可以以根用户身份SSH进入docker容器

docker exec -it --user root <container_id> /bin/bash

然后使用此命令修改root密码

passwd root

通过输入确保sudo已安装

sudo

如果没有安装,请安装

apt-get install sudo

如果需要为用户dev赋予sudo权限,可以将用户dev添加到sudo组

usermod -aG sudo dev

现在,您可以在容器内从您的开发用户运行sudo级别的命令,或者您可以使用前面设置的密码在容器内切换到root。

要测试它,请以用户dev登录,并列出根目录的内容,通常只有根用户才能访问。

sudo ls -la /root

输入dev的密码

如果您的用户在正确的组中,并且您正确地输入了密码,那么您使用sudo发出的命令应该以root权限运行。

其他回答

获取正在运行的容器的外壳并更改根通道。

docker exec -u 0 -it <MyContainer> bash

root@MyContainer:/# passwd
Enter new UNIX password: 
Retype new UNIX password: 

'ubuntu'用户的密码是'ubuntu'(至少在docker中ubuntu:14.04.03)。

注意:'ubuntu'是在容器启动后创建的,所以,如果你这样做:

 docker run -i -t --entrypoint /bin/bash  ubuntu     

您将直接得到根提示符。在这里你可以强制修改root用户的密码,提交容器并将其标记为ubuntu:latest(使用-f),如下所示:

root@ec384466fbbb:~# passwd
Enter new UNIX password:
Retype new UNIX password:
passwd: password updated successfully
root@ec384466fbbb:~# exit

% docker commit ec3844
5d3c03e7d6d861ce519fe33b184cd477b8ad03247ffe19b2a57d3f0992d71bca

docker tag -f 5d3c ubuntu:latest

你必须重新构建你对ubuntu:latest的最终依赖。

你也可以这样使用它(如果你需要确认密码)

(echo 'myrootpassword'; echo 'myrootpassword') | passwd root

我确实遇到了无法su到root的问题,因为我是作为无特权用户在容器中运行的。

但我不想像之前的答案所暗示的那样重建一个新的形象。

相反,我发现我可以使用'nsenter'作为根访问容器,参见:https://github.com/jpetazzo/nsenter

首先确定主机上容器的PID:

docker inspect --format {{.State.Pid}} <container_name_or_ID>

然后使用nsenter以root身份进入容器

nsenter --target <PID> --mount --uts --ipc --net --pid

有几种方法可以做到。

运行覆盖USER设置的Docker docker exec -u 0 -it containerName bash

or

docker exec -u root -it --workdir / <containerName> bash

在Docker文件的镜像构建过程中,设置必要的文件权限等 如果您的Linux映像中所有的包都可用,那么在dockerfile中USER实用程序之前输入chpasswin。

完整参考:http://muralitechblog.com/root-password-of-a-docker-container/