Compare commits

..

65 Commits

Author SHA1 Message Date
cdd3d88202 Update README.md 2023-11-16 17:32:30 +01:00
7488262c4c Update README.md 2023-11-16 17:31:44 +01:00
3a8f002f85 Updated README.md 2023-09-02 16:56:34 +02:00
978a8f93e3 Updated recovery script 2023-07-09 19:42:11 +02:00
5786e21c11 Optimized exits 2023-06-28 21:32:09 +02:00
7832c85de7 Optimized version by chat gpt 2023-06-28 21:25:15 +02:00
9fa37046ab Optimized mysql recovery 2023-06-28 21:22:02 +02:00
eddccb1936 Changed mysql to mariadb 2023-06-25 22:15:00 +02:00
02449cb501 removed versions folder from recovery script 2023-04-19 13:21:09 +02:00
4290464986 removed version dir and latest link from backup script 2023-04-19 13:20:07 +02:00
d8471e5b4b solved typos 2023-03-27 02:10:49 +02:00
18fcd3b06d Solved bug in recovery logic 2023-03-27 01:49:58 +02:00
0f2ef55f1e Optimized recover instructions 2023-01-09 13:03:23 +01:00
367d16496a Removed typo 2022-12-23 15:48:10 +01:00
f86727365d Added version 2022-09-01 07:43:08 +02:00
16e1a76eef implemented file backup of databases 2022-08-31 20:48:40 +02:00
ff4e192a7b removed user parameter 2022-08-31 20:21:52 +02:00
6d6d7103d0 added database recovery 2022-08-31 19:04:42 +02:00
87a189efce added akaunting exception 2022-04-04 11:51:22 +02:00
caf78a82be Changed regex condition 2022-04-04 11:34:42 +02:00
cc0496ffa8 Solved naming bug 2022-04-04 11:22:26 +02:00
b907b8246a Removed unnecessary slash 2022-03-29 21:30:39 +02:00
bf817d8829 Added routine to delete symlink if exists 2022-03-29 21:29:25 +02:00
03a8b56093 Refactored and added latest symlink 2022-03-29 19:20:35 +02:00
7927192073 Solved reference bug 2022-03-29 08:45:00 +02:00
fe0ed83dd4 solved version bug 2022-03-28 18:14:59 +02:00
7f0c85eb4a Solved missing whitespace bug 2022-03-28 18:03:07 +02:00
152f11267c Optimized code for use of link_dest 2022-03-28 17:46:32 +02:00
163ee6c7ab Implemented logic for link dest 2022-03-28 17:08:54 +02:00
f0a1b3e742 changed whitespaces and typos 2022-03-28 16:39:37 +02:00
8b903d6723 Draft before implementing link-dest 2022-03-28 16:37:59 +02:00
d9f5e26abe Changed diff to versions 2022-03-17 22:13:08 +01:00
d6b2b3c985 Reduced container down time 2022-03-17 21:10:43 +01:00
5bb95d61f4 Removed backup over kevinveenbirkenbach/alpine-rsync 2022-03-17 20:29:27 +01:00
2776c35da6 Updated readme 2022-02-12 13:05:54 +00:00
97aa13a07d Updated recovery 2022-02-12 12:20:46 +00:00
7cee6cbdcf Added hints how to optimize backups 2022-02-12 09:17:48 +00:00
c5d66c4ff3 Changed path 2022-01-23 22:07:29 +01:00
7f5cc5be72 Added template file 2022-01-23 21:37:59 +01:00
16de548051 Removed deprecated script 2022-01-23 20:56:53 +01:00
72270f5cb8 Removed unused libraries 2022-01-23 20:56:24 +01:00
1ff8fd4a0a Refactored 2022-01-23 20:55:09 +01:00
75c171ce09 Implemented database backup with mysqldump 2022-01-23 17:20:42 +01:00
8ac9512163 Added gitignore file 2022-01-23 16:06:11 +01:00
7206be8294 Renamed variables 2022-01-23 16:03:27 +01:00
454826b7e9 Finished python version 2022-01-23 15:52:31 +01:00
7bf07d7fb5 Draft translating to python 2022-01-23 14:04:38 +01:00
2eeb4961d0 In between commit rewriting in python 2022-01-23 13:01:49 +01:00
d5d3a4d575 Merged 2022-01-21 19:05:00 +01:00
d0bcb04022 Added Description how to backup mariadb container 2022-01-21 19:01:11 +01:00
cb5e5fc6ed Added further information concerning backups 2021-11-12 12:46:21 +01:00
403108ee34 Solved path bug and optimized readme.md 2021-11-11 13:47:17 +01:00
ebab64549d Added hint for backup practices 2021-11-11 13:33:14 +01:00
d49b212290 Solved bugs 2021-11-11 13:17:02 +01:00
568888952f Optimized performance of backup script 2021-11-11 13:03:19 +01:00
f23ea7e6d3 Added 'systemctl restart docker' 2021-10-18 13:25:18 +02:00
febaa5ac3b Made more restrictiv 2021-08-24 19:58:28 +02:00
2d53923538 removed reverse_container due to root cause in docker-compose file 2021-08-22 20:26:47 +02:00
08c961f6e3 Solved bug concerning non running containers 2021-08-20 09:58:10 +02:00
468f5c60d4 Added reverse startup of container to solve dependency bug 2021-08-20 09:27:14 +02:00
f3979ce611 Merge branch 'main' of github.com:kevinveenbirkenbach/docker-volume-backup 2021-08-20 09:16:05 +02:00
6a5093b122 Updated badge link 2021-08-20 09:15:22 +02:00
aaa86b78d1 solved containers bug 2021-08-19 22:32:23 +02:00
99f7b387c2 Highered performance by removing container loop 2021-08-19 22:00:17 +02:00
76d32a2e5c just backup running containers 2021-08-19 21:18:14 +02:00
6 changed files with 201 additions and 73 deletions

