Skip to content

Instantly share code, notes, and snippets.

@NicolasTr
Last active September 13, 2022 22:10
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save NicolasTr/0e9b82f186ea7e057debcde902c119f4 to your computer and use it in GitHub Desktop.
Save NicolasTr/0e9b82f186ea7e057debcde902c119f4 to your computer and use it in GitHub Desktop.
#!/bin/bash -e
# Fast Docker builds on CircleCI
# See this blog post: https://www.tresegnie.com/docker-circleci-speed-cost/
export CONTEXT_FOLDER=???
export IMAGE_NAME=???
export COMMIT_TAG=${CIRCLE_SHA1}
export BRANCH_TAG=${CIRCLE_BRANCH}
# Calculate a content hash of the docker context to avoid pulling/building
# if a docker image with the same context and dockerfile exist on the registry
#
# To test locally on mac, install sha1sum
# brew install md5sha1sum
export CONTENT_HASH=$(\
find domains/${DOMAIN_NAME}/services/${SERVICE_NAME} \( -type l -o -type f \) -print0 \
| sort -z \
| xargs -0 sha1sum \
| sha1sum \
| awk '{ print $1 }' \
)
if ! docker manifest inspect ${IMAGE_NAME}:${CONTENT_HASH}
then
docker pull ${IMAGE_NAME}:${COMMIT_TAG} \
|| docker pull ${IMAGE_NAME}:${BRANCH_TAG} \
|| docker pull ${IMAGE_NAME}:main \
|| true
DOCKER_BUILD_EXTRA_PARAMS=$(docker images \
| grep ${IMAGE_NAME} \
| head -n 1 \
| awk '{ print "--cache-from=" $1 ":" $2 }' || true)
docker build ${DOCKER_BUILD_EXTRA_PARAMS} -t ${IMAGE_NAME}:${CONTENT_HASH} domains/${DOMAIN_NAME}/services/${SERVICE_NAME}
# Not stricly necessary as we are pushing the tags directly to the registry. However, it's still good
# to set them as other scripts might be run after this one.
docker tag ${IMAGE_NAME}:${CONTENT_HASH} ${IMAGE_NAME}:${COMMIT_TAG}
docker tag ${IMAGE_NAME}:${CONTENT_HASH} ${IMAGE_NAME}:${BRANCH_TAG}
docker push ${IMAGE_NAME}:${CONTENT_HASH}
fi
# Tag the images directly in the registry
docker buildx imagetools create ${IMAGE_NAME}:${CONTENT_HASH} \
--tag ${IMAGE_NAME}:${COMMIT_TAG}
docker buildx imagetools create ${IMAGE_NAME}:${CONTENT_HASH} \
--tag ${IMAGE_NAME}:${BRANCH_TAG}
@NicolasTr
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment