我在 Ubuntu 14.04.1 LTS 和内核 3.13.0-4 上使用 Docker 1.4.1。
考虑以下 Dockerfile
FROM debian:wheezy
VOLUME /var/myvol
# RUN mkdir /var/myvol
# copy content to volume
ADD foo /var/myvol/foo
# create user, and make it new owner of directory
RUN useradd nonroot \
&& chown -R nonroot:nonroot /var/myvol/ \
&& ls -al /var/myvol
# switch to new user
USER nonroot
# remove directory owned by user
RUN ls -al /var/myvol && rm /var/myvol/foo && ls -al /var/myvol
并用
touch foo
docker build -t test .
那么结果输出是
Step 0 : FROM debian:wheezy
---> c90d655b99b2
Step 1 : VOLUME /var/myvol
---> Running in d3bc83df9451
---> b860e18186d8
Removing intermediate container d3bc83df9451
Step 2 : ADD foo /var/myvol/foo
---> aded36dba841
Removing intermediate container db5dd1b08958
Step 3 : RUN useradd nonroot && chown -R nonroot:nonroot /var/myvol/ && ls -al /var/myvol
---> Running in 148941cb7858
total 8
drwxr-xr-x 2 nonroot nonroot 4096 Feb 6 09:55 .
drwxr-xr-x 13 root root 4096 Feb 6 09:55 ..
-rw-rw-r-- 1 nonroot nonroot 0 Feb 6 09:30 foo
---> 144e4ff90439
Removing intermediate container 148941cb7858
Step 4 : USER nonroot
---> Running in 924f317b6718
---> 345c1586c69f
Removing intermediate container 924f317b6718
Step 5 : RUN ls -al /var/myvol && rm /var/myvol/foo && ls -al /var/myvol
---> Running in 16c8c2349f27
total 8
drwxr-xr-x 2 root root 4096 Feb 6 09:55 .
drwxr-xr-x 13 root root 4096 Feb 6 09:55 ..
-rw-rw-r-- 1 root root 0 Feb 6 09:30 foo
rm: cannot remove `/var/myvol/foo': Permission denied
INFO[0000] The command [/bin/sh -c ls -al /var/myvol && rm /var/myvol/foo && ls -al /var/myvol] returned a non-zero code: 1
如果我用下面的注释行替换 VOLUME 行,它就可以完美运行。真正奇怪的是
ls -al
的输出:虽然第一个说所有者是非 root,但第二个输出所有者为 root,所以 chown
命令似乎以某种方式被丢弃或切换到新用户后重置权限。我是否以错误的方式理解 Docker 卷?是否只允许 root 使用它们,或者这可能是我应该报告的错误?
[编辑]
我想要实现的是使用卷作为容器化服务的数据存储。此服务不需要以 root 身份运行(因此我更喜欢使用非 root 用户),但是 是 删除不再需要的目录和文件。
最佳答案
当您将目录声明为 VOLUME
时,您实际上无法再在 Dockerfile 中使用它。根本原因是卷是在容器运行时设置的,而不是构建的。
在这种情况下,您可以简单地移动 VOLUME
Dockerfile 末尾的语句。当容器启动时,该目录中镜像中的任何数据都将被复制到卷中。
关于docker - 无法将 Docker Volume 目录的所有者更改为非 root 用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28363079/