mysql備份mysql
一、添加mysql備份用戶sql
GRANT SELECT, RELOAD, SUPER, REPLICATION CLIENT ON *.* TO 'dump'@'localhost' IDENTIFIED BY PASSWORD '123456';
二、配置文件添加mysqldump字段數據庫
[mysqldump] socket=/data/mysql.sock host=localhost user=dump password=123456
三、備份策略bash
全備:天天凌晨4:00less
增備:天天中午12:00和晚上18:00socket
說明:全備週期要看本身業務的數據量ide
四、備份目錄spa
#mkdir -pv /backup/{data/{days,week},scritps}
五、增備腳本xml
#!/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
六、全備腳本crontab
#!/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
七、配置計劃任務
#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
八、建立數據庫信息文件,添加要備份的數據庫名到databases文件
#touch /backup/scripts/databases
腳本按行讀取,每行一個庫名