Skip to content
Jabran Rafique

Automatic database backup using Git (Bitbucket/GitLab/Github)

4 minutes read

This walk-through backs up MySQL databases on Ubuntu 12 LTS or later. Other databases may work with few or no changes. Treat it as a guide, try it on a dummy database before a production one, and use it at your own risk.

If you work with databases, you need regular backups so you don't lose data. Automating them is the easiest way to make sure they happen, and a cron job that runs at set times is one way to do that.

You also need somewhere to keep the backups that makes them easy to restore. A private Git repository on Bitbucket, GitLab or GitHub is cheap, secure and works well.

Set up a cron user

First create a MySQL user for the job. I've called it cron_user, but any name works. Log in to MySQL, replacing USER with your username:

$ mysql -u USER -p

Create the user with a password. Use a strong one and save it somewhere safe before you carry on:

$ CREATE USER 'cron_user'@'localhost' IDENTIFIED BY 'someStrongPassword';

Grant it only the privileges it needs, then flush privileges so the changes take effect:

$ GRANT SELECT,LOCK TABLES, EVENT, TRIGGER, SHOW VIEW PRIVILEGES ON *.* TO 'cron_user'@'localhost';
$ FLUSH PRIVILEGES;

cron_user is ready.

Set up the local and remote repositories

Create a new empty repository called database-backups on whichever service you use. Then ssh into your server, make a backup directory under /home/backup and cd into it.

$ mkdir -p /home/backup/database-backups && cd /home/backup/database-backups

Create a shell script and make it executable.

$ touch cron_backup.sh
$ chmod +x cron_backup.sh

Initialise Git and add the remote.

$ git init
$ git remote add origin {path/to/remote/database-backups.git}
$ git add -A
$ git commit -am 'Add files'
$ git push -u origin HEAD

Write the cron script

Open the file in your editor of choice. I'm using nano.

$ nano cron_backup.sh

Add this script, then save and exit (CTRL x).

#!/bin/sh
# Set variables
DB_NAME="foo"
CRON_USER="bar"

FULLDATE=$(date +"%Y-%d-%m %H:%M")
NOW=$(date +"%Y-%m-%d-%H-%M")
MYSQL_DUMP=`which mysqldump`
GIT=`which git`
TEMP_BACKUP="latest_backup.sql"
BACKUP_DIR=$(date +"%Y/%m")

# Check current Git status and update
${GIT} status
${GIT} pull origin HEAD

# Dump database
${MYSQL_DUMP} -u "$CRON_USER" $DB_NAME > $TEMP_BACKUP &
wait

# Make backup directory if not exists (format: {year}/{month}/)
if [ ! -d "$BACKUP_DIR" ]; then
  mkdir -p $BACKUP_DIR
fi

# Compress SQL dump
tar -cvzf $BACKUP_DIR/$DB_NAME-$NOW-sql.tar.gz $TEMP_BACKUP

# Remove original SQL dump
rm -f $TEMP_BACKUP

# Add to Git and commit
${GIT} add -A
${GIT} commit -m "Automatic backup - $FULLDATE"
${GIT} push origin HEAD

What it does, line by line:

  • #!/bin/sh runs the script with the shell at that path.
  • The next block sets variables used later in the script. You only need to change DB_NAME to your database name and CRON_USER to the cron user you created.
  • ${GIT} status checks the state of the repository.
  • ${GIT} pull fetches and merges the latest from the remote.
  • ${MYSQL_DUMP} -u "$CRON_USER" $DB_NAME > $TEMP_BACKUP & wait dumps the database to a temporary file.
  • The next block creates a {year}/{month}/ directory if it doesn't exist, to keep the backups organised.
  • tar -cvzf $BACKUP_DIR/$DB_NAME-$NOW-sql.tar.gz $TEMP_BACKUP compresses the dump and saves it with a dated name. That saves a lot of space as the repository grows with each backup.
  • rm -f $TEMP_BACKUP deletes the uncompressed dump so you don't keep two copies.
  • The last block adds the new backup to Git, commits it with a dated message and pushes it to the remote.

So the script dumps the database, compresses it with tar, commits it and pushes it. It needs a couple more things set up before it works.

Set up mysqldump credentials

You may have noticed the script never gives a password for CRON_USER. Run it now and it fails with an authentication error. You could create the user without a password, but you shouldn't let any MySQL user touch the database without one. It's a serious security risk even with limited permissions. Instead, create a .my.cnf file in your home directory so mysqldump can authenticate.

$ cd
$ nano ~/.my.cnf

Add the credentials:

[mysqldump]
user=CRON_USER_NAME
password=CRON_USER_PASSWORD

Replace CRON_USER_NAME and CRON_USER_PASSWORD with the real credentials, then save and exit (CTRL x). That fixes the authentication error. Run the script now and a fresh backup appears in the remote repository.

$ ./cron_backup.sh

Reference: Stackoverflow

Set up the cron job

Last, schedule the script with cron. Open the crontab:

$ crontab -u USER -e

Replace USER with the user that has access to the repository and the backup directory. In the editor that opens, add this line at the end:

@daily cd /home/backup/database-backups; /home/backup/database-backups/cron_backup.sh > /dev/null 2>&1

That runs every day at midnight. It changes into /home/backup/database-backups and runs cron_backup.sh.

The script is also on a Gist.