Created
July 18, 2024 16:25
-
-
Save mbround18/80a83f452323fef63f62a87361756a7d to your computer and use it in GitHub Desktop.
Docker compose caching via yq
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env bash | |
# Check for Docker CLI | |
if ! command -v docker &> /dev/null | |
then | |
echo "Docker CLI not found. Please install Docker." | |
exit 1 | |
fi | |
# Check for yq CLI | |
if ! command -v yq &> /dev/null | |
then | |
echo "yq CLI not found. Please install yq." | |
exit 1 | |
fi | |
# Check for docker-compose.yaml | |
if [ ! -f ./docker-compose.yaml ]; then | |
echo "docker-compose.yaml not found. Please ensure the file exists in the current directory." | |
exit 1 | |
fi | |
# Set up necessary environment variables if not already set | |
: "${DOCKER_IMAGE:=your_default_docker_image}" | |
: "${DOCKER_REGISTRY:=your_default_docker_registry}" | |
: "${DOCKER_USER:=your_default_docker_user}" | |
: "${DOCKER_PASSWORD:=your_default_docker_password}" | |
# Preflight script for cacher-preflight | |
working_dir=$(dirname "$(realpath ./docker-compose.yaml)") | |
temp_file="$working_dir/docker-compose.caching.yaml" | |
export CACHE_COMPOSE_PATH=$temp_file | |
export DOCKER_BUILDKIT=1 | |
# Copy into cache path, and add caching | |
cp ./docker-compose.yaml $CACHE_COMPOSE_PATH | |
services=$(yq -r '.services | keys | .[]' ./docker-compose.yaml) | |
for service in $services; do | |
yq eval -i ".services.${service}.build.cache_from[0] = \"type=registry,ref=$DOCKER_IMAGE:${service}-buildcache\"" $CACHE_COMPOSE_PATH | |
yq eval -i ".services.${service}.build.cache_to[0] = \"type=registry,ref=$DOCKER_IMAGE:${service}-buildcache,mode=max\"" $CACHE_COMPOSE_PATH | |
done | |
# Build script for build | |
docker buildx create --use | |
# After using buildx, you will need to relogin into docker. | |
echo "$DOCKER_PASSWORD" | docker login -u "$DOCKER_USER" --password-stdin $DOCKER_REGISTRY | |
docker compose -f $CACHE_COMPOSE_PATH build | |
docker compose -f $CACHE_COMPOSE_PATH push |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment