如何实现GCP自动清理旧GCR镜像?
GCP自动清理旧GCR镜像的实现方案
一、使用官方gcr-cleaner工具
这是Google官方维护的工具,适配大多数通用清理场景:
- 部署方式:可通过Cloud Run或Kubernetes快速部署,支持基于标签规则、镜像年龄、保留数量等维度设置清理条件
- 核心配置示例:
- 指定目标仓库:
--repo=us-docker.pkg.dev/my-project/my-repo - 保留符合语义化版本的标签:
--keep-tag-regex=^v\d+\.\d+\.\d+$ - 保留最新5个镜像:
--keep-n=5 - 清理超过30天的镜像:
--older-than=720h
- 指定目标仓库:
- 自动化触发:搭配Cloud Scheduler定时调用工具的HTTP接口,实现定期自动清理
二、Cloud Functions + GCR API 自定义清理方案
如果需要更个性化的过滤逻辑,可自行编写Cloud Functions实现:
- 调用GCR API列出目标仓库的所有镜像,获取镜像创建时间、标签等元数据
- 自定义过滤规则(比如排除特定业务标签、混合时间+数量维度筛选待删除镜像)
- 调用API执行删除操作
- Python示例代码片段:
import datetime import google.auth from google.cloud import containerregistry_v1 def clean_old_images(event, context): credentials, project_id = google.auth.default() client = containerregistry_v1.ImageClient(credentials=credentials) repo_name = f"projects/{project_id}/locations/us/repositories/my-repo" # 列出仓库内所有镜像 images = client.list_images(parent=repo_name) # 自定义规则:保留最新10个镜像+删除30天前的无标签镜像 keep_count = 10 cutoff_time = datetime.datetime.now(datetime.timezone.utc) - datetime.timedelta(days=30) sorted_images = sorted(images, key=lambda x: x.create_time.timestamp(), reverse=True) for image in sorted_images[keep_count:]: if image.create_time.timestamp() < cutoff_time.timestamp() and not image.tags: client.delete_image(name=image.name)
- 触发方式:通过Cloud Scheduler定时触发该Cloud Function,实现自动执行
三、Cloud Build 定时脚本方案
适合轻量、规则简单的场景,利用Cloud Build的定时构建能力:
- 创建
cloudbuild.yaml构建脚本:
steps: - name: 'gcr.io/google.com/cloudsdktool/cloud-sdk' entrypoint: 'bash' args: - '-c' - | # 按创建时间倒序列出镜像摘要,删除除最新5个外的所有旧镜像 gcloud container images list-tags us-docker.pkg.dev/my-project/my-repo --sort-by=~TIMESTAMP --format="get(digest)" | tail -n +6 | xargs -I {} gcloud container images delete us-docker.pkg.dev/my-project/my-repo@{} --quiet
- 在Cloud Build中配置定时触发器,设置执行频率(如每日/每周),即可自动完成清理
方案对比
- gcr-cleaner:官方维护、配置简单,满足绝大多数通用清理需求
- Cloud Functions自定义:灵活性拉满,适配特殊业务规则的清理场景
- Cloud Build脚本:轻量快速,适合仅需基于数量/时间维度的简单清理
内容的提问来源于stack exchange,提问作者VIKAS KATARIYA
相关产品推荐
相关产品推荐

