docker-volume-backup/docker-volume-backup.sh

47 lines
2.4 KiB
Bash
Raw Normal View History

2020-10-11 18:39:06 +02:00
#!/bin/bash
# Just backups volumes of running containers
# If rsync stucks consider:
2020-12-29 11:11:08 +01:00
# @see https://stackoverflow.com/questions/20773118/rsync-suddenly-hanging-indefinitely-during-transfers
#
2020-12-26 16:31:47 +01:00
backup_time="$(date '+%Y%m%d%H%M%S')";
backups_folder="/Backups/";
2021-08-19 13:46:35 +02:00
repository_name="$(cd "$(dirname "$(readlink -f "${0}")")" && basename `git rev-parse --show-toplevel`)";
machine_id="$(sha256sum /etc/machine-id | head -c 64)";
backup_repository_folder="$backups_folder$machine_id/$repository_name/";
for volume_name in $(docker volume ls --format '{{.Name}}');
2020-10-11 18:39:06 +02:00
do
2021-08-19 19:47:45 +02:00
echo "start backup routine: $volume_name";
2021-08-19 20:01:19 +02:00
for container_name in $(docker ps -a --filter volume="$volume_name" --format '{{.Names}}');
2020-10-11 18:39:06 +02:00
do
echo "stop container: $container_name" && docker stop "$container_name"
for source_path in $(docker inspect --format "{{ range .Mounts }}{{ if eq .Type \"volume\"}}{{ if eq .Name \"$volume_name\"}}{{ println .Destination }}{{ end }}{{ end }}{{ end }}" "$container_name");
do
2021-08-19 14:09:34 +02:00
destination_path="$backup_repository_folder""latest/$volume_name";
raw_destination_path="$destination_path/raw"
prepared_destination_path="$destination_path/prepared"
log_path="$backup_repository_folder""log.txt";
2021-08-19 14:09:34 +02:00
backup_dir_path="$backup_repository_folder""diffs/$backup_time/$volume_name";
raw_backup_dir_path="$backup_dir_path/raw";
prepared_backup_dir_path="$backup_dir_path/prepared";
if [ -d "$destination_path" ]
then
2021-08-19 19:47:45 +02:00
echo "backup volume: $volume_name";
else
2021-08-19 19:47:45 +02:00
echo "first backup volume: $volume_name"
mkdir -vp "$raw_destination_path";
mkdir -vp "$raw_backup_dir_path";
mkdir -vp "$prepared_destination_path";
mkdir -vp "$prepared_backup_dir_path";
fi
docker run --rm --volumes-from "$container_name" -v "$backups_folder:$backups_folder" "kevinveenbirkenbach/alpine-rsync" sh -c "
rsync -abP --delete --delete-excluded --log-file=$log_path --backup-dir=$raw_backup_dir_path '$source_path/' $raw_destination_path";
done
echo "start container: $container_name" && docker start "$container_name";
2021-08-19 21:02:52 +02:00
if [ "mariadb" == "$(docker inspect --format='{{.Config.Image}}' $container_name)"]
then
docker exec some-mariadb sh -c 'exec mysqldump --all-databases -uroot -p"$MARIADB_ROOT_PASSWORD"' > /some/path/on/your/host/all-databases.sql
fi
2020-10-11 18:39:06 +02:00
done
2021-08-19 19:47:45 +02:00
echo "end backup routine: $volume_name";
2020-10-11 18:39:06 +02:00
done