Home Database Mysql Tutorial How to backup script for binlog in MySQL

How to backup script for binlog in MySQL

Jun 03, 2023 pm 06:53 PM
mysql binlog

关于MySQL的二进制日志(binlog),我们都知道二进制日志(binlog)非常重要,尤其当你需要point to point灾难恢复的时侯,所以我们要对其进行备份。关于二进制日志(binlog)的备份,可以基于flush logs方式先切换binlog,然后拷贝&压缩到到远程服务器或本地服务器的其他存储上,例如挂载的NAS存储,也可以使用mysqlbinlog实现binlog的备份,可以实现MySQL二进制日志(binlog)的本地备份或远程备份。最终将MySQL二进制日志(binlog)备份文件存储到磁带上。各个公司的备份策略或备份工具有所不同,这里不做展开,我们主要考虑MySQL二进制日志(binlog)备份方案/策略尽可能尽善尽美,在一些极端情况下少丢失数据。例如,第一种方式,这种备份方式都是周期性的,如果在某个周期中,遇到一些极端情况,例如服务器宕机了,硬盘损坏了,就可能导致这段时间的binlog丢失了。而且这个周期时间太长,二进制日志(binlog)丢失的风险就越大,如果这个周期太短,频繁切换binlog也不好。所以还是使用mysqlbinlog来备份二进制日志(binlog),这里主要介绍一下我写的MySQL二进制日志的备份脚本,这个脚本参考了如何远程备份MySQL binlog[1]中的脚本,但是在其基础上做了很多改进和完善:

  • 参考资料中的脚本由于使用了循环操作,不适合在作业中调用。一般需要手工执行脚本,让其在后台运行。遇到服务器重启或其他异常情况,此脚本可能出现未能执行的情况。

  • 增加了mysql_binlog_backup_job.sh脚本,作业会定期调用此脚本,此脚本会判断mysqlbinlog是否还在执行二进制日志备份。即使遇到了数据库服务器重启等情况,备份MySQL的二进制日志(binlog)也不会成为问题。

  • 不用手工指定第一个binlog文件参数,采用从数据库读取binlog的值.如果是在本地服务器执行binlog的备份,还可以从二进制日志索引文件中获取(参考脚本注释部分)

  • 使用mysql_config_editor配置账号密码,避免在脚本中使用数据库用户的明文密码。

  • 邮件告警处理。

在使用脚本前,必须配置mailx,创建数据库连接账号

create user bkuser@'xxx.xxx.xxx.xxx' identified by "******";
grant  replication client on *.* to bkuser@'%';
grant  replication slave on *.* to bkuser@'%';
Copy after login

这个根据实际情况调整,例如我就是使用Xtrabackup的账号来备份MySQL的binlog。 另外,如果在MySQL数据库服务器本机备份binlog,那么就在本机安全加密登录,如果是在远程服务器备份binlog的话,就在远程服务器配置

$ mysql_config_editor set  --login-path=server1_dbbackup -h xxx.xxx.xxx.xxx -ubkuser -p -P 3306
Enter password:
Copy after login

mysql_binlog_backup_job.sh脚本

#!/bin/sh

#########################################################################################
#                                                                                       #
# This script is used for mysql binlog backup.                                          #
#                                                                                       #
# #######################################################################################
#                                                                                       #
# ScriptName            :    mysql_binlog_backup_job.sh                                 #
# Author                :    潇湘隐者                                                     #
# CerateDate            :    2017-04-14                                                 #
# Description           :                                                               #
#---------------------------------------------------------------------------------------#
#                         作业中调用此脚本,然后此脚本去调用mysql_binlog_backup.sh执行      #
#                         MySQL的二进制日志备份(将MySQL的二进制日志备份到NAS存储或备份存#
#                         储上),此脚本还会判断mysqlbinlog是否在一直在备份二进制日志,  #
#                         如果是的话,则退出当前脚本。如果mysqlbinlog已经由于服务器重   #
#                         启等原因退出了,则会重新调用mysql_binlog_backup.sh            #
#***************************************************************************************#
# Version        Modified Date            Description                                   #
#***************************************************************************************#
# V.1.0          2016-06-20     create the script for mysql binlog backp                #
# V.1.1          2016-07-26     fix some bug                                            #
# V.1.2          2023-04-14     $FIRST_BINLOG从MySQL中获取,即使远程备份也不用手工      #
#                               设定,本地备份也可以这种方式,本地备份默认从             #
#                                mysql binlog index file读取                            #
#########################################################################################

