Docker 运行时的用户与组管理的方法

2020-06-17 06:41:42易采站长站整理

普通用户 docker run 容器内指定不同用户 demo_user


docker run --user=demo_user:group1 --group-add group2 <image_name> <command>

这里的 demo_user 和 group1(主组), group2(副组) 不是主机的用户和组, 而是创建容器镜像时创建的.

当Dockerfile里没有通过USER指令指定运行用户时, 容器会以 root 用户运行进程.

docker 指定用户的方式

Dockerfile 中指定用户运行特定的命令


USER <user>[:<group>] #或
USER <UID>[:<GID>]

docker run -u(–user)[user:group] 或 –group-add 参数方式


$ docker run busybox cat /etc/passwd
root:x:0:0:root:/root:/bin/sh
...
www-data:x:33:33:www-data:/var/www:/bin/false
nobody:x:65534:65534:nobody:/home:/bin/false

$ docker run --user www-data busybox id
uid=33(www-data) gid=33(www-data)

docker 容器内用户的权限

对比以下情况, host 中普通用户创建的文件, 到 docker 容器下映射成了 root 用户属主:


$ mkdir test && touch test/a.txt && cd test
$ docker run --rm -it -v `pwd`:/mnt -w /mnt busybox /bin/sh -c 'ls -al /mnt/*'
-rw-r--r-- 1 root root 0 Oct 22 15:36 /mnt/a.txt

而在容器内卷目录中创建的文件, 则对应 host 当前执行 docker 的用户:


$ docker run --rm -it -v `pwd`:/mnt -w /mnt busybox /bin/sh -c 'touch b.txt'
$ ls -al
-rw-r--r-- 1 xwx staff 0 10 22 23:36 a.txt
-rw-r--r-- 1 xwx staff 0 10 22 23:54 b.txt

docker volume 文件访问权限

创建和使用卷, docker 不支持相对路径的挂载点, 多个容器可以同时使用同一个卷.


$ docker volume create hello #创建卷

hello

$ docker run -it --rm -v hello:/world -w /world busybox /bin/sh -c 'touch /world/a.txt && ls -al' #容器内建个文件
total 8
drwxr-xr-x 2 root root 4096 Oct 22 16:38 .
drwxr-xr-x 1 root root 4096 Oct 22 16:38 ..
-rw-r--r-- 1 root root 0 Oct 22 16:38 a.txt

$ docker run -it --rm -v hello:/world -w /world busybox /bin/sh -c 'rm /world/a.txt && ls -al' #从容器内删除
total 8
drwxr-xr-x 2 root root 4096 Oct 22 16:38 .
drwxr-xr-x 1 root root 4096 Oct 22 16:38 ..

外部创建文件, 容器内指定用户去删除


$ touch c.txt && sudo chmod root:wheel c.txt
$ docker run -u 100 -it --rm -v `pwd`:/world -w /world busybox /bin/sh -c 'rm /world/c.txt && ls -al'