COPY 和 ADD 的 `--chown` 选项不允许变量。有解决方法吗?
`--chown` option of COPY and ADD doesn't allow variables. There exists a workaround?
在 Dockerfile 中,以非 root 用户(例如 $UID 1000)复制目录的常用方法如下:
COPY --chown=1000:1000 /path/to/host/dir/ /path/to/container/dir
但是,我想改用变量。例如
ARG USER_ID=1000
ARG GROUP_ID=1000
COPY --chown=${USER_ID}:${GROUP_ID} /path/to/host/dir/ /path/to/container/dir
但这是不可能的。有解决方法吗?
注意 我知道一个可能的解决方法是将目录复制为根目录,然后 运行 chown 在目录上(变量适用于 RUN
).但是,图像的大小会增加,只是为了在单独的命令中使用 chown。
您可以在 运行 --chown
;
之前创建用户
mkdir -p test && cd test
mkdir -p path/to/host/dir/
touch path/to/host/dir/myfile
创建您的 Dockerfile:
FROM busybox
ARG USER_ID=1000
ARG GROUP_ID=1000
RUN addgroup -g ${GROUP_ID} mygroup \
&& adduser -D myuser -u ${USER_ID} -g myuser -G mygroup -s /bin/sh -h /
COPY --chown=myuser:mygroup /path/to/host/dir/ /path/to/container/dir
构建图像
docker build -t example .
或使用自定义构建它 UID/GID:
docker build -t example --build-arg USER_ID=1234 --build-arg GROUP_ID=2345 .
并验证文件是否已更改
docker run --rm example ls -la /path/to/container/dir
total 8
drwxr-xr-x 2 myuser mygroup 4096 Dec 22 16:08 .
drwxr-xr-x 3 root root 4096 Dec 22 16:08 ..
-rw-r--r-- 1 myuser mygroup 0 Dec 22 15:51 myfile
验证它是否具有正确的 uid/gid:
docker run --rm example ls -lan /path/to/container/dir
total 8
drwxr-xr-x 2 1234 2345 4096 Dec 22 16:08 .
drwxr-xr-x 3 0 0 4096 Dec 22 16:08 ..
-rw-r--r-- 1 1234 2345 0 Dec 22 15:51 myfile
Note: there is an open feature-request for adding this functionality:
issue #35018 "Allow COPY command's --chown to be dynamically populated via ENV or ARG"
在 Dockerfile 中,以非 root 用户(例如 $UID 1000)复制目录的常用方法如下:
COPY --chown=1000:1000 /path/to/host/dir/ /path/to/container/dir
但是,我想改用变量。例如
ARG USER_ID=1000
ARG GROUP_ID=1000
COPY --chown=${USER_ID}:${GROUP_ID} /path/to/host/dir/ /path/to/container/dir
但这是不可能的。有解决方法吗?
注意 我知道一个可能的解决方法是将目录复制为根目录,然后 运行 chown 在目录上(变量适用于 RUN
).但是,图像的大小会增加,只是为了在单独的命令中使用 chown。
您可以在 运行 --chown
;
mkdir -p test && cd test
mkdir -p path/to/host/dir/
touch path/to/host/dir/myfile
创建您的 Dockerfile:
FROM busybox
ARG USER_ID=1000
ARG GROUP_ID=1000
RUN addgroup -g ${GROUP_ID} mygroup \
&& adduser -D myuser -u ${USER_ID} -g myuser -G mygroup -s /bin/sh -h /
COPY --chown=myuser:mygroup /path/to/host/dir/ /path/to/container/dir
构建图像
docker build -t example .
或使用自定义构建它 UID/GID:
docker build -t example --build-arg USER_ID=1234 --build-arg GROUP_ID=2345 .
并验证文件是否已更改
docker run --rm example ls -la /path/to/container/dir
total 8
drwxr-xr-x 2 myuser mygroup 4096 Dec 22 16:08 .
drwxr-xr-x 3 root root 4096 Dec 22 16:08 ..
-rw-r--r-- 1 myuser mygroup 0 Dec 22 15:51 myfile
验证它是否具有正确的 uid/gid:
docker run --rm example ls -lan /path/to/container/dir
total 8
drwxr-xr-x 2 1234 2345 4096 Dec 22 16:08 .
drwxr-xr-x 3 0 0 4096 Dec 22 16:08 ..
-rw-r--r-- 1 1234 2345 0 Dec 22 15:51 myfile
Note: there is an open feature-request for adding this functionality: issue #35018 "Allow COPY command's --chown to be dynamically populated via ENV or ARG"