Understanding the build.sh script
The build.sh script is available at https://github.com/the-gigi/delinkcious/blob/master/build.sh.
Let's examine it bit by bit. There are several best practices we will follow here. First, it's a good idea to add a shebang with the path of the binary that will execute your script – that is, if you know where it is located. If you try to write a cross-platform script that works on many different platforms, you may need to rely on the path or other techniques. set -eo pipefail will fail out immediately (even in the middle of a pipe) if anything goes wrong.
This is highly recommended for production environments:
#!/bin/bash
set -eo pipefail
The next few lines just set some variables for directories and the tags for the Docker images. There are two tags: STABLE_TAB and TAG. The STABLE_TAG tag has a major and minor version and doesn't change in every build. The TAG includes the CIRCLE_BUILD_NUM provided by CircleCI and is incremented in every build. This means that the TAG is always unique. This is considered a best practice for tagging and versioning images:
IMAGE_PREFIX='g1g1'
STABLE_TAG='0.2'
TAG="${STABLE_TAG}.${CIRCLE_BUILD_NUM}"
ROOT_DIR="$(pwd)"
SVC_DIR="${ROOT_DIR}/svc"
Next, we go to the svc directory, which is the parent directory of all our services, and log in to DockerHub using the environment variables we set in the CircleCI project.
cd $SVC_DIR
docker login -u $DOCKERHUB_USERNAME -p $DOCKERHUB_PASSWORD
Now, we get to the main event. The script iterates over all the subdirectories of the svc directory looking for Dockerfile. If it finds a Dockerfile, it builds an image, tags it using a combination of service name and both TAG and STABLE_TAG, and finally pushes the tagged images to the registry:
cd "${SVC_DIR}/$svc"
if [[ ! -f Dockerfile ]]; then
continue
fi
UNTAGGED_IMAGE=$(echo "${IMAGE_PREFIX}/delinkcious-${svc}" | sed -e 's/_/-/g' -e 's/-service//g')
STABLE_IMAGE="${UNTAGGED_IMAGE}:${STABLE_TAG}"
IMAGE="${UNTAGGED_IMAGE}:${TAG}"
docker build -t "$IMAGE" .
docker tag "${IMAGE}" "${STABLE_IMAGE}"
docker push "${IMAGE}"
docker push "${STABLE_IMAGE}"
done
cd $ROOT_DIR