Backing up ownCloud - the whole story
Everyone of us, well, ok, maybe not everyone, so most of us, tend to be too careless about backup. For most of my data I have already duply configured, BUT the backup of my ownCloud instance was still pending.
One could argue that you synchronise your data to the cloud and you therefore have a backup anyway. That’s only half of the story. Sometimes I upload some data to the cloud for sharing only. Yes, I still have the data somewhere, but the share link would be invalid and I have the effort to figure out what it all was…
For years I procastinated the task to create a small script to backup my ownCloud, since one of the disks of my RAID1 broke. OK, I took that as a sign to finally work on that task. It’s quite easy to write a small script that does the job and run it as cron job. The Backing up ownCloud manual gives a good starting point.
Basically you have to store the config
and data
directories and dump the database. But I wanted to do the full Monty. That’s not only putting the data somewhere else, but neatly pack it, hence I compress the data. Furhermore I didn’t mean to waste too much data and store only the last x backups.
I came up with a small script that looks like this:
#!/bin/bash
# Backup date
DATE=`date +"%Y%m%d"`
# Backup directory
BACKUP_DIR=/var/backups/ocloud
# How many backups to keep
KEEP=4
# dump owncloud database
# need to create a .my.cnf file in the users home directory
mysqldump --single-transaction owncloud | bzip2 > $BACKUP_DIR/owncloud-dbbackup_${DATE}.sql.bz2
tar cjf $BACKUP_DIR/owncloud-data_${DATE}.tar.bz -C /var/www/owncloud config data
# Only keep the number of backups defined by $KEEP
cd $BACKUP_DIR
ls -tp owncloud-dbbackup_* | grep -v '/$' | tail -n +${KEEP} | xargs -d '\n' -r rm --
ls -tp owncloud-data_* | grep -v '/$' | tail -n +${KEEP} | xargs -d '\n' -r rm --
The actual backup is quite straight forward. Since I’m not eager to store the backup user’s credentials in the script, I created a .my.cnf file. Found on stackoverflow
[mysqldump]
user=mysqluser
password=secret
This has to be in the user’s home that is running the script. Of course you have to create a backup user in your MySQL/MariaDB.
GRANT LOCK TABLES, SELECT ON DATABASE.* TO 'BACKUPUSER'@'%' IDENTIFIED BY 'PASSWORD';
The last piece was to only keep a defined number of backups. A good solution for this is in Delete all but the most recent x files at stackoverflow.
The script is far from perfect, but works for now. I feel a lot better having a backup (OK, never had any sleepless nights anyway…). I dislike having two different files for database and file backup. Having just one file would be even nicer. Additionally it’ll be nice to delete the file by age and encrypt the backup, but that’s a different story to be told someday…