GitLab在Ubuntu上的常见备份策略
GitLab提供了内置的gitlab-backup命令,可快速备份关键数据(包括Git仓库、数据库、上传文件、CI/CD配置等)。
sudo gitlab-backup create命令创建备份,默认生成格式为时间戳_版本_gitlab_backup.tar的文件(如1717017600_16.9.0_gitlab_backup.tar),存储在/var/opt/gitlab/backups目录(可通过/etc/gitlab/gitlab.rb中的gitlab_rails['backup_path']修改)。crontab设置自动备份,例如每天凌晨2点执行:0 2 * * * /opt/gitlab/bin/gitlab-backup create CRON=1(CRON=1表示以cron模式运行,避免输出干扰)。gitlab_rails['backup_keep_time']设置保留时间,如7天)。若需更灵活的备份(如包含自定义脚本或未纳入自带工具的文件),可手动备份GitLab数据目录和配置文件。
/var/opt/gitlab,使用tar命令压缩备份:sudo tar -czvf /var/backups/gitlab-data-$(date +%Y%m%d).tar.gz /var/opt/gitlab。/etc/gitlab,备份命令:sudo tar -czvf /var/backups/gitlab-config-$(date +%Y%m%d).tar.gz /etc/gitlab。/etc/gitlab/ssl目录:sudo tar -czvf /var/backups/gitlab-ssl-$(date +%Y%m%d).tar.gz /etc/gitlab/ssl。通过rsync工具实现增量备份,仅同步自上次备份以来修改的文件,减少备份时间和存储占用。
sudo rsync -avz --exclude={"/dev/*","/proc/*","/sys/*","/tmp/*","/run/*","/mnt/*","/media/*","/lost+found"} /var/opt/gitlab/ /path/to/incremental/backup/(排除系统临时目录,避免无效数据同步)。若使用Ansible管理GitLab服务器,可通过编写Playbook自动化备份流程,减少人工操作。
---
- name: Backup GitLab on Ubuntu
hosts: gitlab_servers
become: yes
tasks:
- name: Stop GitLab services (unicorn/sidekiq)
ansible.builtin.service:
name: "{{ item }}"
state: stopped
loop:
- gitlab-unicorn
- gitlab-sidekiq
- name: Backup GitLab data directory
ansible.builtin.archive:
path: /var/opt/gitlab
dest: "/var/backups/gitlab-backup-{{ lookup('pipe', 'date +%Y%m%d%H%M%S') }}.tar.gz"
format: gz
- name: Backup GitLab configurations
ansible.builtin.archive:
path: /etc/gitlab
dest: "/var/backups/gitlab-configs-{{ lookup('pipe', 'date +%Y%m%d%H%M%S') }}.tar.gz"
format: gz
- name: Start GitLab services
ansible.builtin.service:
name: "{{ item }}"
state: started
loop:
- gitlab-unicorn
- gitlab-sidekiq
backup_gitlab.yml,通过ansible-playbook -i inventory_file backup_gitlab.yml运行。