Kubectl Delete Pod: How to Delete/Drain Pods from a Kubernetes Node

How to Delete Pods From Kubernetes Nodes

In Kubernetes, a pod is the smallest deployable unit that can be created, managed, and scaled. Pods encapsulate one or more containers, storage resources, a unique network IP, and options that govern how the containers should run. Deleting pods is a common task that might be necessary for various reasons, such as rolling updates, scaling down applications, or removing malfunctioning pods.

This guide will provide an in-depth look at how to delete pods in Kubernetes using kubectl delete command.

Deleting Pods by Name

The most straightforward way to delete a pod is by its name. Use the following command to delete a specific pod:

 # kubectl delete pod pod-name

Example:

 # kubectl delete pod nginx-pod

This command will terminate the specified pod and remove it from the cluster.

pod "nginx-pod" deleted

Deleting Pods by Label

Labels are key/value pairs attached to objects in Kubernetes, such as pods, which can be used to select a group of objects. You can delete multiple pods at once by specifying a label selector.

 # kubectl delete pods -l label-key=label-value

Example:

 # kubectl delete pods -l app=nginx

This command deletes all pods with the label app=nginx.

pod "nginx-pod1" deleted
pod "nginx-pod2" deleted

Deleting Pods by Field Selector

Field selectors let you select Kubernetes resources based on the value of one or more resource fields. To delete pods by a field selector, use:

 # kubectl delete pods --field-selector field-selector

Example:

 # kubectl delete pods --field-selector status.phase=Failed

This command deletes all pods that are in the Failed phase.

pod "failed-pod1" deleted
pod "failed-pod2" deleted

Deleting Completed Pods

Pods that have completed their tasks and are in the Succeeded phase can also be deleted to free up resources.

 # kubectl delete pods --field-selector=status.phase=Succeeded

This command deletes all pods that are in the Succeeded phase.

pod "completed-pod1" deleted
pod "completed-pod2" deleted

Graceful Deletion of Pods

By default, Kubernetes gracefully shuts down pods. When a pod is deleted, it terminates, allowing it to complete ongoing operations.

To specify a grace period before forcefully terminating a pod, use the –grace-period flag:

 # kubectl delete pod pod-name --grace-period=seconds

Example:

 # kubectl delete pod nginx-pod --grace-period=30

This command gives the pod 30 seconds to shut down gracefully before being forcefully terminated.

Force Deleting Pods

In some cases, a pod might not terminate gracefully. To forcefully delete a pod, use the –force flag along with a grace period of 0:

 # kubectl delete pod pod-name --grace-period=0 --force

Example:

 # kubectl delete pod nginx-pod --grace-period=0 --force

This command immediately deletes the pod without waiting for graceful termination.

pod "nginx-pod" force deleted

Deleting Evicted Pods

Evicted pods are pods that have been forcibly removed from a node due to resource constraints or other reasons. These pods need to be manually deleted. You can identify evicted pods using a field selector and delete them:

 # kubectl delete pod --field-selector=status.reason=Evicted

Example:

 # kubectl delete pod --field-selector=status.reason=Evicted

Output.

pod "evicted-pod1" deleted
pod "evicted-pod2" deleted

Automating Pod Deletion with CronJobs

You can automate the deletion of pods using Kubernetes CronJobs. This is useful for recurring cleanup tasks.

1. Create a CronJob manifest file delete-pods-cronjob.yaml:

apiVersion: batch/v1beta1
kind: CronJob
metadata:
  name: delete-failed-pods
spec:
  schedule: "0 */6 * * *" # Runs every 6 hours
  jobTemplate:
    spec:
      template:
        spec:
          containers:
          - name: kubectl
            image: bitnami/kubectl
            command:
            - /bin/sh
            - -c
            - kubectl delete pod --field-selector=status.phase=Failed
          restartPolicy: OnFailure

2. Apply the CronJob:

 # kubectl apply -f delete-pods-cronjob.yaml

This will create a CronJob that deletes failed pods every 6 hours.

cronjob.batch/delete-failed-pods created

Troubleshooting Pod Deletion

If you encounter issues while deleting pods, check the following:

  • Pod Status: Ensure the pod is not already in the process of terminating.
  • Pod Finalizers: Check if any finalizers prevent the pod from being deleted.
  • Kubernetes Events: View events related to the pod to understand why they might not be deleted.

Commands to help with troubleshooting:

 # kubectl describe pod pod-name

Example:

 # kubectl describe pod nginx-pod

Output.

Name:         nginx-pod
Namespace:    default
Priority:     0
Node:         minikube/192.168.49.2
Start Time:   Tue, 08 Jul 2024 12:34:56 +0000
Labels:       none
Annotations:  none
Status:       Running
IP:           172.17.0.4
...

The kubectl get events command with the –field-selector option allows you to filter Kubernetes events related to a specific object, such as a pod. In this case, you want to filter events related to a nginx-pod pod.

 # kubectl get events --field-selector involvedObject.name=nginx-pod

This command will list all events associated with the nginx-pod.

LAST SEEN   TYPE      REASON              OBJECT            MESSAGE
20m         Normal    Scheduled           pod/nginx-pod     Successfully assigned default/nginx-pod to minikube
19m         Normal    Pulling             pod/nginx-pod     Pulling image "nginx"
18m         Normal    Pulled              pod/nginx-pod     Successfully pulled image "nginx" in 58.3154ms
18m         Normal    Created             pod/nginx-pod     Created container nginx
18m         Normal    Started             pod/nginx-pod     Started container nginx

Conclusion

Deleting pods in Kubernetes is a fundamental operation that is essential for maintaining and managing your cluster. Whether you need to delete a single pod or a group of pods, kubectl provides versatile commands. Understanding the different methods and options available for pod deletion ensures you can handle various scenarios effectively.

FAQs

1. How can I safely drain pods from a Kubernetes node?

Run kubectl drain node_name --ignore-daemonsets --delete-local-data to safely drain a node and evict its pods.

2. How do I cordon a Kubernetes node without draining pods?

You can mark a node unschedulable without evicting pods using kubectl cordon node_name command.

3. Can I drain a specific pod from a node instead of all pods?

No, kubectl drain evicts all pods from the node.

4. How do I force delete a stuck pod in Kubernetes?

You can forcefully delete a pod using kubectl delete pod pod_name --grace-period=0 --force command.

5. How do I undo a drain and allow new pods to be scheduled on a node?

You can uncordon a node to allow new pods to be scheduled by running: kubectl uncordon node_name

6. What’s the difference between kubectl delete pod and kubectl drain?

kubectl delete pod removes a specific pod, while kubectl drain evicts all pods from a node and marks the node as unschedulable.

About Hitesh Jethva

Experienced Technical writer, DevOps professional with a demonstrated history of working in the information technology and services industry. Skilled in Game server hosting, AWS, Jenkins, Ansible, Docker, Kubernetes, Web server, Security, Proxy, Iptables, Linux System Administration, Domain Name System (DNS), and Technical Writing.

View all posts by Hitesh Jethva