dockerdockerfiledockerhubgit-revision

passing $SOURCE_COMMIT to Dockerfile commands on docker hub


I am building docker image for a service at hub.docker.com. During compilation, the commit hash of the source is passed as an argument to CMake (so that it can be embedded in the version information). According to Advanced options for Autobuild and Autotest, the commit hash is automatically available as SOURCE_COMMIT environment variable.

In order to call cmake with that information, it is going as follows -- I am not sure this labyrinth is the most straightforward way:

1. hooks/build

This takes care of actually passing the variable to docker build (taken from this example):

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

2. Dockerfile

The value is grabbed using those two lines:

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

and finally is passed to cmake in

RUN cmake -DGIT_REVISION_HASH=$SOURCE_COMMIT # and so on ...

In summary, an environment variable of the builder shell is passed as build argument, then obtained and assigned to inner shell environment variable which is then expanded and passed as cmake argument.

Did I miss something or does it have to be this complex?


Solution

  • This is how I've always done it too. I don't think there's another way.

    In fact, I think it was intended to be this way.

    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