【问题标题】:dockerfile copy list of files, when list is taken from a local filedockerfile 复制文件列表,当列表取自本地文件时
【发布时间】:2021-09-21 04:55:01
【问题描述】:

我有一个包含路径列表的文件,我需要通过 Dockerfile 的 COPY 命令在 docker build 上复制这些路径。

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

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

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

谢谢!

【问题讨论】:

  • 当你构建图像时,它要做的唯一一件事是什么?为什么你需要安装多组包依赖项?如果该图像有多个应用程序,那么为每个应用程序(和一个 requirements.txt 文件)设置一个单独的图像是否更有意义?

标签: bash docker dockerfile docker-copy


【解决方案1】:

COPY directive 允许它开箱即用的意义上这是不可能的,但是如果您知道扩展名,则可以在路径中使用通配符,例如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))

【讨论】:

  • 这是一个非常灵活但仍然非常易读的解决方案。与多级配对,我现在可以想象可能性。谢谢你!
【解决方案2】:

例如,您可能希望这样做:

FROM ...
ARG files
COPY files

并运行

docker build -build-args items=`${cat list_of_files_to_copy.txt}`

【讨论】:

  • 请注意,环境变量(至少在 Windows 上)have length limitdoesn't seem to be one for Linux 严格取决于 Docker 如何检索值以及 Docker 或底层操作系统发行版是否实施任何限制。此外,如果只是cated,名称中的空格/空格也会导致问题。
  • 一般来说这是一个不错的选择,但是如果需求文件都具有相同的名称(并且它们是并且我无法控制它),那么它们将相互运行。我的情况就是这样。还是谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-05-13
  • 1970-01-01
  • 2021-06-03
  • 2020-01-01
  • 2013-09-17
  • 2021-11-16
  • 1970-01-01
相关资源
最近更新 更多