每天中午12点和晚上12点做一次全备,每隔一小时备份binlog,也就是增量备份,具体操作如下:
Linux下开启binlog
/etc/my.cnf中的mysqld部分加入:
[mysqld]
log-bin=../logs/mysql-bin
max-binlog-size=50M
windows下开启binlog
%mysql%/my.ini中的mysqld部分加入:
[mysqld]
log-bin =../logs/mysql-bin
max-binlog-size=50M
完整备份脚本 (网友提供)
如果数据库数据量比较大,可以一天全备一次, 再每隔一小时增量备份一次;
#!/bin/sh
# mysql data backup script #
# use mysqldump --help,get more detail.
BakDir=/backup/mysql
LogFile=/backup/mysql/mysqlbak.log
DATE=`date +%Y%m%d`
echo " " >> $LogFile
echo " " >> $LogFile
echo "-------------------------------------------" >> $LogFile
echo $(date +"%y-%m-%d %H:%M:%S") >> $LogFile
echo "--------------------------" >> $LogFile
cd $BakDir
DumpFile=$DATE.sql
GZDumpFile=$DATE.sql.tgz
mysqldump --quick --all-databases --flush-logs
--delete-master-logs --lock-all-tables
> $DumpFile
echo "Dump Done" >> $LogFile
tar czvf $GZDumpFile $DumpFile >> $LogFile 2>&1
echo "[$GZDumpFile]Backup Success!" >> $LogFile
rm -f $DumpFile
#delete previous daily backup files:采用增量备份的文件,如果完整备份后,则删除增量备份的文件.
cd $BakDir/daily
rm -f *
cd $BakDir
echo "Backup Done!"
echo "please Check $BakDir Directory!"
echo "copy it to your local disk or ftp to somewhere !!!"
ls -al $BakDir
上面的脚本把mysql备份到本地的/backup/mysql目录,增量备份的文件放在/backup/mysql/daily目录下.
增量备份
增量备份的数据量比较小,但是要在完整备份的基础上操作
增量备份使用bin log,脚本如下:
#!/bin/sh
# mysql binlog backup script
/usr/bin/mysqladmin flush-logs
DATADIR=/var/lib/mysql
BAKDIR=/backup/mysql/daily
###如果你做了特殊设置,请修改此处或者修改应用此变量的行:缺省取机器名,mysql缺省也是取机器名
HOSTNAME=`uname -n`
cd $DATADIR
FILELIST=`cat $HOSTNAME-bin.index`
##计算行数,也就是文件数
COUNTER=0
for file in $FILELIST
do
COUNTER=`expr $COUNTER + 1 `
done
NextNum=0
for file in $FILELIST
do
base=`basename $file`
NextNum=`expr $NextNum + 1`
if [ $NextNum -eq $COUNTER ]
then
echo "skip lastest"
else
dest=$BAKDIR/$base
if(test -e $dest)
then
echo "skip exist $base"
else
echo "copying $base"
cp $base $BAKDIR
fi
fi
done
echo "backup mysql binlog ok"
增量备份脚本是备份前flush-logs,mysql会自动把内存中的日志放到文件里,然后生成一个新的日志文件,所以我们只需要备份前面的几个即可,也就是不备份最后一个.
因为从上次备份到本次备份也可能会有多个日志文件生成,所以要检测文件,如果已经备份过,就不用备份了.
数据还原:
先还原最近的完全备份数据:
mysql -hhostname -uusername -ppassword databasename < backupfile.sql
再还原binlog :
./mysqlbinlog --start-date="2009-04-10 17:30:05" --stop-date="2009-04-10 17:41:28" /usr/local/mysql/data/mysql-bin.000002 |mysql -u root -p123456