#mysql binlog备份文件的保留天数
KEEPY_DAYS=7
FIRST_BINLOG=''
LOG_DATE=$(date +%Y_%m_%d_%H_%M_%S)
BACKUP_DATE=$(date +%Y_%m_%d_%H_%M_%S)
LOCAL_BACKUP_DIR=/dbbackup/mysql_backup/db_backup/binlog_backup
#MYSQL_BINLOG_INDEX=/data/bin_logs/mysql_binlog.index
MYSQL_CMD=/opt/mysql/mysql8.0/bin/mysql
BACKUP_LOG_PATH=/dbbackup/mysql_backup/logs
ERROR_LOG=${BACKUP_LOG_PATH}/binlog_backup_error_${BACKUP_DATE}.log
FILE_TYPE="mysql_binlog.*"
SQL_TEXT='show binary logs'
MAIL_TO="xxxx@xxx.com.cn"
MAIL_FROM="xxxx@xxx.com.cn"
MYSQL_LOGIN_PATH=server1_dbbackup
error()
{
 echo "$1" 1>&2
 echo "$1" >> ${ERROR_LOG}
 echo "$1" | mailx -s "The binlog backup on the server `hostname` failed ,please check the log!" -r ${MAIL_FROM} ${MAIL_TO}
 exit 1
}

##目录不存在则创建目录
if [ ! -d $BACKUP_LOG_PATH ];then
       mkdir -p $BACKUP_LOG_PATH
fi

if [ ! -x /bin/mailx ];then
    error "{LOG_DATE}:mailx did not exists!" 
fi

if [ ! -x $MYSQL_CMD ];then
   error "{LOG_DATE}: mysql client did not exists!" 
fi
#SQL_RESULT=`mysql -h${REMOTE_HOST} -P${PORT} -u${USER_NAME} -p${PASSWORD} ${DATABASE_NAME} -Bse "${SQL_TEXT}"`
SQL_RESULT=`$MYSQL_CMD --login-path=${MYSQL_LOGIN_PATH} -Bse "${SQL_TEXT}"`
FIRST_BINLOG=`echo ${SQL_RESULT} | awk '{print $1}'`
echo $FIRST_BINLOG

if [ ! $FIRST_BINLOG ];then
   error "${LOG_DATE}: please check the mysql binlog"  
fi

##create local_backup_dir if this folder is not exists
if [ ! -d ${LOCAL_BACKUP_DIR} ];then
  mkdir -p ${LOCAL_BACKUP_DIR}
fi
if [ ! -e ${MYSQL_BINLOG_INDEX} ];then
  error "${LOG_DATE}:mysql binlog index file did not exists, please check it!" 
fi

#删除KEEPY_DAYS天之前的binlog备份文件
find ${LOCAL_BACKUP_DIR} -name "${FILE_TYPE}" -type f -mtime +$KEEPY_DAYS -delete
#删除30天前的错误日志
find ${BACKUP_LOG_PATH} -name "binlog_backup_error*.log"   -mtime 30 -delete
process_num=$(ps -ef | grep -w mysqlbinlog | grep -v grep |wc -l)

if [ ${process_num} -ge 1 ];then
       exit 1 
else
  #如果是在本机备份binlog到NAS存储或备份存储上,从二进制文件的索引获取当前MySQL数据库最小的binlog文件
  #如果是远程备份二进制日志(binlog)的话,则使用下面注释的脚本获取
  #FIRST_BINLOG=$(head -1 ${MYSQL_BINLOG_INDEX})
  #FIRST_BINLOG=$(find ${LOCAL_BACKUP_DIR} -name "mysql_binlog.*"  -printf "%p\t%C@\n" | sort -k2 -g |head -1 | awk '{print $1}' | awk -F "/" '{print $NF}') 
  echo ${FIRST_BINLOG}
  nohup sh /dbbackup/mysql_backup/scripts/mysql_binlog_backup.sh ${FIRST_BINLOG} ${LOCAL_BACKUP_DIR} ${FILE_TYPE} &
fi
Copy after login

mysql_binlog_backup.sh脚本

#!/bin/sh

#########################################################################################
#                                                                                       #
# This script is used for mysql binlog local or remote backup.                          #
#                                                                                       #
# #######################################################################################
#                                                                                       #
# ScriptName            :    mysql_binlog_backup.sh                                     #
# Author                :    Kerry                                                      #
# CerateDate            :    2017-04-14                                                 #
# Description           :                                                               #
#---------------------------------------------------------------------------------------#
#                         此脚本参考了https://www.cnblogs.com/ivictor/p/5502240.html    #
#                         的脚本,在它的基础上做了一些改进,例如,ivitcor中脚本备份binlog#
#                         如果服务器重启了,则必须手动执行脚本.......                   #
#***************************************************************************************#
# Version        Modified Date            Description                                   #
#***************************************************************************************#
# V.1.0          2016-06-20     create the script for mysql binlog backp                #
# V.1.1          2016-07-26     fix some bug                                            #
#########################################################################################

BACKUP_BIN=/opt/mysql/mysql8.0/bin/mysqlbinlog
BACKUP_LOG_PATH=/dbbackup/mysql_backup/logs
LOG_DATE=$(date +%Y_%m_%d_%H_%M_%S)
BACKUP_LOG=${BACKUP_LOG_PATH}/binlog_backup.log
ERROR_LOG=${BACKUP_LOG_PATH}/binlog_backup_error_${LOG_DATE}.log
#复制二进制日志的主机,可以远程MySQL数据库也可以是本机
MYSQL_LOGIN_PATH=server1_dbbackup
#time to wait before reconnecting after failure
SLEEP_SECONDS=10
MAIL_TO="xxx@xxx.com.cn"
MAIL_FROM="xxx@xxx.com.cn"

error()
{
 echo "$1" 1>&2
 echo "$1" >> ${ERROR_LOG}
 echo "$1" | mailx -s "The binlog backup on the server `hostname` failed ,please check the log!" -r ${MAIL_FROM} ${MAIL_TO}
 exit 1
}
##目录不存在则创建目录
if [ ! -d $BACKUP_LOG_PATH ];then
       mkdir -p $BACKUP_LOG_PATH
fi


if [ "$#" -ne 3];then   
    error "${LOG_DATE}:you must input 3 arguments" 
fi

if [ ! $1 ];then
    error "${LOG_DATE}:first_binlog arguments is null" 
else
    FIRST_BINLOG=$1
fi

if [ ! $2 ];then
    error "${LOG_DATE}:local_backup_dir arguments is null" 
else
    LOCAL_BACKUP_DIR=$2
fi

if [ ! $3 ];then
    error "${LOG_DATE}:file_type arguments is null" 
else
    FILE_TYPE=$3
fi
##检查mysqlbinlog二进制文件是否存在
if [ ! -x ${BACKUP_BIN} ];then
       error "${LOG_DATE}:mysqlbinlog did not exists, please check it!" 
fi
cd ${LOCAL_BACKUP_DIR}

## 运行while循环,连接断开后等待指定时间,重新连接
while :
do
  #如果当前备份二进制日志目录为空,则使用MySQL实例最小的二进制日志文件名
  if [ `ls -A "${LOCAL_BACKUP_DIR}" |wc -l` -eq 0 ];then
     LAST_BINLOG_FILE=${FIRST_BINLOG}
  else
     #LAST_FILE=`ls -l ${LOCAL_BACKUP_DIR} | grep -v backuplog |tail -n 1 |awk '{print $9}'`
     #echo ${LOCAL_BACKUP_DIR}
     #echo ${FILE_TYPE}
     #取mysqlbinlog备份的最后一个binlog文件名
     LAST_BINLOG_FILE=`find ${LOCAL_BACKUP_DIR} -name "${FILE_TYPE}"  -printf "%p\t%C@\n" | sort -k2 -g |tail -1 | awk '{print $1}' | awk -F "/" '{print $NF}'`
  fi
  #${BACKUP_BIN} --login-path=${MYSQL_LOGIN_PATH} --read-from-remote-server --raw --stop-never --host=${REMOTE_HOST} --port=${REMOTE_PORT}  ${LAST_BINLOG_FILE}
  ${BACKUP_BIN} --login-path=${MYSQL_LOGIN_PATH} --read-from-remote-server --raw --stop-never   ${LAST_BINLOG_FILE}
  echo "`date +"%Y/%m/%d %H:%M:%S"` mysqlbinlog停止,返回代码:$?" | tee -a ${BACKUP_LOG}
  echo "${SLEEP_SECONDS}秒后再次连接并继续备份" | tee -a ${BACKUP_LOG}  
  sleep ${SLEEP_SECONDS}
done
Copy after login

配置作业

*/10 * * * * /dbbackup/mysql_backup/scripts/mysql_binlog_backup_job.sh >> /dbbackup/mysql_backup/logs/mysql_binlog_back.log 2>&1
Copy after login

The above is the detailed content of How to backup script for binlog in MySQL. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

MySQL's Role: Databases in Web Applications MySQL's Role: Databases in Web Applications Apr 17, 2025 am 12:23 AM

The main role of MySQL in web applications is to store and manage data. 1.MySQL efficiently processes user information, product catalogs, transaction records and other data. 2. Through SQL query, developers can extract information from the database to generate dynamic content. 3.MySQL works based on the client-server model to ensure acceptable query speed.

How to start mysql by docker How to start mysql by docker Apr 15, 2025 pm 12:09 PM

The process of starting MySQL in Docker consists of the following steps: Pull the MySQL image to create and start the container, set the root user password, and map the port verification connection Create the database and the user grants all permissions to the database

Laravel Introduction Example Laravel Introduction Example Apr 18, 2025 pm 12:45 PM

Laravel is a PHP framework for easy building of web applications. It provides a range of powerful features including: Installation: Install the Laravel CLI globally with Composer and create applications in the project directory. Routing: Define the relationship between the URL and the handler in routes/web.php. View: Create a view in resources/views to render the application's interface. Database Integration: Provides out-of-the-box integration with databases such as MySQL and uses migration to create and modify tables. Model and Controller: The model represents the database entity and the controller processes HTTP requests.

Solve database connection problem: a practical case of using minii/db library Solve database connection problem: a practical case of using minii/db library Apr 18, 2025 am 07:09 AM

I encountered a tricky problem when developing a small application: the need to quickly integrate a lightweight database operation library. After trying multiple libraries, I found that they either have too much functionality or are not very compatible. Eventually, I found minii/db, a simplified version based on Yii2 that solved my problem perfectly.

How to install mysql in centos7 How to install mysql in centos7 Apr 14, 2025 pm 08:30 PM

The key to installing MySQL elegantly is to add the official MySQL repository. The specific steps are as follows: Download the MySQL official GPG key to prevent phishing attacks. Add MySQL repository file: rpm -Uvh https://dev.mysql.com/get/mysql80-community-release-el7-3.noarch.rpm Update yum repository cache: yum update installation MySQL: yum install mysql-server startup MySQL service: systemctl start mysqld set up booting

Laravel framework installation method Laravel framework installation method Apr 18, 2025 pm 12:54 PM

Article summary: This article provides detailed step-by-step instructions to guide readers on how to easily install the Laravel framework. Laravel is a powerful PHP framework that speeds up the development process of web applications. This tutorial covers the installation process from system requirements to configuring databases and setting up routing. By following these steps, readers can quickly and efficiently lay a solid foundation for their Laravel project.

MySQL and phpMyAdmin: Core Features and Functions MySQL and phpMyAdmin: Core Features and Functions Apr 22, 2025 am 12:12 AM

MySQL and phpMyAdmin are powerful database management tools. 1) MySQL is used to create databases and tables, and to execute DML and SQL queries. 2) phpMyAdmin provides an intuitive interface for database management, table structure management, data operations and user permission management.

Centos install mysql Centos install mysql Apr 14, 2025 pm 08:09 PM

Installing MySQL on CentOS involves the following steps: Adding the appropriate MySQL yum source. Execute the yum install mysql-server command to install the MySQL server. Use the mysql_secure_installation command to make security settings, such as setting the root user password. Customize the MySQL configuration file as needed. Tune MySQL parameters and optimize databases for performance.

See all articles