docker exec 的默认用户是什么?

What's the default user for docker exec?

调用docker exec(没有--user)时root是默认用户吗?

Dockerfile 中的 USER 行是否影响 docker exec 的默认用户?

Does a USER line in the Dockerfile affect the default user for docker exec?

是的,as the docs mention:

The USER instruction sets the user name (or UID) and optionally the user group (or GID) to use when running the image and for any RUN, CMD and ENTRYPOINT instructions that follow it in the Dockerfile.

这是一个创建用户并将其设为 运行 用户的 Dockerfile 示例。

cat Dockerfile
FROM ubuntu:latest
RUN useradd -r sathya
USER sathya

构建图像

docker build -t sathya:user .
Sending build context to Docker daemon  19.46kB
Step 1/3 : FROM ubuntu:latest
 ---> 113a43faa138
Step 2/3 : RUN useradd -r sathya
 ---> Running in 5b72508a891d
Removing intermediate container 5b72508a891d
 ---> b81692196e13
Step 3/3 : USER sathya
 ---> Running in d43d399a86ac
Removing intermediate container d43d399a86ac
 ---> c0388a898992
Successfully built c0388a898992
Successfully tagged sathya:user

运行一个容器

docker run -it -d sathya:user bash
0903e85fa4de4bb820f015f3ff2bbca9eb2c038814ff7ea809519334687597c7

执行容器。看到 运行ning 用户是指定的默认用户

docker exec -it 0903e85fa4de bash
sathya@0903e85fa4de:/$ whoami
sathya

docker exec 中的默认用户与用于启动容器的用户相同,可以在 docker 运行 或您的撰写文件中设置。

如果你在启动容器时没有明确设置用户,它会默认为镜像中配置的用户,你可以检查镜像来查找。这是由 Dockerfile 中的最后一个 USER 行配置的。它也可以由 FROM 行指定的父图像配置。

如果图像和 运行 命令均未指定用户,则 docker 默认为 root,uid 0。