先回答第一个问题:
> 如果 docker 中的用户名交 dockeruser 宿主机没有这个用户,他是怎么映射的呢?按照 uid 吗?
是的,按照 uid 来映射。默认从 uid=0 开始映射,宿主机的 uid=0,1,2,... 映射为容器的 uid=0,1,2,...。你可以通过 `--userns-remap` 选项来改变这个行为,比如说可以指定宿主机的 uid=1000,1001,1002,... 映射为容器的 uid=0,1,2,...。
第二个问题:
> 所以在容器内就是 root 权限了,怎么避免呢?
事实确实是这样的,你可以参考 LWN 的这篇文章:[User namespaces + overlayfs = root privileges](
https://lwn.net/Articles/671641/)。这一点其实在 Docker 官方给出的 [Docker daemon attack surface](
https://docs.docker.com/engine/security/security/) 中也已经指出来了:
> Docker allows you to share a directory between the Docker host and a guest container; and it allows you to do so without limiting the access rights of the container. This means that you can start a container where the /host directory is the / directory on your host; and the container can alter your host filesystem without any restriction. This is similar to how virtualization systems allow filesystem resource sharing. Nothing prevents you from sharing your root filesystem (or even your root block device) with a virtual machine.
那么,怎么避免呢?一种方案是,可以在运行容器的时候通过 `--user` 选项指定非 root 用户名和组。另外,挂载 volumes 的时候遵循 Principle of Least Privilege 是一个好习惯:尽量避免挂载系统重要的目录或文件,如果实在需要,不妨使用只读挂载。