如何将 Docker 构建的上下文定义为本地分支之一的特定提交?

dsi*_*cos 5 git docker

我想使用引用本地存储库的提交哈希来提供 Docker 构建命令的上下文。

涵盖 Docker 构建的文档指定如何引用远程存储库上而不是本地存储库上的分支或标签。参考

我尝试用协议替换 URLfile://以引用本地 git 存储库,但这会返回错误

docker build file:///home/username/repositories/hello-world

错误

无法准备上下文:找不到路径“file:///home/username/repositories/hello-world”

我想将本地 Git 存储库(特定提交、标签或分支)作为 Docker 构建映像的构建上下文。

我已经看过这个问题Docker build Specific local gitbranch但我不希望必须克隆或签出分支来从中构建。

Eri*_*kMD 3

我确认file://url 前缀未被 识别为 (Git) URL docker build

\n\n

相关的代码片段

\n\n
validPrefixes = map[string][]string{\n    "url": {"http://", "https://"},\n\n    // The github.com/ prefix is a special case used to treat context-paths\n    // starting with `github.com` as a git URL if the given path does not\n    // exist locally. The "github.com/" prefix is kept for backward compatibility,\n    // and is a legacy feature.\n    //\n    // Going forward, no additional prefixes should be added, and users should\n    // be encouraged to use explicit URLs (https://github.com/user/repo.git) instead.\n    "git": {"git://", "github.com/", "git@"},\n\n    [\xe2\x80\xa6]\n
Run Code Online (Sandbox Code Playgroud)\n\n

一方面,git clone支持git clone /home/path/repo.gitgit clone file:///home/path/repo.git\xe2\x88\x92 ,并且实际上两种语法之间的行为不同,因为前者暗示了标志--local顺便说一句,我在这里使用措辞repo.git而不是repo/.git,因为为了简单起见,我假设这repo.git是一个裸存储库,即没有签出的工作目录)。

\n\n

因此,您可能想要打开一个功能请求以moby支持docker build file:///home/path/repo.git(这将触发git clone file:///home/path/repo.git),以便我们甚至可以指定类似的内容docker build file:///home/path/repo.git#master:folder/subfolder

\n\n

另一方面,您已经可以通过依赖 的“STDIN 模式”docker build,结合一些Bash 进程替换和 with git archive(它不会修改存储库本身,因此它应该满足您的要求)以有效的方式模拟此功能没有分行结账):

\n\n
docker build -t image - < <(cd /home/path/repo.git && \\\n  git archive --format=tar.gz master:folder/subfolder)\n
Run Code Online (Sandbox Code Playgroud)\n\n

在这种情况下,请注意,Dockerfile将考虑的是 Git 存储库,位于master路径下的分支中folder/subfolder

\n\n

实际上,“重定向+进程替换”\xe2\x80\xa6 < <(\xe2\x80\xa6)是不需要的,可以用管道代替:

\n\n
cd /home/path/repo.git && \\\ngit archive --format=tar.gz master:folder/subfolder | docker build -t image -\n
Run Code Online (Sandbox Code Playgroud)\n\n

:folder/subfolder(如果您Dockerfile位于存储库的根目录,则可以删除该部分)

\n