gongdear

gongdear的技术博客

欢迎大家参观我的博客
  menu
115 文章
89355 浏览
5 当前访客
ღゝ◡╹)ノ❤️

基于 systemd 的 GitLab 备份与构建产物自动清理方案

使用systemd service建立定时任务实现对docker运行的gitlab自动备份和gitlab-runner构建产物自动清理

gitlab

docker容器名称为gitlab

直接使用容器内gitlab的备份命令就可以,保证备份目录挂载出来即可。

/etc/systemd/system/gitlab-backup.service

[Unit]
Description=GitLab Backup via Docker
Documentation=https://docs.gitlab.com/ee/raketasks/backup_restore.html
After=docker.service
Requires=docker.service
[Service]
Type=oneshot
ExecStart=/usr/bin/docker exec gitlab gitlab-backup create CRON=1
User=root
StandardOutput=journal
StandardError=journal
# 可选:设置工作目录或环境变量(如需要)
# Environment=PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
[Install]
WantedBy=multi-user.target

/etc/systemd/system/gitlab-backup.timer

[Unit]
Description=Run GitLab backup daily at 2:00 AM
Requires=gitlab-backup.service
[Timer]
OnCalendar=*-*-* 02:00:00
Persistent=true
[Install]
WantedBy=timers.target

生效规则

systemctl daemon-reload
systemctl enable --now gitlab-backup.timer

gitlab-runner

gitlab-runner主要是清理构建产物,需要编写清理脚本。

我的docker私服做了命名区分,registry.xxx.com/[dev|test|prod]/都是构建产物,registry.xxx.com/global/全部是基础镜像,所以按照命名来清理就可以。

/usr/local/bin/clean-ci-images.sh

#!/bin/bash
# /usr/local/bin/clean-ci-images.sh
set -euo pipefail
echo "[$(date --iso-8601=seconds)] Starting CI image cleanup..."
PREFIXES=(
  "registry.xxx.com/test/"
  "registry.xxx.com/dev/"
  "registry.xxx.com/prod/"
)
PATTERN=$(IFS=\|; echo "${PREFIXES[*]}")
MATCHED_IMAGES=$(
  docker images --format "{{.Repository}}:{{.Tag}}" \
    | grep -E "^($PATTERN)" 2>/dev/null || true
)
if [ -n "$MATCHED_IMAGES" ]; then
  echo "Removing images:"
  echo "$MATCHED_IMAGES"
  echo "$MATCHED_IMAGES" | xargs -r docker rmi
else
  echo "No matching images found."
fi
# 清理悬空镜像(安全)
docker image prune -f
echo "[$(date --iso-8601=seconds)] Cleanup finished."

给脚本执行权限

chmod +x /usr/local/bin/clean-ci-images.sh

/etc/systemd/system/clean-ci-images.service

[Unit]
Description=Clean up CI-built Docker images (test/dev/prod)
After=docker.service
Requires=docker.service

[Service]
Type=oneshot
ExecStart=/usr/local/bin/clean-ci-images.sh
User=root
Group=root
StandardOutput=journal
StandardError=journal/etc/systemd/system/clean-ci-images.service

/etc/systemd/system/clean-ci-images.timer

[Unit]
Description=Run clean-ci-images daily at 3 AM
Requires=clean-ci-images.service

[Timer]
OnCalendar=*-*-* 03:00:00
Persistent=true

[Install]
WantedBy=timers.target/etc/systemd/system/clean-ci-images.timer

生效

systemctl daemon-reload
systemctl enable --now clean-ci-images.timer

可以手动触发一次server执行查看效果

systemctl start clean-ci-images.service

可以使用journalctl -xeu clean-ci-images.service来查看日志

宝剑锋从磨砺出,梅花香自苦寒来.