谷歌云如何实现创建新Docker镜像时自动删除旧镜像?
自动清理Google Cloud Artifact Registry旧镜像的方案
方案1:配置Artifact Registry原生生命周期规则
这是最省心的官方方案,无需额外代码:
- 打开Google Cloud控制台,找到你的Artifact Registry镜像仓库
- 进入仓库的生命周期标签页,点击添加规则
- 按需设置清理条件:
- 按时间:删除创建超过X天的镜像版本(比如30天)
- 按数量:保留最近N个镜像版本(比如10个),自动删除更早的
- 还可以加过滤条件,比如只清理非
latest标签的开发镜像
- 保存规则后,系统会自动按周期执行清理
方案2:Cloud Build构建后自动清理
如果你的镜像由Cloud Build自动生成,可以在构建流程里加清理步骤:
- 修改
cloudbuild.yaml,在构建完成后添加清理脚本:
steps: # 这里放你原本的构建、推送镜像步骤 - name: 'gcr.io/google.com/cloudsdktool/cloud-sdk' entrypoint: 'bash' args: - '-c' - | # 替换为你的项目ID和仓库名 REPO="us-central1-docker.pkg.dev/你的项目ID/你的仓库名" # 保留最近5个镜像,删除更早的 gcloud artifacts docker images list $REPO --format="value(digest)" --sort-by=~create_time | tail -n +6 | while read digest; do gcloud artifacts docker images delete $REPO@$digest --quiet done
- 每次代码推送触发构建后,都会自动清理掉超出数量的旧镜像
方案3:定时执行自定义清理脚本
需要更灵活的逻辑(比如按标签、分支过滤)时,用定时任务实现:
- 写一个清理脚本,比如用Python调用Artifact Registry API:
from google.cloud import artifactregistry_v1 from datetime import datetime, timedelta client = artifactregistry_v1.ArtifactRegistryClient() # 替换为你的项目信息 PROJECT_ID = "你的项目ID" LOCATION = "us-central1" REPO_NAME = "你的仓库名" parent = client.repository_path(PROJECT_ID, LOCATION, REPO_NAME) versions = client.list_versions(parent=parent) # 删除7天前创建的非latest标签镜像 cutoff = datetime.now() - timedelta(days=7) for version in versions: create_time = version.create_time if create_time < cutoff and "latest" not in version.name: client.delete_version(name=version.name)
- 把脚本部署为Cloud Functions,用Cloud Scheduler设置每天凌晨触发
- 或者打包成镜像部署为Cloud Run服务,通过Cloud Scheduler定时调用接口触发清理
内容的提问来源于stack exchange,提问作者RicardoRuizQ
相关产品推荐
相关产品推荐

