HostOnNet Blog

MySQL Data Directory Backup with Rsync

Lets create 2 folders.

mkdir /usr/hostonnet/
mkdir /home/hon_mysql_backup

Create following file

vi /usr/hostonnet/

With following content.

#title           :
#description     : Make daily backup of MySQL data directory.
#web             :

#/usr/bin/mysql -e "FLUSH TABLES WITH READ LOCK;"
rsync -vrplogDtH --delete /var/lib/mysql/ /home/hon_mysql_backup/daily/   2>&1 > /var/log/mysql_backup_daily.log
#/usr/bin/mysql -e "UNLOCK TABLES;"

Lets generate shell scripts for weekly and monthly mysql backup from daily backup file we created above.

sed -e "s/daily/weekly/g" /usr/hostonnet/ > /usr/hostonnet/
sed -e "s/daily/monthly/g" /usr/hostonnet/ > /usr/hostonnet/

Make them executable

chmod 755 /usr/hostonnet/
chmod 755 /usr/hostonnet/
chmod 755 /usr/hostonnet/

Set cronjob, so backup commands run daily, weekly and monthly.

@daily /usr/hostonnet/
@weekly /usr/hostonnet/
@monthly /usr/hostonnet/

Make sure crond is running on your server, if not refer

On Ubuntu, verify cronjob running with

root@cloud1:~# service cron status
cron start/running, process 907

On CentOS/RHEL, it is

[root@server12 ~]# service crond status
crond (pid  15121) is running...
[root@server12 ~]#

Locking Tables

If you are copying MySQL data folder, there is a chance the backup can be corrupt (repair possible in most cases) as data is written to the data directory while you copying, so on large database, you may not able to copy before data file changes. One solution is to lock tables before you backup

mysql -u root -p"password" -e "FLUSH TABLES WITH READ LOCK;"

Unlock database after backup finished.

mysql -u root -p"password" -e "UNLOCK TABLES;"

Posted in MySQL