bash - dockerfile 复制文件列表,当列表取自本地文件时
问题描述
我有一个文件,其中包含我需要通过 Dockerfile 的COPY
命令复制的路径列表docker build
。
我的用例是这样的:我有一个 pythonrequirements.txt
文件,当我在项目内部调用多个其他需求文件时,使用-r PATH
.
现在,我想COPY
单独 docker 所有需求文件,运行 pip install,然后复制项目的其余部分(用于缓存等)。到目前为止,我还没有设法使用 dockerCOPY
命令做到这一点。
从文件中获取路径不需要帮助-我已经做到了-只要可以做到-如何?
谢谢!
解决方案
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-string、format()
函数或切换到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))
推荐阅读
- gcc - 将静态库文件添加到 makefile
- tfs - TFS2017 Sonarqube 代码覆盖率未显示
- php - vTigerCRM 7 - 除非手动触发,否则调度程序不会运行任何 cron 作业
- angular - Angular 6,如何在子组件上测试父发射器?
- git - Git 将我的工作从某个提交转移到一个单独的分支,而无需从当前父级进行更改
- excel - Excel - 仅在看到特定数字后才对列中的数字求和
- r - ggplot2 重命名 x 轴刻度会更改图表外观
- scala - 通过对存储在列表中的字段宽度值进行切片/拆分,将 apache-spark 数据帧字符串列拆分为多列
- sql-server - T-SQL 查询检查被锁定的表或资源的历史数据
- go - 接口的同义结构字段和方法名称