Snippet for Fun

Docker Semantic Tag

Posted at — Aug 31, 2019

Every docker image has one or more tags to identify different images under the same image name. But the default docker build command always creates a latest tag to our newly created image. Although this latest naming is ok for the local build/development usages, we may encounter some problems in the real world, for example, how can we update the container image for a k8s deployment if the image tag is always is latest? It sounds like an easy task, but actually, it isn’t (before 1.15).

To keep an explicit and maintainable image tags history, we can follow this pattern:

{IMAGE_NAME}:{YYYYMMDD}-{git-revision}

It’s quite easy to write a build script (which you can find it in the repo too):

#!/usr/bin/bash

set -e

# the image tag to use, if it's empty, infer from the codebase (see belows)
IMAGE_TAG="$1"

# the name the docker image
IMAGE_NAME="registry.build4.fun/my-cool-project"

# path to the docker file
IMAGE_DOCKERFILE="$(pwd)/Dockerfile"

# docker build context
IMAGE_BUILDCTX="$(pwd)"

if [[ -z "$TAG" ]]
then
    date_version=$(date "+%Y%m%d")
    head_commit=$(git rev-parse --short HEAD)
    IMAGE_TAG="${date_version}-${head_commit}"
fi

docker build \
    -t "${IMAGE_NAME}:${IMAGE_TAG}" \
    -t "${IMAGE_NAME}:latest" \
    -f  "$IMAGE_DOCKERFILE" \
    "$IMAGE_BUILDCTX"

Usage example:

$ ./docker-build.sh
Sending build context to Docker daemon  3.584kB
Step 1/1 : FROM busybox
 ---> db8ee88ad75f
Successfully built db8ee88ad75f
Successfully tagged registry.build4.fun/my-cool-project:20190831-7ba8c87
Successfully tagged registry.build4.fun/my-cool-project:latest