Backup MySQL database with CRON

CentOS Dec 15, 2018

It is important to backup your database. I case of an error, you can easily restore all data. You do not have to do the backup process manually.

I wanted to automate my MySQL database backup workflow. To do this, I  created a shell script, which collects all database data and stores it  into a file. After creation, the script compresses the file and uploads  it to another server. I use another server to decrease the risk of data  loss. If my primary production server fails, I still have all backups on  another physical system.

Create a new database user

It is highly recommended creating a new database user with limited permissions.

You can restrict the new user to the following permissions:

  • SELECT
  • RELOAD
  • FILE
  • LOCK TABLES
  • TRIGGER
  • SHOW VIEW

You can set these permissions global or for every needed database/table.

To use this user during crontab backup, you have to create a file in your home directory called .my.cnf and insert the user credentials. The file should look like this:

[mysqldump]
user=
password=

What does the shell script look like?

Create a new file sqlbackup.sh and paste the following code:

#!/bin/bash

today=`date '+%Y_%m_%d'`;
mysqldump DATABASE_NAME > /PATH_TO_BACKUP_FOLDER/dump-$today.sql
tar -cPf /PATH_TO_BACKUP_FOLDER/dump-$today.tar /PATH_TO_BACKUP_FOLDER/dump-$today.sql
rm /PATH_TO_BACKUP_FOLDER/dump-$today.sql

backupdir='/PATH_TO_BACKUP_FOLDER'
DAYS_OLD=30

for d in $backupdir ; do
    if [ -d "$d" ] ; then
        FILE="$d/"$(ls "$d" -t1  | head -n 1)
        if test $(find "$FILE" -mtime +$DAYS_OLD) ; then
            rm $FILE
        fi
    fi
done

To get this code running, you need to replace 2 placeholders: DATABASE_NAME, PATH_TO_BACKUP_FOLDER!

The code will also delete local backup files older than 30 days. If you want to increase or decrease this value, change DAYS_OLD.

You can also add the server upload algorithm in this file.

How to configure the CRON?

On an Ubuntu system execute crontab -e. This will open an editor. At the end of the file insert:

0 1 * * * /PATH_TO_BACKUP_FOLDER/sqlbackup.sh

This command will then execute every day at 01:00 AM.


Please comment below, if you have any questions.

Credits:

Tags

Stefan

Howdy! I'm Stefan and I am the main author of this blog. If you want know more, you can check out the 'About me' page.

Impressum | Data Privacy Policy | Disclaimer
Copyright: The content is copyrighted and may not be reproduced on other websites without permission.