1、添加mysql备份用户
GRANT SELECT, RELOAD, SUPER, REPLICATION CLIENT ON *.* TO 'dump'@'localhost' IDENTIFIED BY PASSWORD '123456';
2、配置文件添加mysqldump字段
[mysqldump] socket=/data/mysql.sock host=localhost user=dump password=123456
3、备份策略
全备:每天凌晨4:00
增备:每天中午12:00和晚上18:00
说明:全备周期要看自己业务的数据量
4、备份目录
#mkdir -pv /backup/{data/{days,week},scritps}
5、增备脚本
#!/bin/bash #incremental backup every day. # binlog_dir='/data/binlog' binlog_file=`cat $binlog_dir/bin-index.index` start_time=$(date "-d 1 day ago" +"%Y-%m-%d %H:%M:%S") back_dir=/backup/data/days log_file=/var/log/back_daily.log line=`cat /backup/scripts/databases|wc -l` for i in `seq $line` do database=`sed -n "$i p" /backup/scripts/databases` DIR=$back_dir/$database if [ -d $DIR ] then echo "$DIR is exist." >>$log_file else mkdir $DIR fi for j in $binlog_file do mysqlbinlog --no-defaults -d $database --start-datetime="$start_time" $j >> $DIR/"$database"_`date +%F`.sql done #Keep 2 files, remove outdated files # file_nu=`ls $DIR/*.sql |wc -l` if [ $file_nu -gt 2 ];then rm_file="$database"_`date "-d 1 day ago" +%F`.sql if [ -f $DIR/$rm_file ];then rm -f $DIR/$rm_file; echo `date "+%F %H:%M:%S"` "====>" 'rm outdated file:' $rm_file >> $log_file else echo `date "+%F %H:%M:%S"` "====>" 'rm outdated file failed.' fi else echo `date "+%F %H:%M:%S"` "====>" 'file number less than 2.' >> $log_file fi done
6、全备脚本
#!/bin/bash # #mysqldump databases without create database # back_dir=/backup/data/week log_file=/var/log/back_weekly.log line=`cat /backup/scripts/databases|wc -l` for i in `seq $line` do database=`sed -n "$i p" /backup/scripts/databases` DIR=$back_dir/$database if [ -d $DIR ] then echo `date "+%F %H-%M-%S"` "====>$DIR is exist." >>$log_file else mkdir $DIR fi mysqldump --single-transaction --master-data=2 --no-create-db --databases $database > $DIR/"$database"_`date +%F`.sql #Keep 5 files,remove outdated files. # file_nu=`ls $DIR/*.sql |wc -l` if [ $file_nu -gt 5 ];then rm_file="$database"_`date "-d 35 day ago" +%F`.sql if [ -f $DIR/$rm_file ];then rm -f $DIR/$rm_file; echo `date "+%F %H-%M-%S"` "====>" 'remove outdated file:'$rm_file; >>$log_file fi else echo `date "+%F %H-%M-%S"` "====>" 'file number less than 5.' >>$log_file fi done
7、配置计划任务
#crontab -e 0 12,18 * * * source /etc/profile;/bin/bash /backup/scripts/daily.sh >/dev/null 2>&1 0 4 * * * source /etc/profile;/bin/bash /backup/scripts/weekly.sh >/dev/null 2>&1
8、创建数据库信息文件,添加要备份的数据库名到databases文件
#touch /backup/scripts/databases
脚本按行读取,每行一个库名
原文地址:http://blog.51cto.com/4708705/2050372