Introduction
Regular data backups are vital. We all know this. So in that spirit, I've made a simple bash script that does the following:
- Stops all running Docker containers on the server.
- Creates an archieve file of all the bind mount data.
- Creates archieves of all the Docker volumes in use.
- Copies all archieves created from the server to my desktop.
- Removes all archieves created by the script from the server.
- Restarts all the Docker containers on the server.
Prerequisites
In order for the SCP command to function you need to have SSH password-less connection setup between the two devices.
The Script
#!/bin/bash
# a back up script for docker container data
echo stopping services...
docker stop $(docker ps -a -q) > /dev/null
echo -en '\n'
sleep 10
echo creating archives...
tar -cPvf "server_backup_$(date +"%Y-%m-%d").tar.gz" --exclude=/opt/containerd -C /opt . > /dev/null
tar -cPvf "ghost-data_volume_backup_$(date +"%Y-%m-%d").tar.gz" -C /var/lib/docker/volumes ghost-data > /dev/null
tar -cPvf "grafana-data_volume_backup_$(date +"%Y-%m-%d").tar.gz" -C /var/lib/docker/volumes grafana-data > /dev/null
tar -cPvf "influxdb-data_volume_backup_$(date +"%Y-%m-%d").tar.gz" -C /var/lib/docker/volumes influxdb-data > /dev/null
tar -cPvf "mariadb-data_volume_backup_$(date +"%Y-%m-%d").tar.gz" -C /var/lib/docker/volumes mariadb-data > /dev/null
tar -cPvf "prometheus_volume_backup_$(date +"%Y-%m-%d").tar.gz" -C /var/lib/docker/volumes prometheus-data > /dev/null
echo -en '\n'
sleep 10
echo copying archive to remote location...
scp -i /home/user/.ssh/id_rsa *.tar.gz [email protected]:~/Downloads/ > /dev/null
echo -en '\n'
sleep 10
echo removing archive from server...
rm *.tar.gz
echo -en '\n'
sleep 10
echo starting services...
docker start $(docker ps -a -q) > /dev/null
echo -en '\n'
sleep 10
echo back up completed and services resumed.
The script file is stored in the user home folder. It needs to have execute permissions to run.
chmod +x docker_script.sh
The script needs to run as root in order to work (archiving folders that are owned by root).
sudo ./docker_script.sh
I run mine with a crontab job on the 1st day of the month as my data doesn't change very much (now that my homelab is setup correctly).