背景说明
网上有很多教程,写的都是从零搭建一个什么什么,基本上都是从无到有的教程,但是,很少有文章提及搭建好之后如何备份,这次通过请教GitHub Copilot Chat,生成几个备份脚本,以备后用。
注:本文涉及的所有脚本默认仅针对Linux环境。
备份MySQL
#!/bin/bash
# Set the database name, backup directory, host, username, and password
database="<database>"
backup_directory="<backup_directory>"
host="<host>"
username="<username>"
password="<password>"
# Create the backup directory if it doesn't exist
mkdir -p $backup_directory
# Create a timestamped backup file name
backup_file="$backup_directory/$database-$(date +%Y-%m-%d-%H-%M-%S).sql"
# Backup the database to the backup file
mysqldump -h $host -u $username -p$password $database > $backup_file
# Delete backups older than 7 days
find $backup_directory -type f -name "$database-*.sql" -mtime +7 -delete
echo $backup_file
备份SQLite
#!/bin/bash
# Set the database file path and backup directory
database="<database>"
backup_directory="<backup_directory>"
# Create the backup directory if it doesn't exist
mkdir -p $backup_directory
# Create a timestamped backup file name
backup_file="$backup_directory/$(basename $database)-$(date +%Y-%m-%d-%H-%M-%S).db"
# Backup the database to the backup file using SQLite's .backup command
sqlite3 $database ".backup $backup_file"
# Delete backups older than 7 days
find $backup_directory -type f -name "*.db" -mtime +7 -delete
echo $backup_file
备份目录
#!/bin/bash
# Set the directory to backup and backup directory
directory="<directory>"
backup_directory="<backup_directory>"
# Create the backup directory if it doesn't exist
mkdir -p $backup_directory
# Create a timestamped backup file name
backup_file="$backup_directory/$(basename $directory)-$(date +%Y-%m-%d-%H-%M-%S).tar.gz"
# Backup the directory to the backup file
tar -czf $backup_file $directory
# Delete backups older than 7 days
find $backup_directory -type f -name "*.tar.gz" -mtime +7 -delete
echo $backup_file
上传至对象存储
因为平时腾讯云用的比较多,对腾讯云的产品比较熟悉,所以这里就以腾讯云的对象存储为例。
#!/bin/bash
read file
prefix=$1
bucket=$2
coscli cp $file "cos://$bucket/$prefix/$(basename $file)"
COSCLI 是腾讯云对象存储(Cloud Object Storage,COS)提供的客户端命令行工具。具体安装、配置参考官方文档。当然也可以选择s5cmd这种兼容s3协议的客户端,支持各家对象存储。
划重点
上面的内容看起来平平无奇,我主要想说的是最后这一段。
上文中的备份脚本有个细节,最后会输出备份文件的路径,目的是为了结合最后一个脚本上传至对象存储。
整体使用逻辑是:备份脚本分别写,上传脚本共用同一个。
这里以备份 /data/test/
目录至对象存储的/test/
路径下为示例说明具体使用:
backup.sh
#!/bin/bash
directory="/data/test"
backup_directory="/data/backup/test"
mkdir -p $backup_directory
backup_file="$backup_directory/$(basename $directory)-$(date +%Y-%m-%d-%H-%M-%S).tar.gz"
cd $directory
tar -czf $backup_file .
find $backup_directory -type f -name "*.tar.gz" -mtime +7 -delete
echo $backup_file
upload.sh
#!/bin/bash
read file
prefix=$1
bucket=$2
coscli cp $file "cos://$bucket/$prefix/$(basename $file)"
备份命令如下:
./backup.sh | ./upload.sh test temp
结合crontab
就可以实现定时备份了。
另外,对于对象存储上的内容,可以设置生命周期,自动删除旧的备份。如下图(腾讯的对象存储为例),设置了备份保留30天。