Labelling automated builds on Docker Hub
Automated builds are a popular feature on Docker Hub that build a new Docker image whenever a new commit is pushed to a git repository on GitHub or BitBucket.
Docker labels are a powerful mechanism for adding metadata to your containers. As the New Stack says there are now some good practices for using them at label-schema.org. Build hooks allow you to generate up-to-date labels at build-time. So that your metadata is updated automatically as part of the automated build process.
Why use an automated build?
An automated build avoids the manual work of building, tagging and pushing Docker images. It also makes it easier to keep the code in your images in sync with the code in your version control system. Lastly there are some important security benefits if you rebuild your images regularly to incorporate security updates.
If you’re interested in automating your Docker build processes MicroBadger provides image change notifications. We check public Docker images you’re interested in and call your webhook if they change. You can use this to trigger a build in your CI system or notify your team via Slack. Your first notification is free and you can join our private beta if you’d like more.
How widely used are automated builds?
Our research shows 26% of the the 410k public images on Docker Hub are using automated builds. They account for 32% of the 5.5 billion image pulls, 28% are official image pulls and the remaining 40% are pulls for non automated builds.
What’s the issue with labels?
In general labelling your images is straightforward, using the LABEL command in your Dockerfile. However there are 2 label-schema.org labels that are very useful but need to be dynamic. These are org.label-schema.build-date and org.label-schema.vcs-ref.
The vcs-ref lets you link your image to the code used to build it. The build-date is useful for several reasons. If your Dockerfile installs operating system packages your image might contain different versions depending on when it was built. Another example is when managing images at scale you might want to know all images in use that were built over, say, 3 months ago.
For sensible reasons Docker don’t allow dynamic code to run in the Dockerfile. Instead the ARG command is provided to pass data into the Dockerfile. This is easy when building images locally but for automated builds you need to use a build hook script.
How does the hook work?
Create a file called /hooks/build relative to your Dockerfile. This overrides the Docker build process so your script needs to build and tag the image.
# $IMAGE_NAME var is injected into the build so the tag is correct.
docker build --build-arg VCS_REF=`git rev-parse — short HEAD` \
--build-arg BUILD_DATE=`date -u +”%Y-%m-%dT%H:%M:%SZ”` \
-t $IMAGE_NAME .