1
.gitignore vendored Normal file
View File

@@ -0,0 +1 @@
databases.csv

View File

@@ -1,5 +1,5 @@
# docker-volume-backup
[![License: GPL v3](https://img.shields.io/badge/License-GPL%20v3-blue.svg)](./LICENSE.txt) [![Travis CI](https://travis-ci.org/kevinveenbirkenbach/docker-volume-backup.svg?branch=master)](https://travis-ci.org/kevinveenbirkenbach/docker-volume-backup)
# Backup Docker Volumes to Local
[![License: GPL v3](https://img.shields.io/badge/License-GPL%20v3-blue.svg)](./LICENSE.txt)
## goal
This script backups all docker-volumes with the help of rsync.
@@ -9,7 +9,7 @@ It is part of the following scheme:
![backup scheme](https://www.veen.world/wp-content/uploads/2020/12/server-backup-768x567.jpg)
Further information you will find [in this blog post](https://www.veen.world/2020/12/26/how-i-backup-dedicated-root-servers/).
## Backup
## Backup all volumes
Execute:
```bash
@@ -17,42 +17,50 @@ Execute:
```
## Recover
### database
```bash
docker exec -i mysql_container mysql -uroot -psecret database < db.sql
```
### volume
Execute:
```bash
./docker-volume-recover.sh {{volume_name}} {{backup_path}}
bash ./docker-volume-recover.sh "{{volume_name}}" "$(sha256sum /etc/machine-id | head -c 64)" "{{version_to_recover}}"
```
### Database
## Debug
To checkout what's going on in the mount container type in the following command:
```bash
docker run -it --entrypoint /bin/sh --rm --volumes-from {{container_name}} -v /Backups/:/Backups/ kevinveenbirkenbach/alpine-rsync
```
## Manual Backup
rsync -aPvv '***{{source_path}}***/' ***{{destination_path}}***";
## Test
Delete the volume.
## Setup
Install pandas
```bash
docker rm -f container-name
docker volume rm volume-name
```
## Author
Recover the volume:
Kevin Veen-Birkenbach
- 📧 Email: [kevin@veen.world](mailto:kevin@veen.world)
- 🌍 Website: [https://www.veen.world/](https://www.veen.world/)
```bash
docker volume create volume-name
docker run --rm -v volume-name:/recover/ -v ~/backup/:/backup/ "kevinveenbirkenbach/alpine-rsync" sh -c "rsync -avv /backup/ /recover/"
```
## License
Restart the container.
## Optimation
This setup script is not optimized yet for performance. Please optimized this script for performance if you want to use it in a professional environment.
This project is licensed under the GNU Affero General Public License v3.0. The full license text is available in the `LICENSE` file of this repository.
## More information
- https://docs.docker.com/storage/volumes/
- https://blog.ssdnodes.com/blog/docker-backup-volumes/
- https://www.baculasystems.com/blog/docker-backup-containers/
- https://hub.docker.com/_/mariadb
- https://gist.github.com/spalladino/6d981f7b33f6e0afe6bb
- https://stackoverflow.com/questions/26331651/how-can-i-backup-a-docker-container-with-its-data-volumes
- https://netfuture.ch/2013/08/simple-versioned-timemachine-like-backup-using-rsync/
- https://zwischenzugs.com/2016/08/29/bash-to-python-converter/
- https://en.wikipedia.org/wiki/Incremental_backup#Incremental
- https://unix.stackexchange.com/questions/567837/linux-backup-utility-for-incremental-backups

1
databases.csv.tpl Normal file
View File

@@ -0,0 +1 @@
database;username;password;container

109
docker-volume-backup.py Normal file
View File

@@ -0,0 +1,109 @@
#!/bin/python
# Backups volumes of running containers
#
import subprocess
import os
import re
import pathlib
import pandas
from datetime import datetime
def bash(command):
print(command)
process = subprocess.Popen([command], stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
out, err = process.communicate()
stdout = out.splitlines()
output = []
for line in stdout:
output.append(line.decode("utf-8"))
if process.wait() > bool(0):
print(command, out, err)
raise Exception("Exitcode is greater then 0")
return output
def print_bash(command):
output = bash(command)
print(list_to_string(output))
return output
def list_to_string(list):
return str(' '.join(list))
print('start backup routine...')
dirname = os.path.dirname(__file__)
repository_name = os.path.basename(dirname)
# identifier of this backups
machine_id = bash("sha256sum /etc/machine-id")[0][0:64]
# Folder in which all Backups are stored
backups_dir = '/Backups/'
# Folder in which the versions off docker volume backups are stored
versions_dir = backups_dir + machine_id + "/" + repository_name + "/"
# Time when the backup started
backup_time = datetime.now().strftime("%Y%m%d%H%M%S")
# Folder containing the current version
version_dir = versions_dir + backup_time + "/"
# Create folder to store version in
pathlib.Path(version_dir).mkdir(parents=True, exist_ok=True)
print('start volume backups...')
print('load connection data...')
databases = pandas.read_csv(dirname + "/databases.csv", sep=";")
volume_names = bash("docker volume ls --format '{{.Name}}'")
for volume_name in volume_names:
print('start backup routine for volume: ' + volume_name)
containers = bash("docker ps --filter volume=\"" + volume_name + "\" --format '{{.Names}}'")
if len(containers) == 0:
print('skipped due to no running containers using this volume.')
else:
container = containers[0]
# Folder to which the volumes are copied
volume_destination_dir = version_dir + volume_name
# Database name
database_name = re.split("(_|-)(database|db)", container)[0]
# Entries with database login data concerning this container
databases_entries = databases.loc[databases['database'] == database_name]
# Exception for akaunting due to fast implementation
if len(databases_entries) == 1 and container != 'akaunting':
print("Backup database...")
mysqldump_destination_dir = volume_destination_dir + "/sql"
mysqldump_destination_file = mysqldump_destination_dir + "/backup.sql"
pathlib.Path(mysqldump_destination_dir).mkdir(parents=True, exist_ok=True)
database_entry = databases_entries.iloc[0]
database_backup_command = "docker exec " + container + " /usr/bin/mariadb-dump -u " + database_entry["username"] + " -p" + database_entry["password"] + " " + database_entry["database"] + " > " + mysqldump_destination_file
print_bash(database_backup_command)
print("Backup files...")
files_rsync_destination_path = volume_destination_dir + "/files"
pathlib.Path(files_rsync_destination_path).mkdir(parents=True, exist_ok=True)
versions = os.listdir(versions_dir)
versions.sort(reverse=True)
if len(versions) > 1:
last_version = versions[1]
last_version_files_dir = versions_dir + last_version + "/" + volume_name + "/files"
if os.path.isdir(last_version_files_dir):
link_dest_parameter="--link-dest='" + last_version_files_dir + "' "
else:
print("No previous version exists in path "+ last_version_files_dir + ".")
link_dest_parameter=""
else:
print("No previous version exists in path "+ last_version_files_dir + ".")
link_dest_parameter=""
source_dir = "/var/lib/docker/volumes/" + volume_name + "/_data/"
rsync_command = "rsync -abP --delete --delete-excluded " + link_dest_parameter + source_dir + " " + files_rsync_destination_path
print_bash(rsync_command)
print("stop containers...")
print("Backup data after container is stopped...")
print_bash("docker stop " + list_to_string(containers))
print_bash(rsync_command)
print("start containers...")
print_bash("docker start " + list_to_string(containers))
print("end backup routine for volume:" + volume_name)
print('finished volume backups.')
print('restart docker service...')
print_bash("systemctl restart docker")
print('finished backup routine.')

View File

@@ -1,46 +0,0 @@
#!/bin/bash
# Just backups volumes of running containers
# If rsync stucks consider:
# @see https://stackoverflow.com/questions/20773118/rsync-suddenly-hanging-indefinitely-during-transfers
#
backup_time="$(date '+%Y%m%d%H%M%S')";
backups_folder="/Backups/";
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}}');
do
echo "start backup routine: $volume_name";
for container_name in $(docker ps -a --filter volume="$volume_name" --format '{{.Names}}');
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
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";
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
echo "backup volume: $volume_name";
else
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";
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
done
echo "end backup routine: $volume_name";
done

View File

@@ -1,6 +1,61 @@
#!/bin/bash
# @param $1 Volume-Name
volume_name="$1"
backup_path="$2"
docker volume create "$volume_name"
docker run --rm -v "$volume_name:/recover/" -v "$backup_path:/backup/" "kevinveenbirkenbach/alpine-rsync" sh -c "rsync -avv /backup/ /recover/"
# Check minimum number of arguments
if [ $# -lt 3 ]; then
echo "ERROR: Not enough arguments. Please provide at least a volume name, backup hash, and version."
exit 1
fi
volume_name="$1" # Volume-Name
backup_hash="$2" # Hashed Machine ID
version="$3" # version to backup
container="${4:-}" # optional
mysql_root_password="${5:-}" # optional
database="${6:-}" # optional
backup_folder="Backups/$backup_hash/docker-volume-backup/$version/$volume_name"
backup_files="/$backup_folder/files"
backup_sql="/$backup_folder/sql/backup.sql"
echo "Inspect volume $volume_name"
docker volume inspect "$volume_name"
exit_status_volume_inspect=$?
if [ $exit_status_volume_inspect -eq 0 ]; then
echo "Volume $volume_name already exists"
else
echo "Create volume $volume_name"
docker volume create "$volume_name"
if [ $? -ne 0 ]; then
echo "ERROR: Failed to create volume $volume_name"
exit 1
fi
fi
if [ -f "$backup_sql" ]; then
if [ -n "$container" ] && [ -n "$mysql_root_password" ] && [ -n "$database" ]; then
echo "recover mysql dump"
cat "$backup_sql" | docker exec -i "$container" mariadb -u root --password="$mysql_root_password" "$database"
if [ $? -ne 0 ]; then
echo "ERROR: Failed to recover mysql dump"
exit 1
fi
exit 0
fi
echo "A database backup exists, but a parameter is missing. Files will be recovered instead."
fi
if [ -d "$backup_files" ]; then
echo "recover files"
docker run --rm -v "$volume_name:/recover/" -v "$backup_files:/backup/" "kevinveenbirkenbach/alpine-rsync" sh -c "rsync -avv --delete /backup/ /recover/"
if [ $? -ne 0 ]; then
echo "ERROR: Failed to recover files"
exit 1
fi
exit 0
else
echo "ERROR: $backup_files doesn't exist"
exit 1
fi
echo "ERROR: Unhandled case"
exit 1