k8s批量删除pod - Wed, Sep 11, 2019
k8s批量删除pod
k8s批量删除pod
基本用法
# 删除特定条件的pod
kubectl delete pod $(kubectl get pod -n iot | grep broker | awk '{print $1}') -n iot
Makefile中使用
# 在Makefile中使用
delete-pod:
@kubectl delete pod $$(kubectl get pod -n iot | grep $(IMAGE_NAME) | awk '{print $$1}') -n iot
常用批量删除方法
方法1:根据名称过滤
# 删除名称包含特定字符串的pod
kubectl get pods -n default | grep nginx | awk '{print $1}' | xargs kubectl delete pod -n default
# 或使用字段选择器
kubectl get pods -n default -o name | grep nginx | xargs kubectl delete -n default
方法2:根据标签删除
# 删除特定标签的pod
kubectl delete pod -l app=nginx
# 删除多个标签
kubectl delete pod -l 'app in (nginx,redis)'
# 排除特定标签
kubectl delete pod -l 'app!=nginx'
方法3:根据状态删除
# 删除所有Evicted pod
kubectl get pods --all-namespaces -o json | jq '.items[] | select(.status.reason=="Evicted") | "kubectl delete pod \(.metadata.name) -n \(.metadata.namespace)"' | sh
# 或简单方法
kubectl delete pod --field-selector=status.phase=Failed --all-namespaces
方法4:根据时间删除
# 删除创建超过7天的pod
kubectl get pods -o name | xargs -I {} kubectl get {} -o jsonpath='{.metadata.creationTimestamp}'
强制删除
# 强制删除(不推荐)
kubectl delete pod <pod-name> -n <namespace> --force --grace-period=0
# 删除Terminating状态的pod
kubectl patch pod <pod-name> -p '{"metadata":{"finalizers":null}}'
使用脚本批量管理
#!/bin/bash
# delete_pods.sh
NAMESPACE="default"
LABEL="app=nginx"
echo "Deleting pods with label $LABEL in namespace $NAMESPACE"
kubectl delete pod -n $NAMESPACE -l $LABEL
定时清理
apiVersion: batch/v1
kind: CronJob
metadata:
name: cleanup-evicted-pods
spec:
schedule: "0 */6 * * *"
jobTemplate:
spec:
template:
spec:
containers:
- name: kubectl
image: bitnami/kubectl
command:
- kubectl
- delete
- pods
- --all-namespaces
- --field-selector=status.phase=Failed
restartPolicy: OnFailure
最佳实践
- 使用标签管理:通过标签批量管理pod
- 避免直接删除:优先修改控制器配置
- 优雅删除:给足grace period时间
- 监控清理:定期清理Evicted pod