Mysql运行很长时间以后会导致二进制很大或者很多,需要定期备份清理。
二进制日志清理:
mysql提供expire-logs-days变量用以清理过期日志。
默认为0表示不清理,最大值为99天。
可以在my.cnf添加: 表示删除5天以前的二进制日志
expire-logs-days = 5
set global expire_logs_days=5; //全局会话设置日志过期时间
# 日志查看
show binary logs;
show master logs;
flush logs; //二进制日志滚动
reset master; //重置二进制日志,
二进制日志备份:
通过nfs自动备份至其他Server
安装NFS:客户端需要安装,否则客户端在mount时,指定nfs挂载失败。
Centos6服务端:
yum install -y nfs-utils rpcbind
vi /etc/exports
/data/binlog_backup 192.168.3.6(rw,sync,no_root_squash) *(ro)
客户端:
mount -t nfs 192.168.10.27:/data/binlog_backup /data/binlog_backup
# 将此挂载命令写入:/etc/rc.d/rc.local
备份脚本:参考博客http://blog.chinaunix.net/uid-20639775-id-3209044.html
#!/bin/bash
#Date:2017-05-09
USER=root
PASS=123456
HOST=localhost
MYSQL="/usr/local/mysql/bin/mysql"
# binlog
BINLOG=`grep "log-bin=" /etc/my.cnf | grep -v "^#" | awk -F"=" '{print $2}'`
BIN_LOG_DIR=`dirname $BINLOG`
BIN_LOG_FILE=`basename $BINLOG`
# binlog backup dir
BIN_LOG_BACKUP_DIR="/data/binlog_backup"
BACKUPFILE="$BIN_LOG_BACKUP_DIR/backup.file"
LOGFILE="$BIN_LOG_BACKUP_DIR/binlog_backup.log"
[ ! -d "$BIN_LOG_BACKUP_DIR" ] && mkdir -p $BIN_LOG_BACKUP_DIR
[ ! -f "$LOGFILE" ] && touch "$LOGFILE"
[ ! -f "$BACKUPFILE" ] && touch "$BACKUPFILE"
# flush logs
$MYSQL -u$USER -h$HOST -p$PASS -e "flush logs"
# backup file list
FILE_LIST=`comm -23 $BINLOG.index $BACKUPFILE` #没有备份的二进制文件列表
FILE_COUNT=`comm -23 $BINLOG.index $BACKUPFILE|wc -l` #执行此脚本时,FILE_COUNT一定是大于或者等于1
COUNT=0
# running binlog backup
for file in $FILE_LIST;do
BINLOG_FILE=`basename $file`
let COUNT=$COUNT+1
if [ $COUNT -eq $FILE_COUNT ];then #跳过mysql当前正在使用的二进制日志
echo "skip the lastest binlog file" >> $LOGFILE
else
cp $BIN_LOG_DIR/$BINLOG_FILE $BIN_LOG_BACKUP_DIR/
if [ $? -eq 0 ];then
echo "`date -d "today" +%Y-%m-%d-%H-%M-%S` $BINLOG_FILE backup success" >> $LOGFILE
else
echo "`date -d "today" +%Y-%m-%d-%H-%M-%S` $BINLOG_FILE backup faild,please check it out" >> $LOGFILE
exit 5
fi
# gzip
gzip $BIN_LOG_BACKUP_DIR/$BINLOG_FILE
if [ $? -eq 0 ];then
echo "`date -d "today" +%Y-%m-%d-%H-%M-%S` $BINLOG_FILE gzip success" >> $LOGFILE
else
echo "`date -d "today" +%Y-%m-%d-%H-%M-%S` $BINLOG_FILE gzip faild,please check it out" >> $LOGFILE
exit 6
fi
echo $file >> $BACKUPFILE
fi
done