Last active
September 18, 2023 13:32
-
-
Save pasdam/35f4fd0f5ca47a546fbf0df2502583cb to your computer and use it in GitHub Desktop.
docker compose up wrapper to automatically restart containers for which read-only volumes have been changed on the host machine
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
#!/bin/sh | |
print_usage() { | |
SCRIPT_NAME=$(basename "$0") | |
echo "Simple wrapper of docker compose to add labels to force the container re-creation when config files are updated" | |
echo "Example: $SCRIPT_NAME -f compose.custom.yaml up -d" | |
exit "$1" | |
} | |
FILES_ARG= | |
OTHER_ARGS= | |
while [ "$#" -gt 0 ]; do | |
case $1 in | |
-h | --help) print_usage 0 ;; | |
-f | --file) | |
FILES=$(printf "%s\n%s" "${FILES}" "$2") | |
FILES_ARG="$FILES_ARG --file $2" | |
shift | |
;; | |
*) | |
OTHER_ARGS="$OTHER_ARGS $1" | |
;; | |
esac | |
shift | |
done | |
FILES=$(printf "%s" "$FILES" | tail -n +2) # delete first new line | |
if [ -z "$FILES" ]; then | |
# use default files | |
files=( | |
./compose.yaml | |
./compose.yml | |
./docker-compose.yaml | |
./docker-compose.yml | |
) | |
for file in "${files[@]}"; do | |
if [ ! -f "$file" ]; then | |
continue | |
fi | |
FILES=$(printf "%s%s\n" "${FILES}" "$file") | |
FILES_ARG="--file $file" | |
break | |
done | |
fi | |
INITIAL_DIR=$(pwd) | |
OVERRIDE_COMPOSE_FILE="compose.local.yaml" | |
touch $OVERRIDE_COMPOSE_FILE | |
truncate -s 0 $OVERRIDE_COMPOSE_FILE | |
while IFS= read -r file; do | |
if [ ! -f "$file" ]; then | |
1>&2 echo "File $file does not exist" | |
exit 1 | |
fi | |
SERVICES=$(yq -r '.services | keys | ... comments="" | .[]' $file) # list services | |
BASE_PATH=$( dirname $file) | |
cd "$BASE_PATH" | |
while IFS= read -r service; do | |
VOLUMES=$(yq -r '.services.'"$service"'.volumes[]' $file) | |
lastModificationSeconds=0 | |
while IFS= read -r volume; do | |
case $volume in ./*:ro) | |
volume=$(echo $volume | sed "s|:.*||") | |
volumeModificationSeconds=$(date -r $volume +%s) | |
lastModificationSeconds=$(( volumeModificationSeconds > lastModificationSeconds ? volumeModificationSeconds : lastModificationSeconds )) | |
esac | |
done <<< "$VOLUMES" | |
yq -i '.services.'"$service"'.labels."com.pasdam.volumes-last-modified-timestamp" |= '$lastModificationSeconds'' $OVERRIDE_COMPOSE_FILE | |
done <<< "$SERVICES" | |
done <<< "$FILES" | |
FILES_ARG="$FILES_ARG --file $OVERRIDE_COMPOSE_FILE" | |
cd "$INITIAL_DIR" | |
docker compose $FILES_ARG $OTHER_ARGS |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment