MariaDB在Linux环境下的备份工具可分为逻辑备份与物理备份两类,需根据数据量、恢复需求及性能要求选择:
mysqldump(单线程,通用性强,适合小数据量或需要跨版本恢复的场景)、mysqlpump(多线程并行,提升备份速度,适合中大型数据库)。mariabackup(官方推荐,支持全量/增量/压缩备份,恢复速度快,适合生产环境)、rsync(文件系统级备份,需停机,适合全量备份或归档)。mysqldump备份所有数据库,添加--single-transaction(InnoDB一致性)、--master-data=2(记录binlog位置,便于增量恢复)选项,压缩节省空间:mysqldump -u root -p --all-databases --single-transaction --master-data=2 | gzip > /backup/mariadb/full_backup_$(date +%F).sql.gz
使用mysqlpump并行备份(提升速度):mysqlpump -u root -p --all-databases --parallel-servers=4 | gzip > /backup/mariadb/full_backup_pump_$(date +%F).sql.gz
FLUSH LOGS),后续可通过mysqlbinlog提取增量语句:FLUSH LOGS; -- 滚动binlog,生成新的binlog文件
导出增量binlog到SQL文件:mysqlbinlog /var/lib/mysql/mysql-bin.00000X > /backup/mariadb/incremental_$(date +%F).sql
mariabackup创建物理备份,指定目标目录(需为空):mariabackup --backup --user=root --password=your_password --target-dir=/backup/mariadb/full_backup
--incremental-basedir选项:mariabackup --backup --user=root --password=your_password --target-dir=/backup/mariadb/incr_backup_$(date +%F) --incremental-basedir=/backup/mariadb/full_backup
停机后使用rsync同步数据目录(默认/var/lib/mysql),保留文件属性:
systemctl stop mariadb
rsync -a --delete /var/lib/mysql/ /backup/mariadb/fs_backup/
systemctl start mariadb
gunzip /backup/mariadb/full_backup_$(date +%F).sql.gz
mysql命令导入,恢复前建议停止写入(如停止应用服务):mysql -u root -p < /backup/mariadb/full_backup_$(date +%F).sql
DROP等危险语句):mysql -u root -p < /backup/mariadb/incremental_$(date +%F).sql
--prepare选项重组备份数据,使其可导入:mariabackup --prepare --target-dir=/backup/mariadb/full_backup
systemctl stop mariadb
rm -rf /var/lib/mysql/*
rsync -aP /backup/mariadb/full_backup/ /var/lib/mysql/
chown -R mysql:mysql /var/lib/mysql
systemctl start mariadb
mariabackup --prepare --target-dir=/backup/mariadb/full_backup --incremental-dir=/backup/mariadb/incr_backup_$(date +%F)
rsync -aP /backup/mariadb/incr_backup_$(date +%F)/ /var/lib/mysql/
systemctl stop mariadb
cp -R /var/lib/mysql /var/lib/mysql_backup
rsync -a --delete /backup/mariadb/fs_backup/ /var/lib/mysql/
chown -R mysql:mysql /var/lib/mysql
systemctl start mariadb
root或mysql用户可访问,防止未授权访问。cron日志或备份工具的输出,监控备份任务的执行状态,失败时及时告警。