Skip to content

Instantly share code, notes, and snippets.

@atedja
Last active July 20, 2018 06:05
Show Gist options
  • Save atedja/a464ca2682589d2f528e to your computer and use it in GitHub Desktop.
Save atedja/a464ca2682589d2f528e to your computer and use it in GitHub Desktop.
Dockerize script that can be used to build and push a Docker image from any Git repo that has a Dockerfile. This script uses the git commit sha as the docker tag.
#!/bin/bash
# dockerize
# Albert Tedja <albert@siliconaxon.com>
# Color stuff
yellow='\e[1;33m'
nc='\e[0m'
color=$yellow
ctrl_c () {
echo
info "CTRL-C pressed. TERMINATED BY USER"
exit $?
}
trap ctrl_c INT
info () {
echo -e "${color}[dockerize] ${1}${nc}"
}
# Grab flags
while getopts bpr opts; do
case ${opts} in
b) BUILD=true ;;
p) PUSH=true ;;
r) REBUILD=true ;;
esac
done
# Show usage if -b and -p are not specified
if [[ -z $BUILD ]] && [[ -z $REBUILD ]] ; then
echo -e "Simplify building, pushing, and running docker images."
echo -e "Usage:"
echo -e "\tdockerize [OPTIONS]\n"
echo -e "Options:"
echo -e "\t-b\tBuild image."
echo -e "\t-p\tPush image to the registry."
echo -e "\t-r\tRebuild by removing existing image with the same name and tag."
echo
echo -e "Example:"
echo -e "\tdockerize -bp"
exit 1
fi
# Docker user. Replace
DOCKER_USER="localhost:5000"
APPLICATION_NAME=$(basename `pwd`)
IMAGE_TAG="latest"
IMAGE_ID="${DOCKER_USER}/${APPLICATION_NAME}"
IMAGE_ID_TAG="${IMAGE_ID}:${IMAGE_TAG}"
if [ -d ".git" ]; then
info "Git Repository detected. Using the latest commit as tag"
# Construct image name and tag from git repo
GIT_REPO_NAME=$(basename `git remote show -n origin | grep Fetch | cut -d: -f2-` | sed 's/.git//')
GIT_REPO_COMMIT=$(git log -n 1 --pretty=format:"%H")
GIT_REPO_COMMIT_SHORT=${GIT_REPO_COMMIT:0:8}
APPLICATION_NAME=$GIT_REPO_NAME
IMAGE_TAG=$GIT_REPO_COMMIT_SHORT
IMAGE_ID="${DOCKER_USER}/${APPLICATION_NAME}"
IMAGE_ID_TAG="${IMAGE_ID}:${IMAGE_TAG}"
fi
info "Application name: ${APPLICATION_NAME}"
info "Commit: ${IMAGE_TAG}"
info "Image: ${IMAGE_ID_TAG}"
# Check for existing image
exist=$(docker images | grep $APPLICATION_NAME | grep $IMAGE_TAG)
# Rebuild. Always delete existing image.
if [[ -n $REBUILD ]] ; then
if [[ -n $exist ]]; then
info "Removing old image."
docker rmi $IMAGE_ID_TAG
fi
set -e
info "Building image"
docker build --no-cache -t $IMAGE_ID_TAG .
docker tag $IMAGE_ID_TAG $IMAGE_ID:latest
set +e
fi
# Build
if [[ -n $BUILD ]] ; then
if [[ -z $exist ]]; then
set -e
info "Building image"
docker build --no-cache -t $IMAGE_ID_TAG .
docker tag $IMAGE_ID_TAG $IMAGE_ID:latest
set +e
else
info "Image already exist."
fi
fi
# Push
if [[ -n $PUSH ]] ; then
info "Pushing to registry"
docker push $IMAGE_ID_TAG
docker push $IMAGE_ID:latest
fi
echo $IMAGE_ID_TAG
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment