You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Kubernetes中清理旧Deployment并保留最新5个的命令实现

Kubernetes 清理旧 Deployment 命令方案

问题分析

需要清理 web 命名空间内前缀为 myproject-static-staging 的旧 Deployment,仅保留最新的5个。当前通过kubectl -n web get deploy --sort-by=.metadata.creationTimestamp可查看按创建时间升序排列的列表(最旧的在前,最新的在后)。

原命令存在两个关键错误:

  • 使用 head -n 5 取升序列表的前5项,实际是删除最旧的5个,而非保留最新5个
  • grep -v master 错误排除了需要删除的旧实例 myproject-static-staging-master

正确命令

验证版本(先确认要删除的实例)

kubectl get deployment -n web --sort-by=.metadata.creationTimestamp --template '{{range .items}}{{.metadata.name}}{{"\n"}}{{end}}' | grep myproject-static-staging | head -n -5

执行删除版本

kubectl get deployment -n web --sort-by=.metadata.creationTimestamp --template '{{range .items}}{{.metadata.name}}{{"\n"}}{{end}}' | grep myproject-static-staging | head -n -5 | xargs -r kubectl -n web delete deployment

命令说明

  1. 按创建时间升序输出实例名称:kubectl get deployment -n web --sort-by=.metadata.creationTimestamp --template '{{range .items}}{{.metadata.name}}{{"\n"}}{{end}}'
    • 升序排列后,最旧的实例在前,最新的实例在后
  2. 过滤目标前缀实例:grep myproject-static-staging,仅处理指定前缀的Deployment
  3. 筛选需删除的实例:head -n -5,输出除最后5个(最新的5个)之外的所有实例
  4. 批量删除:xargs -r kubectl -n web delete deployment,-r 参数确保无输入时不执行删除命令,避免报错

内容的提问来源于stack exchange,提问作者igramnet

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 01:55:11