首页 > 解决方案 > dockerfile 复制文件列表,当列表取自本地文件时

问题描述

我有一个文件,其中包含我需要通过 Dockerfile 的COPY命令复制的路径列表docker build

我的用例是这样的:我有一个 pythonrequirements.txt文件,当我在项目内部调用多个其他需求文件时,使用-r PATH.

现在,我想COPY单独 docker 所有需求文件,运行 pip install,然后复制项目的其余部分(用于缓存等)。到目前为止,我还没有设法使用 dockerCOPY命令做到这一点。

从文件中获取路径不需要帮助-我已经做到了-只要可以做到-如何?

谢谢!

标签: bashdockerdockerfiledocker-copy

解决方案


COPY从指令允许它开箱即用的意义上说是不可能的,但是如果您知道扩展名,您可以使用通配符作为路径,例如COPY folder*something*name somewhere/.

对于简单的requirements.txt获取,可能是:

# but you need to distinguish it somehow
# otherwise it'll overwrite the files and keep the last one
# e.g. rename package/requirements.txt to package-requirements.txt
# and it won't be an issue
COPY */requirements.txt ./
RUN for item in $(ls requirement*);do pip install -r $item;done

但是,如果它变得更复杂一些(例如仅收集特定文件,通过某些自定义模式等),那么,不会。但是,对于这种情况,只需通过简单的F-stringformat()函数或切换到Jinja使用模板,创建一个Dockerfile.tmpl(或任何您想要命名的临时文件),然后收集路径,插入模板Dockerfile并准备好转储到一个文件,然后用docker build.

例子:

# Dockerfile.tmpl
FROM alpine
{{replace}}
# organize files into coherent structures so you don't have too many COPY directives
files = {
    "pattern1": [...],
    "pattern2": [...],
    ...
}
with open("Dockerfile.tmpl", "r") as file:
    text = file.read()

insert = "\n".join([
    f"COPY {' '.join(values)} destination/{key}/"
    for key, values in files.items()
])

with open("Dockerfile", "w") as file:
    file.write(text.replace("{{replace}}", insert))

推荐阅读