大家都知道服务器的稳定至关重要的,一旦我们的云服务器服务器硬盘坏了,客户的信息全部丢失,这样损失就无比巨大,特别是涉及到客户的充值资产的时候,不仅仅是信誉丢失的问题,还可能涉及法律诉讼。 所以我们需要定期做服务器的数据库备份。 保证服务器的100% 可靠性。 本文介绍了一个比较简单的返回定期自动备份数据库.
前提条件: 有两台服务器,一台是主服务器提供对外服务,另外一台是备份服务器,纯粹是当作sftp服务器用作存储备份数据库。
1:主服务器配置
我的例子,主服务器工作在centos + nodejs + mongoDB 环境下。
第一步配置服务器定期备份
// 定时任务,每隔1小时备份一次数据库,一天有24个备份
function server_regular_task() {
const rule = new schedule.RecurrenceRule();
rule.minute = 50;
schedule.scheduleJob(rule, async () => {
if (process.env.NODE_APP_INSTANCE === '0') {
createBackup()
}
});
}
// 数据库备份------------------------------------------------------------------------------------------------------------
const execSync = require('child_process').execSync;
const fse = require('fs-extra');
// MongoDB连接配置
const dbHost = '127.0.0.1'; // MongoDB主机地址
const dbPort = 27017; // MongoDB端口号
const dbName = 'xxxx'; // 要备份的数据库名称
const backupDir = '/data/release/xxxxx'; // 备份文件存放路径
function createBackup() {
const dateTime = (new Date()).getHours();
const fileName = `${dateTime}`;
try {
// 创建备份命令
const command = `mongodump --host ${dbHost} --port ${dbPort} -d ${dbName} -o ${backupDir} --gzip`;
// 执行备份命令并将结果输出到控制台
console.log(`Executing backup command: ${command}`);
execSync(command);
const sourceFolderPath = '/data/release/xxxx'; // 原始文件夹路径
const newFolderName = fileName; // 新文件夹名称
const destinationFolderPath = `/data/release/xxxx/${newFolderName}`; // 新文件夹路径
fse.copy(sourceFolderPath, destinationFolderPath, { overwrite: true })
.then(() =>
console.log(`成功拷贝并重命名文件夹 ${sourceFolderPath} 为 ${destinationFolderPath}`)
)
.catch((err) => console.error(`拷贝并重命名文件夹时发生错误:`, err));
} catch (error) {
console.error(`Failed to create backup: ${error}`);
}
}
这个是本地备份的效果
第二步,每个小时通过sftp 上传文件夹到远程服务器
const schedule = require('node-schedule');
// 定时任务,每隔1小时 上传一下数据给远程
function server_update_sftp() {
const rule = new schedule.RecurrenceRule();
rule.minute = 54;
schedule.scheduleJob(rule, async () => {
if (process.env.NODE_APP_INSTANCE === '0') {
sftpuploadFile()
.then(msg => {
console.log(msg);
})
.catch(err => {
console.log(`sftpuploadFile error: ${err.message}`);
});
}
});
}
const sftpClient = require('ssh2-sftp-client');
const sftp_config = {
host: 'xxxx', // 远程主机地址
port: 22, // 远程主机端口号
username: 'root', // 登录用户名
password: 'xxxx' // 密码或者SSH密钥(如果有)
};
async function sftpuploadFile() {
const xclient = new sftpClient();
const src = '/data/release/xxxx';
const dst = 'xxxx';
try {
await xclient.connect(sftp_config);
xclient.on('upload', info => {
console.log(`Listener: Uploaded ${info.source}`);
});
let rslt = await xclient.uploadDir(src, dst);
return rslt;
} catch (err) {
console.error(err);
} finally {
xclient.end();
}
}
2:备份服务器配置:
备份服务器不需要任何配置, 默认安装好centos系统后,就会支持sftp的, 你只要有这个服务器的ip,root密码就可以了。下面是完成上传后的效果。
有问题可以咨询我