In this episode, we'll discuss various methods for deleting Pods in Kubernetes. We'll learn how to delete Pods by name, label selector, namespace, and other advanced techniques.

Note
If you want to read the previous episode, you can click the Episode 8 thumbnail below
In the previous episode, we learned deeply about the Namespace object in Kubernetes. In episode 9, we'll discuss an important operational task: Deleting Pods in Kubernetes.
Note: Here I'll be using a Kubernetes Cluster installed through K3s.
While we learned how to create and manage Pods in episode 5, knowing how to properly delete Pods is equally important. In production environments, you'll frequently need to delete Pods for various reasons: cleaning up resources, troubleshooting issues, performing maintenance, or managing deployments. Understanding different deletion methods and their implications is crucial for effective cluster management.
Before diving into the how, let's understand why you might need to delete Pods:
When you delete a Pod in Kubernetes, several things happen:
During deletion, a Pod goes through these states:
You can see the Terminating state when you run kubectl get pods during deletion:
NAME READY STATUS RESTARTS AGE
nginx-pod 1/1 Terminating 0 5mLet's explore different methods to delete Pods:
The most straightforward way to delete a Pod is by specifying its name:
sudo kubectl delete pod <pod-name>For example:
sudo kubectl delete pod nginx-podOutput:
pod "nginx-pod" deletedTo delete a Pod in a specific Namespace, use the -n or --namespace flag:
sudo kubectl delete pod <pod-name> -n <namespace>For example:
sudo kubectl delete pod nginx-pod -n developmentYou can delete multiple Pods at once by listing their names:
sudo kubectl delete pod <pod-name-1> <pod-name-2> <pod-name-3>For example:
sudo kubectl delete pod nginx-pod-1 nginx-pod-2 nginx-pod-3If you created a Pod using a YAML file, you can delete it using the same file:
sudo kubectl delete -f pod.ymlThis is useful because:
One of the most powerful features is deleting Pods based on their labels. This is especially useful when you have many Pods with similar characteristics.
To delete all Pods with a specific label:
sudo kubectl delete pod -l <key>=<value>For example, delete all Pods with app=nginx:
sudo kubectl delete pod -l app=nginxYou can use multiple label selectors with comma separation (AND logic):
sudo kubectl delete pod -l app=nginx,environment=developmentThis deletes all Pods that have both app=nginx AND environment=development labels.
You can use more advanced selectors:
# Delete Pods where environment is either development or staging
sudo kubectl delete pod -l "environment in (development,staging)"
# Delete Pods where environment is NOT production
sudo kubectl delete pod -l "environment notin (production)"
# Delete Pods that have the tier label
sudo kubectl delete pod -l tier
# Delete Pods that don't have the tier label
sudo kubectl delete pod -l "!tier"Let's create multiple Pods and delete them using labels:
Step 1: Create Pods with labels
apiVersion: v1
kind: Pod
metadata:
name: nginx-dev-1
labels:
app: nginx
environment: development
tier: frontend
spec:
containers:
- name: nginx
image: nginx
---
apiVersion: v1
kind: Pod
metadata:
name: nginx-dev-2
labels:
app: nginx
environment: development
tier: backend
spec:
containers:
- name: nginx
image: nginx
---
apiVersion: v1
kind: Pod
metadata:
name: nginx-prod-1
labels:
app: nginx
environment: production
tier: frontend
spec:
containers:
- name: nginx
image: nginxApply the configuration:
sudo kubectl apply -f labeled-pods.ymlStep 2: Verify Pods are running
sudo kubectl get pods -L app,environment,tierOutput:
NAME READY STATUS RESTARTS AGE APP ENVIRONMENT TIER
nginx-dev-1 1/1 Running 0 30s nginx development frontend
nginx-dev-2 1/1 Running 0 30s nginx development backend
nginx-prod-1 1/1 Running 0 30s nginx production frontendStep 3: Delete only development Pods
sudo kubectl delete pod -l environment=developmentOutput:
pod "nginx-dev-1" deleted
pod "nginx-dev-2" deletedStep 4: Verify only production Pod remains
sudo kubectl get podsOutput:
NAME READY STATUS RESTARTS AGE
nginx-prod-1 1/1 Running 0 2mTo delete all Pods in a specific Namespace:
sudo kubectl delete pods --all -n <namespace>For example:
sudo kubectl delete pods --all -n developmentWarning
Be very careful with this command! It will delete ALL Pods in the specified Namespace. Always double-check the Namespace before running this command.
To delete all Pods in the default Namespace:
sudo kubectl delete pods --allSometimes Pods get stuck in the Terminating state and won't delete normally. In these cases, you can force delete them.
To force delete a Pod immediately:
sudo kubectl delete pod <pod-name> --grace-period=0 --forceFor example:
sudo kubectl delete pod nginx-pod --grace-period=0 --forceWarning
Force deleting Pods should be used as a last resort. It doesn't give containers time to shut down gracefully, which can lead to data loss or corruption. Only use this when a Pod is stuck and won't delete normally.
The grace period is the time Kubernetes gives containers to shut down gracefully:
Example with custom grace period:
# Give 60 seconds for graceful shutdown
sudo kubectl delete pod nginx-pod --grace-period=60You can combine kubectl commands with other tools to delete Pods based on their status.
To delete all Pods with Failed status:
sudo kubectl delete pod --field-selector=status.phase=FailedTo delete all Pods with Succeeded status (completed jobs):
sudo kubectl delete pod --field-selector=status.phase=SucceededYou can use field selectors to target Pods in specific phases:
# Delete Pods in Pending state
sudo kubectl delete pod --field-selector=status.phase=Pending
# Delete Pods in Unknown state
sudo kubectl delete pod --field-selector=status.phase=UnknownLet's create a scenario with failed Pods and clean them up:
Step 1: Create a Pod that will fail
apiVersion: v1
kind: Pod
metadata:
name: failing-pod
spec:
containers:
- name: failing-container
image: busybox
command: ["sh", "-c", "exit 1"]
restartPolicy: NeverApply the configuration:
sudo kubectl apply -f failing-pod.ymlStep 2: Wait for Pod to fail
sudo kubectl get podsOutput:
NAME READY STATUS RESTARTS AGE
failing-pod 0/1 Error 0 10sStep 3: Delete all failed Pods
sudo kubectl delete pod --field-selector=status.phase=FailedYou can combine different methods for more precise deletion:
sudo kubectl delete pod -l app=nginx -n developmentsudo kubectl delete pod -l app=nginx --grace-period=60You can delete multiple resource types at once:
# Delete Pods and Services with specific label
sudo kubectl delete pod,service -l app=nginxWhen Pods are managed by controllers (Deployments, ReplicaSets, StatefulSets, DaemonSets), deleting the Pod directly will cause the controller to recreate it.
If you delete a Pod managed by a Deployment:
sudo kubectl delete pod nginx-deployment-abc123The Deployment will immediately create a new Pod to maintain the desired replica count.
To permanently delete Pods managed by controllers, you need to delete the controller itself:
Delete Deployment (and its Pods)
sudo kubectl delete deployment nginx-deploymentDelete ReplicaSet (and its Pods)
sudo kubectl delete replicaset nginx-replicasetDelete StatefulSet (and its Pods)
sudo kubectl delete statefulset nginx-statefulsetDelete DaemonSet (and its Pods)
sudo kubectl delete daemonset nginx-daemonsetSometimes you want to temporarily stop Pods without deleting the controller:
# Scale Deployment to 0 replicas
sudo kubectl scale deployment nginx-deployment --replicas=0This stops all Pods but keeps the Deployment configuration. You can scale back up later:
# Scale back to 3 replicas
sudo kubectl scale deployment nginx-deployment --replicas=3Let's explore some real-world scenarios for deleting Pods:
You've been testing in the testing Namespace and want to clean up:
# Delete all Pods in testing Namespace
sudo kubectl delete pods --all -n testing
# Or delete the entire Namespace (including all resources)
sudo kubectl delete namespace testingYou've deployed a new version and want to remove old version Pods:
# Delete Pods with old version label
sudo kubectl delete pod -l version=v1.0
# Keep Pods with new version
# (Pods with version=v2.0 remain untouched)After running batch jobs, clean up completed and failed Pods:
# Delete all succeeded Pods
sudo kubectl delete pod --field-selector=status.phase=Succeeded
# Delete all failed Pods
sudo kubectl delete pod --field-selector=status.phase=FailedA Pod is consuming too many resources and needs immediate removal:
# Force delete immediately
sudo kubectl delete pod resource-hog-pod --grace-period=0 --forceDifferent teams use the same cluster with label-based organization:
# Backend team cleans up their development Pods
sudo kubectl delete pod -l team=backend,environment=development
# Frontend team cleans up their staging Pods
sudo kubectl delete pod -l team=frontend,environment=stagingAfter deleting Pods, it's important to verify the deletion was successful:
sudo kubectl get podssudo kubectl get pods -Asudo kubectl get pods -n developmentYou can watch Pods being deleted in real-time:
sudo kubectl get pods -wThis will continuously update the output as Pods change state. Press Ctrl+C to stop watching.
Deleting Pods in the wrong Namespace can cause production issues.
Problem: You meant to delete test Pods but deleted production Pods instead.
Solution: Always verify the Namespace before deletion:
# Check current Namespace
sudo kubectl config view --minify | grep namespace:
# Always specify Namespace explicitly
sudo kubectl delete pod nginx-pod -n developmentForce deleting Pods can cause data loss or corruption.
Problem: Force deleting a database Pod causes data corruption.
Solution: Only use force delete as a last resort. Try normal deletion first and investigate why the Pod won't terminate.
Deleting Pods managed by controllers doesn't achieve the desired result.
Problem: You delete a Pod, but it immediately comes back.
Solution: Delete the controller (Deployment, ReplicaSet, etc.) or scale it to zero.
Manually deleting Pods one by one is inefficient.
Problem: You have 50 test Pods to delete and you're deleting them individually.
Solution: Use label selectors to delete multiple Pods at once:
sudo kubectl delete pod -l environment=testDeleting all Pods without having a way to recreate them.
Problem: You delete all Pods and realize you don't have the YAML configurations.
Solution: Always keep YAML configurations in version control (Git) before deleting resources.
Always label your Pods appropriately so you can delete them selectively:
metadata:
labels:
app: myapp
environment: development
version: v1.0
team: backendAlways verify what you're about to delete:
# List Pods that will be deleted
sudo kubectl get pod -l app=nginx
# Then delete them
sudo kubectl delete pod -l app=nginxUse the --dry-run flag to see what would be deleted without actually deleting:
sudo kubectl delete pod -l app=nginx --dry-run=clientWhen deleting Pods in production, document the reason:
# Add a comment in your terminal history or runbook
# Reason: Cleaning up old version after successful v2.0 deployment
sudo kubectl delete pod -l version=v1.0Keep different environments in separate Namespaces to prevent accidental deletion:
# Development Pods
sudo kubectl delete pod -l app=nginx -n development
# Production Pods are safe in different NamespaceFor regular cleanup tasks, use Kubernetes CronJobs:
apiVersion: batch/v1
kind: CronJob
metadata:
name: cleanup-failed-pods
spec:
schedule: "0 2 * * *" # Run at 2 AM daily
jobTemplate:
spec:
template:
spec:
serviceAccountName: pod-cleaner
containers:
- name: kubectl
image: bitnami/kubectl:latest
command:
- /bin/sh
- -c
- kubectl delete pod --field-selector=status.phase=Failed
restartPolicy: OnFailureAlways keep your Pod configurations in version control:
# You can always recreate Pods from YAML
sudo kubectl apply -f pod.yml
# Safe to delete because you have the configuration
sudo kubectl delete -f pod.ymlUsing kubectl with jq to delete old Pods:
# Delete Pods older than 7 days (requires jq)
sudo kubectl get pods -o json | jq -r '.items[] | select(.metadata.creationTimestamp | fromdateiso8601 < (now - 604800)) | .metadata.name' | xargs sudo kubectl delete podYou can script deletion based on resource usage:
# Get Pods with high memory usage and delete them
# (This is an example - adjust thresholds as needed)
sudo kubectl top pods | awk '$3 > 1000 {print $1}' | xargs sudo kubectl delete podCreate a script for safer batch deletion:
#!/bin/bash
PODS=$(sudo kubectl get pod -l app=nginx -o name)
echo "The following Pods will be deleted:"
echo "$PODS"
read -p "Are you sure? (yes/no): " CONFIRM
if [ "$CONFIRM" = "yes" ]; then
echo "$PODS" | xargs sudo kubectl delete
else
echo "Deletion cancelled"
fiIn episode 9, we've explored various methods for deleting Pods in Kubernetes. We've learned how to delete Pods by name, label selector, Namespace, status, and using advanced techniques.
Key takeaways:
kubectl delete pod with various options for different deletion scenariosUnderstanding how to properly delete Pods is essential for cluster maintenance, troubleshooting, and resource management. By mastering these techniques, you can efficiently manage your Kubernetes workloads and maintain a clean, well-organized cluster.
Are you getting a clearer understanding of Pod deletion in Kubernetes? In the next episode 10, we'll discuss another important Kubernetes concept: Probe. Probe is used to check the health of a Pod and restart it if it's not healthy.
Note
If you want to continue reading, you can click the Episode 10 thumbnail below