可以从Dockerfile中的清单或白名单复制文件吗?

huangapple go评论49阅读模式
英文:

Is it possible to copy files from a manifest or whitelist in a Dockerfile?

问题

Docker支持使用.dockerignore文件来排除COPY命令中的文件。我所要找的是相反的操作:一种从清单中白名单或复制文件的方式。

可以通过运行以下命令来创建这样的清单:

git ls-files > files-to-include.txt

Dockerfile语法是否支持这样的功能?还是有其他方法可以实现相同的结果?

英文:

I know that docker supports a .dockerignore file to exclude files for COPY commands. What I am looking for is opposite: a way to whitelist or copy files from a manifest.

One can create such a manifest by running:

git ls-files > files-to-include.txt

Does the Dockerfile syntax support such feature? Or is there another way to get the same result?

答案1

得分: 1

以下是已翻译的内容:

没有内置的方法来实现这一点。但是,通过一些小的修改,你可以创建一个"反向dockerignore文件",就像这样:

include.sh

#!/usr/bin/env sh

FILE=.dockerignore

# 添加git索引文件
git ls-files > $FILE
# 在每一行前面添加NOT符号以保留
sed -i 's/^/!/' $FILE
# 在文件中添加*作为第一行
sed -i '1s/^/*\n&/' $FILE

.dockerignore

结果类似于以下内容:

*
!.dockerignore
!.gitignore
!Dockerfile
!LICENSE
!README.md
!bin/action.sh
!bin/commitlint
!commitlint-plugin-tense/blacklist.txt
!commitlint-plugin-tense/index.js
!commitlint-plugin-tense/index.test.js
!commitlint-plugin-tense/package-lock.json
!commitlint-plugin-tense/package.json
!commitlint.config.js
!package.json
!yarn.lock

结论

第一行的 * 忽略所有文件。前缀为 ! 的每个后续行告诉 Docker 不要忽略给定的文件。结果基本上是一个要在 Dockerfile 中使用 COPY 指令添加的文件白名单。需要注意的主要事项是,当添加或删除文件时,此文件可能会迅速过时,需要不断维护。

英文:

There is no built-in way to do this. However, with a little hacking you can create an "inverse dockerignore file" like this:

include.sh

#!/usr/bin/env sh

FILE=.dockerignore

# add git indexed files
git ls-files > $FILE
# add NOT symbol in front of each line to keep
sed -i 's/^/!/' $FILE
# add * as the first line in the file
sed -i '1s/^/*\n&/' $FILE

.dockerignore

The result is something like this:

*
!.dockerignore
!.gitignore
!Dockerfile
!LICENSE
!README.md
!bin/action.sh
!bin/commitlint
!commitlint-plugin-tense/blacklist.txt
!commitlint-plugin-tense/index.js
!commitlint-plugin-tense/index.test.js
!commitlint-plugin-tense/package-lock.json
!commitlint-plugin-tense/package.json
!commitlint.config.js
!package.json
!yarn.lock

Conclusion

The first line * ignores all files. Each subsequent line in the prefixed with ! tells Docker to NOT ignore the given file. The result is essentially a whitelist of files to add using COPY directive in a Dockerfile. The main thing to watch out for is that this file can quickly become obsolete when adding or removing files and would have to be constantly maintained.

huangapple
  • 本文由 发表于 2023年5月11日 11:35:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/76223991.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定