How to Version your Docker Images

While there are probably a thousand ways to do this, I’m going to show you a very simple way, using things that have become quite common. It will also ensure your images versions match your Git version tags so you know exactly which code is actually inside the image.

This assumes you already have a Dockerfile that builds your image.

Version File

First, create a VERSION file with nothing in it but the version numbers:

0.0.1

We’ll want to store this VERSION file in the image for completeness (and your program can use it to display the version), so add the following to your Dockerfile:

ADD VERSION .

That will add the VERSION file to your WORKDIR.

Build Script

If you don’t already have a build script, create one and call it build.sh. The simplest form of this is just to run your docker build:

set -ex
# SET THE FOLLOWING VARIABLES
# docker hub username
USERNAME=treeder
# image name
IMAGE=helloworld
docker build -t $USERNAME/$IMAGE:latest .

You may require some extra build steps in there so just go ahead and add them. Or you may have your own build script, in which case you can ignore this script and just change the line in the script below to run your build. And be sure to chmod a+x ./build.sh so you can run it.

Release Script

Now, let’s create a simple release script called release.sh that when run, will bump the version, run your build script, set git tags, push tags to GitHub, build the image, and push the image to Docker Hub. You can copy and paste the script below, just change the values at the top to match your Docker Hub information:

set -ex
# SET THE FOLLOWING VARIABLES
# docker hub username
USERNAME=treeder
# image name
IMAGE=helloworld
# ensure we're up to date
git pull
# bump version
docker run --rm -v "$PWD":/app treeder/bump patch
version=`cat VERSION`
echo "version: $version"
# run build
./build.sh
# tag it
git add -A
git commit -m "version $version"
git tag -a "$version" -m "version $version"
git push
git push --tags
docker tag $USERNAME/$IMAGE:latest $USERNAME/$IMAGE:$version
# push it
docker push $USERNAME/$IMAGE:latest
docker push $USERNAME/$IMAGE:$version

Make it executable with chmod a+x ./release.sh then run it with ./release.sh .

And there you have it. Every time you do a release, run ./release.sh and you’ll have nicely versioned images that match up with your source code.