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:

#!/bin/bash
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 http://label-schema.org.

1 Like

Seems like the meta-data from http://label-schema.org were superseded in favor of https://github.com/opencontainers/image-spec. You can find the list of suggested labels here: https://github.com/opencontainers/image-spec/blob/master/annotations.md

Since https://microbadger.com still depends on the labels of label-schema.org, for time beeing I will stick with those.