1. Background
There is now a server in use, and it is necessary to back up the database data, laboratory files and procurement platform files on the server.
Store the backup files on another server and require the backup files for the last seven days to be retained.
2. Detailed steps
2.1 Backup environment
- Create a backup directory on the new server:
mkdir /opt/backup
- Directory permissions:
chmod 700 /opt/backup
2.2 SSH password-free
- The old server generates a key pair:
ssh-keygen -t rsa
- Configure password-free (requires input of the backup server password):
ssh-copy-id -i ~/.ssh/id_rsa.pub user@new_server_ip
- Verify that you can log in directly:
ssh user@new_server_ip
2.3 Backup script
vim /opt/
#!/bin/bash
# Backup date
BACKUP_DATE=$(date +%Y%m%d)
# Backup server information
NEW_SERVER="user@new_server_ip"
# Database User
MYSQL_USER="backup_user"
# Database Password
MYSQL_PASS="your_password"
# Existing server temporary backup directory
BACKUP_DIR="/tmp/backup/${BACKUP_DATE}"
# Existing server log file directory (storage logs during backup)
BACKUP_LOG_DIR="/var/log/backup/"
# Backup server backup directory
BACKUP_TAR_DIR="/opt/backup/"
# Create a temporary directory
mkdir -p ${BACKUP_DIR}
# Create a backup log directory
mkdir -p ${BACKUP_LOG_DIR}
{
# Backup MySQL database and compress (no spaces after -u and -p)
mysqldump --single-transaction -u${MYSQL_USER} -p${MYSQL_PASS} --databases "db1" "db2" | gzip > ${BACKUP_DIR}/db_${BACKUP_DATE}.
# Backup purchase files
rsync -avz --delete /var/www/uploads/purchase/ ${BACKUP_DIR}/files-purchase/
# Backup lab files
rsync -avz --delete /var/www/uploads/lab/ ${BACKUP_DIR}/files-lab/
# Package the file and back up and compress it (there is now one file and two folders in the ${BACKUP_DIR} directory)
tar czf ${BACKUP_DIR}/${BACKUP_DATE}. -C ${BACKUP_DIR} .
# Transfer packaged files to the BACKUP_TAR_DIR directory of the backup server
scp -r ${BACKUP_DIR}/${BACKUP_DATE}. ${NEW_SERVER}:${BACKUP_TAR_DIR}
# Clean up the old backup server (retained for 7 days)
# -mindepth is the protection that will not delete ${BACKUP_TAR_DIR}. If the scp fails, the directory date will not be modified.
ssh ${NEW_SERVER} "find ${BACKUP_TAR_DIR} -mindepth 1 -type d -mtime +7 -exec rm -rf {} \;"
# Clean up temporary files
rm -rf ${BACKUP_DIR}
# The output is completed, add time record
echo "backup done. timedatectl:";
timedatectl;
} >> "${BACKUP_LOG_DIR}/${BACKUP_DATE}.log" 2>&1
2.4 Script execution permissions
chmod +x /opt/
2.5 Timing tasks
echo "0 2 * * * root /opt/" > /etc//backup_job
2.6 Recovery Process
According to the actual situation, you can decompress and then cover it. Make a backup before covering it.
- database:
zcat /backup/db_20250408. | mysql -u root -p
- document:
tar xzf /opt/backup/ -C /var/www/uploads/