A Simple Backup Script

I recently installed a new server. It doesn’t do much but I want to make sure it backed up anyway. While I explore better options for backups I decided to write a little script to grab the data from the machine and bundle it all up in some sort of compressed archive. I’ll then download that archive to my home lab for safe keeping (probably using scp or something like that).

The script I’m using is shown below. It needs to be run with sudo as the backup location includes files that are readable only by root.

#!/bin/bash

# This script will create a dated backup of the Docker files and a dump of all the databases
# It will only store the most recent backup.

# Where backups will be stored
backup_root="/home/username/backups"
# The start of the name of the file that will hold the backup
backup_filename="servername-"
# Where to place the database backups - should be within the Docker path
db_backup_dest="/home/username/docker/mariadb/backups"
# Parent directory of the Docker directory
docker_parent="/home/username"
# Name of the  Docker directory within docker_parent
backup_target="docker"

# Repeat this line for each database you want to backup
mariadb-dump --user username --password=secret --host 10.10.0.3 databasename > $db_backup_dest/databasename.sql

# Remove old backup files
rm $backup_root/$backup_filename*

# Create todays filename
day=$(date +%Y-%m-%d)
backup_file="$backup_root/$backup_filename$day.tgz"

# Perform the backup
echo "Backup File: $backup_file"
tar -czf $backup_file -C $docker_parent $backup_target

Once you’re happy the script is working as expected place it in the crontab of root and have it run everyday. Open roots crontab with this command

sudo crontab -e

Paste in the command to run the script and the time you want it to run:

0 3 * * * /home/username/backups/backup.sh >> /var/log/cron.log 2>&1

To bring the backup down from the server a simple scp command is probably the best option for now. Something like:

scp servername.example.com:~/backups/servername-* .

Run the above command on a cronjob as often as needed. The data on this server changes very slowly so for me there’s little point pulling the backup more than once a week.

References

  • Inspiration was taken from this article