One Option to Backup Docker Services


When hard drives fail, a working backup solution is a safetynet to reduce the risks of dataloss.

For my infrastructure, I wrote a script to make continues backups of my docker-compose services and copy them over to a network storage location.

It will backup the service and if available defined volumes.

The backups are stored per host and grouped by year and month (…/hostname/2024-11/servicename-service-00000000000.tar.gz).

#!/bin/bash

SERVICE_ROOT=${1:-/srv/docker}
BACKUP_ROOT=${2:-/mnt/network/backup/location/$(hostnamectl hostname)}

backup_project() {
    project_name=$1
    target_base_dir="$BACKUP_ROOT/$1/$(date +%Y-%m)"
    mkdir -p "$target_base_dir"
    timestamp=$(date +%s)
    echo "[+] Backing up service: $1"
    tar -cpzf "${target_base_dir}/$1-service-$timestamp.tar.gz" -C "$SERVICE_ROOT" "$1"

    volumes=($(docker volume ls -f name=$project_name | awk '{if (NR > 1) print $2}'))
    for v in "${volumes[@]}"
    do
        echo "[+] Backing up service $1 volume: $v"
        docker run --rm -v $v:/data -v $target_base_dir:/backup busybox \
            tar -cpzf "/backup/$1-volume-$v-$timestamp.tar.gz /data"
    done
}

for service in $SERVICE_ROOT/*/docker-compose.y*ml; do
    echo "[*] Stopping running containers"
    docker-compose -f $service stop

    service_dir=$(dirname $service)
    project=$(basename $service_dir)
    backup_project "$project"

    echo "[*] Restarting containers"
    docker-compose -f $service start
done