【问题标题】:`--chown` option of COPY and ADD doesn't allow variables. There exists a workaround?COPY 和 ADD 的 `--chown` 选项不允许使用变量。有解决方法吗?
【发布时间】:2019-05-22 15:08:46
【问题描述】:

在 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

但这是不可能的。有解决方法吗?

注意我知道一种可能的解决方法是将目录复制为 root,然后在目录上运行 chown(变量适用于 RUN)。但是,图像的大小会增加,只是为了在单独的命令中使用 chown。

【问题讨论】:

    标签: dockerfile docker-copy


    【解决方案1】:

    您可以在运行--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 .
    

    并验证文件是否被 chown'ed

    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
    

    注意:有一个开放的功能请求来添加此功能: issue #35018 "允许通过 ENV 或 ARG 动态填充 COPY 命令的 --chown"

    【讨论】:

    • 我几乎有同样的问题。从某种意义上说,myuser 不能被$USERNAME 之类的变量替换。但是,拥有一个固定的用户名称对我来说不是问题。我需要的是一个可变的用户 ID 和组 ID。长话短说:您解决了我的问题,但这只是因为用户名可以在我的用例中修复。
    • 您是否要更改 UID/GID,因为(在开发期间)您想让它们与您的本地用户匹配(并将您的源绑定安装在容器内)?你可能对这个肮脏的把戏感兴趣(来自@bmitch); sudo-bmitch.github.io/presentations/dc2018eu/…整个演示文稿值得一读(你也可以在GitHub上找到它github.com/sudo-bmitch/presentations
    猜你喜欢
    • 2023-02-25
    • 2015-08-15
    • 1970-01-01
    • 2015-10-12
    • 1970-01-01
    • 1970-01-01
    • 2021-06-18
    • 2019-03-25
    • 2015-08-01
    相关资源
    最近更新 更多