This shell script builds a Docker image and tags it with the short hash of the latest git commit.

It passes the short commit hash and a build timestamp as build arguments to the Dockerfile, so that you can access these in the image/container. Maybe you want to show them somewhere to see which version of the app that is running?

#!/bin/bash 

VERSION=$(git log -1 --pretty=%h)
REPO="registry.example.com/my-project:"
TAG="$REPO$VERSION"
LATEST="${REPO}latest"
BUILD_TIMESTAMP=$( date '+%F_%H:%M:%S' )
docker build -t "$TAG" -t "$LATEST" --build-arg VERSION="$VERSION" --build-arg BUILD_TIMESTAMP="$BUILD_TIMESTAMP" . 
docker push "$TAG" 
docker push "$LATEST"

It also tags the image with the latest tag, as well as the version tag.

In order to receive the build arguments in the Dockerfile, and pass them on as environment variables to the image, you need to use these lines in your Dockerfile:

...
ARG VERSION
ENV VERSION $VERSION
ARG BUILD_TIMESTAMP
ENV BUILD_TIMESTAMP $BUILD_TIMESTAMP
...

Now you can simply run this shell script to build and tag your image automatically. I use this for all my projects ✅👌