将 $SOURCE_COMMIT 传递给 docker 集线器上的 Dockerfile 命令

passing $SOURCE_COMMIT to Dockerfile commands on docker hub

我正在为 hub.docker.com 的服务构建 docker 图像。在编译期间,源的提交哈希作为参数传递给 CMake(以便它可以嵌入版本信息中)。根据 Advanced options for Autobuild and Autotest,提交哈希自动用作 SOURCE_COMMIT 环境变量。

为了使用该信息调用 cmake,过程如下——我不确定这个迷宫是最直接的方法:

1。 hooks/build

这负责将变量实际传递给 docker 构建(取自 this example):

#!/bin/bash
docker build  --build-arg SOURCE_COMMIT=$SOURCE_COMMIT -f $DOCKERFILE_PATH -t $IMAGE_NAME .

2。 Dockerfile

使用这两行获取值:

ARG SOURCE_COMMIT                  # get it from the --build-arg
ENV SOURCE_COMMIT $SOURCE_COMMIT   # set shell variable (of the same name)

最后在

中传递给cmake
RUN cmake -DGIT_REVISION_HASH=$SOURCE_COMMIT # and so on ...

总而言之,builder shell 的环境变量作为构建参数传递,然后获取并分配给内部 shell 环境变量,然后展开并作为 cmake 参数传递。

我是不是漏掉了什么,还是一定要这么复杂?

我也一直这样做。我认为没有其他方法。

其实我觉得本来就是这样的

The ARG instruction defines a variable that users can pass at build-time to the builder with the docker build command using the --build-arg = flag. If a user specifies a build argument that was not defined in the Dockerfile, the build outputs a warning.

Docs