【问题标题】:Is there a way to ADD/COPY both directory and file in a single ADD/COPY command (dockerfile)?有没有办法在单个 ADD/COPY 命令(dockerfile)中同时添加/复制目录和文件?
【发布时间】:2020-09-20 15:02:54
【问题描述】:

在我的 dockerfile 中,我试图将文件和目录添加/复制到destinationFolder。预期输出为:

destinationFolder/test.txt
destinationFolder/test_dir/*

但是,在ADD command (as mentioned in note) 中,目录本身并没有被复制,只是它的内容。

ADD test.txt test_dir /destinationFolder/

有没有办法使用单个 ADD/COPY 命令实现所需的输出?

【问题讨论】:

    标签: docker dockerfile docker-image docker-build


    【解决方案1】:

    2 个解决方案,具体取决于您当前项目目录的确切内容。不过,基线是相同的:将所有内容放在同一个目录中,然后将该目录的内容直接推送到图像中的目标目录。

    此外,如Docker best practice 中所述,如果您不需要任何最新的特殊功能,我建议您使用COPY 而不是ADD

    将您的内容移至单独的文件夹

    您要推送到目标文件夹的所有内容都可以放在您一次推送的专用文件夹中:

    在您的项目目录中,您可以

    mkdir imageContents
    mv test.text test_dir imageContents
    

    然后你修改你的 Dockerfile:

    COPY imageContents destinationFolder/
    

    从您的项目根目录复制确切的结构

    除了将根目录或项目直接推送到映像之外,这个想法是相同的。这也适用于您放在那里的任何其他文件夹,并且不会被忽略。请注意,您可以将其用于现有文件夹结构,以简单地添加一些文件(例如在 /etc/ 结构中)。

    创建一个.dockerignore 文件以确保您只复制相关内容:

    .dockerignore
    Dockerfile
    .git
    # Add any other files that should be out of context
    # Dummy examples below
    .yamllint
    mysecretfiles
    

    根据您的情况,重新创建要推送到图像的确切文件结构:

    mkdir destinationFolder
    mv test.txt test_dir destinationFolder
    

    最终添加一些您想要推送到图像的其他文件

    mkdir -p etc/myapp
    echo "config1=myvalue" > etc/myapp/myapp.conf
    

    并将你的 Docker 文件修改为:

    COPY . /
    

    制作自己的方法

    您可以轻松地混合使用上述两种方法,以满足您对图像文件中任何目标的确切需求。

    【讨论】:

    • 如何创建带有 * 的 .dockerfile 以忽略所有文件。然后 !filename.txt / !folder_name 以便只有那些文件/文件夹在构建上下文中可用。随后我们可以做 ADD 。 .
    • 这是你的 .dockeringnore,请自助 :) ADD 无论如何都可以在任何一种情况下完成。 Docker 文档只是说明,如果您不绝对需要 ADD 的特殊功能,您应该更喜欢 COPY
    • 通过 ADD 的特殊权力,你是指URLs吗?
    • 我的意思是我在回答中引用的链接中所写的内容:That’s because it’s more transparent than ADD. COPY only supports the basic copying of local files into the container, while ADD has some features (like local-only tar extraction and remote URL support) that are not immediately obvious. Consequently, the best use for ADD is local tar file auto-extraction into the image, as in ADD rootfs.tar.xz /
    猜你喜欢
    • 2021-05-06
    • 2019-02-16
    • 2018-11-02
    • 1970-01-01
    • 1970-01-01
    • 2019-08-29
    • 1970-01-01
    • 2016-03-24
    • 2019-07-23
    相关资源
    最近更新 更多