Docker Community Forums

Share and learn in the Docker community.

Access git tag/commit from Dockerfile during build without git binary

I would like my Docker image to be aware of the git tag/commit that originated the build, but without having a git binary to read it. Is there any way to pass that information in a variable into the Dockerfile?

I assume that the git binary is only missing in your image, but present on your build system.

For automated builds on Docker Hub, I use a pre_build hook that exports the reference with VCS_REF=$(git rev-parse --short HEAD). Then I pass the variable as a build arg into the build process. Inside the Dockerfile I assign the ARG to a LABEL (your could assign it to an ENV as well).

1 Like

Thanks, that is what I was looking.

I think the basic version only requires hooks/build:

docker build --build-arg VCS_REF=$(git rev-parse --short HEAD) -f $DOCKERFILE_PATH -t $IMAGE_NAME .

Agree, it is sufficient to use it direcly in the build hook.

I just have a pre commit hook, because I prepare a couple of details, like
– modifiying the tag depending on the source branch (SOURCE_BRANCH=$(git symbolic-ref -q --short HEAD))
– populate a variable to store the build date (BUILD_DATE=$(date -u +"%Y-%m-%dT%H:%M:%SZ"))
– change the image tag in the README.MD which will be used as description on Docker Hub (this could be done for an example docker-compose.yml as well)

My images use the build meta-data as suggested from

1 Like

Seems like the meta-data from were superseded in favor of You can find the list of suggested labels here:

Since still depends on the labels of, for time beeing I will stick with those.