Skip to content

Instantly share code, notes, and snippets.

@reddec
Created July 29, 2017 07:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save reddec/b677329f1431abaf3440de48e98bc6b0 to your computer and use it in GitHub Desktop.
Save reddec/b677329f1431abaf3440de48e98bc6b0 to your computer and use it in GitHub Desktop.
Simple backup of docker-compose with images and data-volumes
#!/bin/sh
if [ "1$1" != "1" ]; then
cd "$1"
fi
BACKUP_IMAGES="backup/images"
BACKUP_VOLUMES="backup/volumes"
rm -rf "$BACKUP_IMAGES"
rm -rf "$BACKUP_VOLUMES"
mkdir -p "$BACKUP_IMAGES"
mkdir -p "$BACKUP_VOLUMES"
prefix=$(basename "`pwd`" | sed -e 's/_//' -e 's/-//')
echo "Backuping $prefix"
docker-compose stop
for volume in $(docker volume ls | grep "$prefix"_ | awk '{print $2}'); do
echo "Backuping volume $volume"
name=$(echo "$volume" | sed -e "s/^$prefix"_"//")
docker run --rm -v `pwd`/"$BACKUP_VOLUMES":/media -v $volume:/mnt:ro busybox tar -czf /media/"$name".tar.gz mnt
done
echo "Backuping images"
for image in $(docker-compose images -q); do
echo "Backuping image $image"
docker save -o "$BACKUP_IMAGES"/"$image".tar.gz "$image"
done
echo '#!/bin/sh' > "$BACKUP_IMAGES"/tag.sh
docker-compose images | tail -n+3 | awk '{print "docker tag "$4" "$2":"$3}' >> "$BACKUP_IMAGES"/tag.sh
chmod +x "$BACKUP_IMAGES"/tag.sh
echo "Creating restore script"
cat - > restore.sh <<EOF
#!/bin/sh
echo "Importing images"
for image in "$BACKUP_IMAGES"/*.tar.gz; do
echo "Importing \$image"
docker load -i "\$image"
done
echo "Tagging"
"$BACKUP_IMAGES"/tag.sh
echo "Restoring"
docker-compose create
echo "Importing data volumes"
prefix=\$(basename "\`pwd\`" | sed -e 's/_//' -e 's/-//')
for file in "$BACKUP_VOLUMES"/*.tar.gz; do
basefile=\$(basename "\$file")
name="\$(echo \$basefile | sed -e 's/.tar.gz\$//')"
volume="\$prefix"_"\$name"
echo "volume: \$name -> \$volume"
docker run --rm -v \`pwd\`/"$BACKUP_VOLUMES":/media:ro -v \$volume:/mnt busybox tar -xzf /media/"\$basefile"
done
EOF
chmod +x restore.sh
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment