improved docker backup and restore

This commit is contained in:
tabledevil
2023-06-07 14:17:05 +02:00
parent 32ca98f99e
commit a6ed73fcfb
2 changed files with 79 additions and 2 deletions

View File

@@ -19,12 +19,32 @@ mkdir -p $BACKUP_DIR
docker-compose -f $COMPOSE_FILE down
# Tarball the Docker Compose directory
tar -czvf $BACKUP_DIR/"files_${DIR##*/}"_$TIMESTAMP.tar.gz -C / $DIR
CONFIG_BACKUP_FILE="files_${DIR##*/}"_$TIMESTAMP.tar.gz
tar -czvf $BACKUP_DIR/$CONFIG_BACKUP_FILE -C / $DIR
# Identify and save each Docker image used by the stack
IMAGES=$(docker-compose -f $COMPOSE_FILE config | awk '{if ($1 == "image:") print $2;}')
BACKUP_FILE=$BACKUP_DIR/"backup_${BASE_DIR_NAME}_${TIMESTAMP}.txt"
# Clear the backup list file
echo "${COMPOSE_FILE}" > $BACKUP_FILE
# Write config backup file name to the backup list file
echo $CONFIG_BACKUP_FILE >> $BACKUP_FILE
for IMAGE in $IMAGES; do
docker save $IMAGE | gzip > $BACKUP_DIR/"image_${IMAGE//[:\/]/_}"_$TIMESTAMP.tar.gz
# Get image id (strip off "sha256:" prefix)
IMAGE_ID=$(docker inspect --format="{{.Id}}" $IMAGE | sed 's/sha256://')
# Check if the image backup file already exists
IMAGE_BACKUP_FILE="image_${IMAGE//[:\/]/_}_${IMAGE_ID}.tar.gz"
IMAGE_BACKUP=$BACKUP_DIR/$IMAGE_BACKUP_FILE
if [ ! -f $IMAGE_BACKUP ]; then
docker save $IMAGE | gzip > $IMAGE_BACKUP
fi
# Write image backup file name to the backup list file
echo $IMAGE_BACKUP_FILE >> $BACKUP_FILE
done
# Restart the Docker Compose stack

57
tools/restore_docker.sh Normal file
View File

@@ -0,0 +1,57 @@
#!/bin/bash
# Specify your backup directory
BACKUP_DIR=/mnt/backups
# List available stacks for backup
echo "Available stacks for recovery:"
STACKS=($(ls $BACKUP_DIR))
select STACK_NAME in "${STACKS[@]}"; do
# Verify stack backup directory exists
STACK_BACKUP_DIR=$BACKUP_DIR/$STACK_NAME
if [ -d $STACK_BACKUP_DIR ]; then
break
else
echo "Invalid selection"
fi
done
# List available backups for the stack
echo "Available backups for stack $STACK_NAME:"
BACKUPS=($(ls $STACK_BACKUP_DIR/backup_*.txt))
# Display only the timestamps
TIMESTAMPS=("${BACKUPS[@]##*_}")
select CHOICE in "${TIMESTAMPS[@]}"; do
# Get the full filename of the chosen backup
BACKUP_FILE=$(echo "${BACKUPS[@]}" | tr ' ' '\n' | grep $CHOICE)
if [ -f $BACKUP_FILE ]; then
break
else
echo "Invalid selection"
fi
done
# Extract original Docker Compose file path
COMPOSE_FILE=$(head -n 1 $BACKUP_FILE)
DIR=$(dirname "${COMPOSE_FILE}")
# Check if stack is running and stop it
docker-compose -f $COMPOSE_FILE down
# Rename existing Docker Compose directory
mv $DIR $DIR.recovery_$(date +"%Y%m%d%H%M%S")
# Restore files from backup
tar -xzvf $STACK_BACKUP_DIR/$(sed '2q;d' $BACKUP_FILE) -C /
# Load Docker images from backup
tail -n +3 $BACKUP_FILE | while read IMAGE_FILE; do
docker load < $STACK_BACKUP_DIR/$IMAGE_FILE
done
# Change to the Docker Compose directory and restart the Docker Compose stack
cd $DIR
docker-compose up -d