CentOS GitLab备份与恢复技巧
使用gitlab-rake命令创建全量备份,包含Git仓库、数据库、用户/组、权限等所有关键数据,默认存储在/var/opt/gitlab/backups目录。命令:
sudo gitlab-rake gitlab:backup:create
备份文件命名格式为TIMESTAMP_gitlab_backup.tar(如1713350400_gitlab_backup.tar),便于按时间识别。
若需修改默认备份路径,编辑/etc/gitlab/gitlab.rb文件,添加:
gitlab_rails['backup_path'] = "/mnt/backups"(自定义路径需存在且有写入权限)
同时可设置备份文件权限(如gitlab_rails['backup_archive_permissions'] = 0644)和保留时间(如gitlab_rails['backup_keep_time'] = 604800,单位:秒,此处为7天)。修改后需执行sudo gitlab-ctl reconfigure使配置生效。
通过crontab设置定时任务,实现每日自动备份。例如,每天凌晨2点执行备份:
crontab -e → 添加行:0 2 * * * /opt/gitlab/bin/gitlab-rake gitlab:backup:create
建议将备份脚本(包含备份与压缩逻辑)加入定时任务,提升自动化程度。
将本地备份文件同步至远程服务器(如通过rsync),避免本地磁盘故障导致数据丢失。示例脚本(auto_backup_to_remote.sh):
#!/bin/bash
LocalBackDir=/var/opt/gitlab/backups
RemoteBackDir=root@192.168.1.100:/remote/gitlab_backups
find $LocalBackDir -type f -mmin -60 -name '*.tar*' | while read file; do
scp "$file" "$RemoteBackDir"
done
添加定时任务(每天凌晨0点执行):0 0 * * * /root/auto_backup_to_remote.sh
远程服务器需配置SSH免密登录(通过authorized_keys),确保同步无需手动输入密码。
定期清理过期备份,节省存储空间。例如,删除/var/opt/gitlab/backups目录下超过30天的备份文件:
find /var/opt/gitlab/backups -type f -mtime +30 -name '*.tar*' -exec rm -rf {} \;
可将此命令加入定时任务(如每天凌晨1点执行),实现自动清理。
unicorn(Web服务)和sidekiq(后台任务)进程,确保数据一致性:sudo gitlab-ctl stop unicorn && sudo gitlab-ctl stop sidekiqls -lh查看大小,或tar -tzf尝试解压),避免恢复失败。1713350400_gitlab_backup.tar)复制到备份目录(默认/var/opt/gitlab/backups):cp /remote/gitlab_backups/1713350400_gitlab_backup.tar /var/opt/gitlab/backups/gitlab-rake恢复指定备份(BACKUP参数为备份文件的时间戳部分):sudo gitlab-rake gitlab:backup:restore BACKUP=1713350400yes确认。sudo gitlab-ctl startsudo gitlab-ctl restart。备份文件不包含/etc/gitlab/gitlab.rb(配置文件)和/etc/gitlab/gitlab-secrets.json(密钥文件),需手动备份这些文件(恢复前复制至安全位置),并在恢复后将其放回原路径,然后执行sudo gitlab-ctl reconfigure重新加载配置。
gitlab-rake gitlab:env:info查看当前版本。