Using kubectl delete | Tutorial and best practices (2023)

The Kubernetes command line tool,kubectl, provides a way to communicate with theKubernetes-Clusterthrough the control plane to manage resources by creating, editing, and extracting details about specific resources. The tool contains a number of commands that can be used to perform various tasks.

One of the commands associated with this tool is the <terminal inline>kubectl delete<terminal inline> command. This command allows you to gracefully shut down running resources. Some of the use cases for the <terminal inline>kubectl delete<terminal inline> command include theTermination of running pods, Implementations, Services, StatefulSets and many other resources.

In this guide, you'll learn how to properly use <terminal inline>kubectl delete<terminal inline> to stop resources, and learn about the various parameters this command exposes. You will learn some best practices to guide you in using this command safely and correctly.

What is kubectl removal?

kubectl delete gives you the ability to gracefully close and terminate Kubernetes resources based on their specific filenames or resource names. Gracefully terminating resources with the <terminal inline>kubectl delete<terminal inline> command should be done with the utmost discretion, since once the command has run, there is no way to undelete the resource.

Kubernetes does not provide users with the ability to pause and resume resources. There are several ways to work around this limitation. One of them is to simply stop (delete) the desired resource to pause it and reapply the resource definition to the cluster to resume it.

The <terminal inline>kubectl delete<terminal inline> command is particularly useful when cleaning up an application after deployment. During development, the creation and deployment of resources is a major concern, but managing those resources sometimes falls by the wayside after deployment.

Some of these resource management tasks include removing unused pods. While these pods are running and not being used in the Kubernetes cluster, they consume some of the node's resources, limiting other, more important running pods.

In some cases, aKubernetes nodeIt should be shut down and Kubernetes services and deployments must be stopped. Another resource management issue might be the removal of StatefulSets that manage pods that depend on persistent storage configurations, e.g. B. Persistent Volumes.

Using kubectl delete | Tutorial and best practices (1) Using kubectl delete | Tutorial and best practices (2)

Monitor Kubernetes events in real time

Monitor the health of your cluster and resolve issues faster with pre-built dashboards that just work.

(Video) Kubernetes Tutorial for Beginners [FULL COURSE in 4 Hours]

Learn more Book a demo

Using kubectl delete | Tutorial and best practices (3)

Using kubectl delete | Tutorial and best practices (4) Using kubectl delete | Tutorial and best practices (5)

Remove with kubectl

Before starting this tutorial, you should understand the following Kubernetes concepts:

  • Debt
  • stateful sentences
  • Replikat-Sets
  • Calls
  • Services
  • kubectlCommand line tool

To begin using <terminal inline>kubectl delete<terminal inline> , you must have a single-node Kubernetes cluster running with at least 4 GB of available RAM. You can create one locally with simple Kubernetes distributions, e.gMinikube,K3s, ÖMicroK8s, or you can purchase one from a cloud provider such asGoogles Kubernetes Engine(ONG),Azure Kubernetes service, ÖService Amazon Elastic Kubernetes(EXP).

Basic use case to remove kubectl

Now that your cluster is set up, you can get started with a basic use case of the <terminal inline>kubectl delete<terminal inline> command.

Deploy an example NGINX deployment by creating a file named <terminal inline>deployment.yaml<terminal inline> and then adding the following code snippet:

apiVersion: apps/v1kind: deployment metadata: name: nginx deployment labels: application: nginxspec: replicas: 3 selector: matchLabels: application: nginx template: metadata: labels: application: nginx specification: container: - name: nginx image: nginx: 1.14.2 Ports: - ContainerPort: 80

Then run the configurations on your Kubernetes cluster using <terminal inline>kubectl apply<terminal inline>Domain:

kubectl apply -f ./deployment.yaml

The above command creates an NGINX deployment with a ReplicaSet and three NGINX Pods deployed and running on the default <Inline-Terminal><Inline-Terminal>namespaceon your Kubernetes cluster. To check this, you can just run <terminal inline>kubectl get pod<terminal inline> command and get the following response:


After you have successfully deployed NGINX to your Kubernetes cluster, the next step is to post-deployment cleanup.

(Video) Kubernetes Security Best Practices you need to know | THE Guide for securing your K8s cluster!

If you run the <terminal inline>kubectl delete pods --all<terminal inline> command to delete all NGINX pods in the default namespace, a different set of pods reappears to replace the deleted ones. To prevent this, you should delete the deployment configuration with filename <inline terminal>deployment.yaml<inline terminal> or deployment name <inline terminal>nginx-deployment<inline terminal> as shown in the < terminal inline>metadata<terminal section inline> in the YAML snippet above.

The NGINX implementation can be removed in two ways:

# Delete deployment with filenamekubectl delete -f ./deployment.yaml# Delete deployment with metadata name:kubectl Delete deployment nginx deployment

After the deployment resource is deleted, you should not be able to see any pods, deployments, or ReplicaSets in the <terminal inline>default<terminal inline> namespace. You only see a single active Kubernetes service when you run the <terminal inline>kubectl get services<terminal inline> command:

Get kubectl services

This will display the services available in the <terminal inline>default<terminal inline> namespace:

Service/KubernetesCluster-IP10.43.0.1<none>443/TCP45 Std

Please note that depending onKubernetes distribution typeis running, the output shown above may vary slightly.

Advanced use case to remove kubectl

In the previous section, you created a simple NGINX implementation and then successfully removed it. In this section, you'll see a more advanced use case for the <terminal inline>kubectl delete<terminal inline> command and walk through the steps required to use the command.

In this example, you will implement the popular WordPress CMS. To do this, create the WordPress service <terminal inline>wp-pv-claim<terminal inline> PersistentVolumeClaim and deploy the WordPress app with the latest Docker Hub image.

Using your favorite text editor, create a file named <terminal inline>wordpress.yaml<terminal inline> and paste the following YAML code:

apiVersion: v1kind: Servicemetadata: name: wordpress tags: application: wordpressspec: ports: - port: 80 selector: application: wordpress tier: frontend type: LoadBalancer---apiVersion: v1kind: PersistentVolumeClaimmetadata: name: wp-pv-claim tags: app: wordpressspec: accessModes: -ReadWriteOnce Resources: Requests: Storage: 1Gi---apiVersion: apps/v1kind: Deploymentmetadata: Name: WordPress Labels: app: wordpressspec: selector: matchLabels: app: wordpress level: interface strategy: type: Rebuild Template: Metadata: Tags: Application: WordPress Layer: Frontend Specification: Container: - Image: Wordpress:5.9.3-Apache Name: Wordpress env: - Name: WORDPRESS_DB_HOST Value: Wordpress DB - Name: WORDPRESS_DB_PASSWORD Value: Password Ports: - containerPort: 8080 name: wordpress volumeMounts: - name: wordpress-persistent-storage mountPath: /var/www/html volumes: - name: wordpress-persistent-storage persistentVolume eClaim: ClaimName: wp-pv-claim

Apply the above configuration to your cluster by running the <terminal inline>kubectl apply<terminal inline> command:

(Video) Kubernetes in 5 mins

kubectl describes the deployment test web application

You will see output similar to the following:

$ kubectl apply -f ./wordpress.yml service/wordpress createdpersistentvolumeclaim/wp-pv-claim createddeployment.apps/wordpress created

Verify that the changes were made correctly by using the <terminal inline>kubectl get all<terminal inline> command:

kubectl get everything

You should get an output similar to this:

NAME READY STATUS RESTART AGEpod/svclb-wordpress-4r66v 1/1 Running 0 25spod/wordpress-66ff8d4cb4-k746r 1/1 Running 0 25sNAME TYPE CLUSTER IP EXTERNAL IP PORT(S) AGEservice/kubernetes ClusterIP < none> 443/TCP 9dservice/wordpress LoadBalancer 8080:32552/TCP 25s CURRENT NAME DESIRED READY UPDATED NODE SELECTION AVAILABLE AGEdaemonset.apps/svclb-wordpress 1 1 1 1 1 <noneUPDATE/DATED.appyploment.depressment/1.appyploment.depressment AGE> 25s AGE 1 1 25s CURRENT DESIRED NAME READY AGErepliset.apps/wordpress-66ff8d4cb4 1 1 1 25s

After verifying that the WordPress deployment was successful, you can proceed with the cleanup.

As before, trying to delete the pods is useless as the implementation specification recreates them as many times as needed. Fortunately, you only have to use one command to delete the newly created implementation, service, and PVC:

$ kubectl delete -f ./wordpress.yamlservice "wordpress" eliminatedpersistentvolumeclaim "wp-pv-claim" eliminateddeployment.apps "wordpress" eliminated

If you want, you can confirm the above output with the commands:

kubectl getserviceskubectl Retrieves persistent volume claims

The output should look something like this:


No resources foundindefault namespace.

(Video) Improving my Kubernetes Setup // Security and Best-Practices!

Another way to check that there are no traces of WordPress left is to use the <terminal inline>kubectl get all<terminal inline> command again:

$ kubectl get everything


As you can see, the <terminal inline>kubectl delete<terminal inline> command is useful for both simple and more advanced use cases.

However, note that this was possible because a single YAML file was used to configure all moving parts. This may or may not be a good idea as you could accidentally delete even data stored on onesustained volume. This brings us to the next section, Best Practices.

Better Practices

A single misused <terminal inline>kubectl delete<terminal inline> command can destroy an entire application and render it unusable. There are no safety precautions such as B. Prompts to ask if you really want to delete the resource or not attached to the command. Before you perform any operation with the <terminal inline>kubectl delete<terminal inline> command, you need to know exactly what you want to delete and how you want to delete it.

You can use the <terminal inline>kubectl delete --help<terminal inline> command to see a list of flags and options that can be applied.

Know when and how to use kubectl delete

To understand when to delete Kubernetes resources, you need to understand your application's tolerance for the unavailability of one or more resources. If any of the resources are removed, your app should continue to work.

Likewise, knowing how resources are cleared is important to keep your services and applications running. For example, removing resources should be avoided when the <terminal inline>--force<terminal inline> flag is set to <terminal inline>true<terminal inline> , as this may result in a resource inconsistency that may cause an application runtime error or would cause data loss. . Unless you are very sure that this will not cause problems for your application, this should only be used as a last resort.

Use kubectl delete only when absolutely necessary

It is highly recommended that you use the <terminal inline>kubectl delete<terminal inline> command sparingly unless you are performing critical operations such as: B. Cleanup operations for resource optimization.

It is also recommended to defer removing PersistentVolumeClaims until all necessary data has been restored or copied by using the <terminal inline>kubectl cp<terminal inline> command from <terminal inline>mountPath<terminal inline> on your host machine.

(Video) Kubernetes Logging | Using kubectl & Best Practices

final thoughts

In this article, you learned about the <terminal inline>kubectl delete<terminal inline> command: what it is, the different use cases, and recommended uses.

The <terminal inline>kubectl delete<terminal inline> command can be very useful when managing resources, but it's important to note that while you can prevent bottlenecks in your application, so can <terminal inline>kubectl delete<terminal inline> Discontinue your application completely if used carelessly.

Kubernetes deployments are best paired with a monitoring solution like ContainIQ, which allows you to keep an eye on your resources, analyze logs and track potential issues in your application, keep you informed about the health of your cluster, and Your cluster better manage resources. .


What does kubectl delete do? ›

What is kubectl delete? kubectl delete offers you a way to gracefully shut down and terminate Kubernetes resources by their filenames or specific resource names.

What are the best practices for Kubernetes? ›

  • Administer a Cluster. Reconfiguring a kubeadm cluster. ...
  • Use a User Namespace With a Pod.
  • Troubleshooting Applications. Debug Pods. ...
  • Horizontal Pod Autoscaling. HorizontalPodAutoscaler Walkthrough.
  • Job with Pod-to-Pod Communication. ...
  • Deploy and Access the Kubernetes Dashboard. ...
  • Use a SOCKS5 Proxy to Access the Kubernetes API.
Dec 25, 2022

Does deleting namespace delete all resources? ›

Deleting a namespace is a final act. Everything in the namespace including all services, running pods, and artifacts will be deleted.

What is the purpose of delete command? ›

The Delete command in SQL is a part of the Data Manipulation Language, a sub-language of SQL that allows modification of data in databases. This command is used to delete existing records from a table. Using this, you can either delete specific records based on a condition or all the records from a table.

What happens when kubectl delete pod? ›

Kubernetes pod gets recreated when deleted.

How do I delete completed pods in Kubernetes? ›

First, confirm the name of the node you want to remove using kubectl get nodes , and make sure that all of the pods on the node can be safely terminated without any special procedures. Next, use the kubectl drain command to evict all user pods from the node.

How do I delete old pods in Kubernetes? ›

The only ways in which a Pod in such a state can be removed from the apiserver are as follows:
  1. The Node object is deleted (either by you, or by the Node Controller).
  2. The kubelet on the unresponsive Node starts responding, kills the Pod and removes the entry from the apiserver.
  3. Force deletion of the Pod by the user.

How do I delete an object in Kubernetes? ›

You can use the delete command to delete an object from a cluster: delete <type>/<name>

How can I improve my Kubernetes performance? ›

To enhance Kubernetes performance, focus on defining resource limits, using optimized and lightweight container images, and deploying clusters closer to your users.
  1. Define resource limits. ...
  2. Use optimized, lightweight container images. ...
  3. Deploy Kubernetes clusters closer to your users.
Dec 21, 2022

How do I clean up Kubernetes resources? ›

The simplest method of deleting any resource in Kubernetes is to use the specific manifest file used to create it. With the manifest file on hand, we can use the kubectl delete command with the -f flag. The manifest file contains all of the information to target a specific resource.

What happens when you delete a Kubernetes namespace? ›

Sometimes a user deletes a namespace before all its resources have been removed. This action may cause the namespace to become permanently stuck in the Terminating status. Kubernetes does not allow creating another namespace with the same name until the deletion process is finished.

How do I clean up namespace? ›

Use the ibmcloud cr retention-run command to clean up a namespace by retaining a specified number of images for each repository within a namespace in IBM Cloud Container Registry. All other images in the namespace are deleted. You can choose whether to exclude untagged images from the clean-up process.

How do I delete everything under the namespace in Kubernetes? ›

# kubectl-delete_all is a utility to delete all objects in the namespace.

What is the procedure of DELETE command? ›

Delete Process Command
delete process/* Search Criteria */
[pname=Process name | generic | (list)]
[pnumber=Process number | (list)]
[snode=snode name | generic | (list)]
4 more rows

What is the difference between truncate and DELETE? ›

The DELETE command is used to delete particular records from a table. The TRUNCATE command is used to delete the complete data from the table. It is a DML command. The DELETE command acquires the lock on every deleting record; thus, it requires more locks and resources.

What is DELETE command give example? ›

Delete command is a data manipulation command which is used to remove records from a table. All records may be removed in one go, or a set of records may be deleted based on a condition.

Does kubectl replace delete? ›

kubectl replace command, will delete the existing resource and recreate it from the given definition file.

Will deleting a pod restart it? ›

Overall, both the rollout restart and delete commands can be used to restart pods in Kubernetes, but they work in different ways and have different effects on the system. The rollout restart command is used to restart an entire deployment or replica set, while the delete command is used to delete individual pods.

How do I delete a pod without waiting? ›

To skip the wait, run the command with the --wait=false option. When you delete a pod object, all its containers are terminated in parallel. The pod's deletionGracePeriodSeconds is the time given to the containers to shut down.

How do I delete a pod after completion? ›

Here is a single command to delete all pods that are terminated, Completed, in Error, etc.
Here's an explanation:
  1. get all pods without any of the headers.
  2. filter out pods which are Running.
  3. filter out pods which are Pending.
  4. pull out the name of the pod using a sed regex.
  5. use xargs to delete each of the pods by name.
Mar 8, 2019

How do I delete all clusters in Kubernetes? ›

Deleting a cluster
  1. Go to the Google Kubernetes Engine page in the Google Cloud console. Go to Google Kubernetes Engine.
  2. Next to the cluster you want to delete, click more_vert Actions, then click delete Delete.
  3. When prompted to confirm, click Delete again.

How do I manually delete pods? ›

The action of deleting the pod is simple. To delete the pod you have created, just run kubectl delete pod nginx . Be sure to confirm the name of the pod you want to delete before pressing Enter. If you have completed the task of deleting the pod successfully, pod nginx deleted will appear in the terminal.

How do I delete a container in Kubernetes? ›

Removing data collector Docker container / Kubernetes pod
  1. Run the following command to remove Docker container: docker stop <Container_ID> docker rm <Container_ID> ...
  2. Optional: Run the following command to remove the container forcefully: docker rm -f < Container_ID>

How do I delete pod files and install again? ›

Just rm -rf that pod's folder, and remove the line from the Podfile. Then run pod install again.

How do I delete pods from multiple namespaces? ›

To delete pods in a different namespace, just add --namespace=<name of namespace> to that command. To delete pods in all namespaces, add --all-namespaces .

How do I delete a node in Kubernetes? ›

To remove a Kubernetes Node:

Log in to the Kubernetes Node that you want to remove. Log in to the Salt Master node. Log in to any Kubernetes Master node. Wait until the workloads are gracefully deleted and the Kubernetes Node is removed.

How do I delete a data object? ›

There are three ways using which we can easily delete any property of the object. The first way is using the special operator in JavaScript called the delete operator, the second way is using Object Destructuring and the third one is using the Reflect. deleteProperty() method.

Does deleting namespace delete pods? ›

2. Delete deployment in namespace which will delete PODS - e.g. kubectl delete deployment <deployment_name> The second approach which I would take is by deleting all the deployment which belongs to POD, this approach is indirect because in a typical Kubernetes POD we do multiple deployments of the docker container.

What are the common issues with Kubernetes? ›

7 Common Kubernetes Pitfalls
  • Incorrect Labels and Selectors. ...
  • Ignoring Health Checks. ...
  • Using the Default Namespace for all Objects. ...
  • Using the 'Latest' Tag. ...
  • Lack of Monitoring and Logging. ...
  • Wrong Container Port Mapped to a Service. ...
  • Crashloopbackoff error. ...
  • Wrapping Up.
Sep 2, 2022

Why is Kubernetes so difficult? ›

Kubernetes manages containers, but it's difficult for developers to understand the moving parts in a large enterprise container environment. Having many more moving parts also introduces a larger attack surface.

When you should not use Kubernetes? ›

5 Reasons You Should NOT Use Kubernetes
  1. If you don't need high availability.
  2. If your app is monolithic.
  3. The cost of the learning curve.
  4. The cost … in general.
  5. Its sheer complexity.
Nov 1, 2021

How do I know if my Kubernetes are healthy? ›

TCP: If your application has an open port, Kubernetes can do a simple TCP connect check. If the connection is fine, the application passed the health check. gRPC: You can use gRPC-health-probe in your container to enable the gRPC health check if you are running a Kubernetes version 1.23 or less.

How do I know if my Kubernetes cluster is healthy? ›

Check Cluster Health
  1. Run the command kubectl describe cluster . If the status is ready, it means that both the cluster infrastructure and the cluster control plane are ready. ...
  2. If the cluster is not ready, run the following command to determine what is wrong with the cluster infrastructure: kubectl describe wcpcluster.
Oct 20, 2021

How long does it take to master Kubernetes? ›

It will take you approximately 13 hours to complete this entire learning path.

How do I delete a workload in Kubernetes? ›

To delete a workload cluster, run the tanzu cluster delete command.
For each PVC:
  1. Run kubectl describe pvc <my-pvc> to identify the PV it is bound to. ...
  2. Run kubectl describe pv <my-pv> to describe to determine if its bound PV Reclaim Policy is Retain or Delete .
  3. Run kubectl delete pvc <my-pvc> to delete the PVC.

What is the difference between foreground and background in Kubernetes delete? ›

Foreground: The object itself cannot be deleted before all the objects that it owns are deleted. Background: The object itself is deleted, after which the GC deletes the objects that it owned. Orphan: The object itself is deleted.

How do I clean up deployment in Kubernetes? ›

Clean Up
  1. EKS cluster. $ kubectl delete -k envs/eks/
  2. Other cluster types. $ kubectl delete -k envs/local-env/

What happens if you delete a Kubernetes node? ›

If I directly delete that node (using the commands mentioned in other answers), data will get lost because those pods have some PersistentVolumes, and deleting a Node will also delete PersistentVolumes (if using some cloud providers). Thus, please manually delete those pods one by one.

Does deleting namespace delete PVC? ›

Accidental PVC delete or namespace delete can cause the Persistent Volume to get deleted. Such volumes lose their data, and the stateful applications lose their state. By using Persistent Volume TrashCan, users can get a grace period to undo such unintended delete operation.

What is the difference between namespace and node in Kubernetes? ›

Save this question. Show activity on this post. Relationship between cluster and namespaces : - Namespaces are in cluster Relationship between cluster and node :- Nodes are in cluster Relationship between pod and namespaces :- Pods run under namespace Relationship between pod and Node : - pods can run on node.

How do I delete pods in namespace? ›

steps to delete pv:
  1. delete all deployment and pods or resources related to that PV kubectl delete --all deployment -n namespace kubectl delete --all pod -n namespace.
  2. edit pv kubectl edit pv pv_name -n namespace remove
  3. delete pv kubectl delete pv pv_name -n namespace.

How do I delete all resources in a specific namespace? ›

To do a mass delete of all resources in your current namespace context, you can execute the kubectl delete command with the -all flag.

How do I delete a namespace in Linux? ›

ip netns delete NAME - delete the name of a network namespace If NAME is present in /var/run/netns it is umounted and the mount point is removed. If this is the last user of the network namespace the network namespace will be freed, otherwise the network namespace persists until it has no more users.

How do I delete all my jobs in kubectl? ›

you can do kubectl -n <namespace name> delete ...

What command do you use to delete everything on your cluster? ›

Now that you've successfully deployed NGINX to your Kubernetes cluster, the next step is to clean up after the deployment. If you perform the command kubectl delete pods --all to delete all the NGINX pods in the default namespace, another set of pods will spring back up to replace the ones that were deleted.

What happens when you delete a namespace? ›

Sometimes a user deletes a namespace before all its resources have been removed. This action may cause the namespace to become permanently stuck in the Terminating status. Kubernetes does not allow creating another namespace with the same name until the deletion process is finished.

How do I delete a file in kubectl? ›

The simplest method of deleting any resource in Kubernetes is to use the specific manifest file used to create it. With the manifest file on hand, we can use the kubectl delete command with the -f flag. The manifest file contains all of the information to target a specific resource.

How do I safely remove a node from Kubernetes? ›

To remove a Kubernetes Node:

Log in to the Kubernetes Node that you want to remove. Log in to the Salt Master node. Log in to any Kubernetes Master node. Wait until the workloads are gracefully deleted and the Kubernetes Node is removed.

What is the fastest way to delete a node module? ›

On Windows Platform the simplest way is to use the terminal. Please Run the command RMDIR /Q/S foldername to delete the folder and all of its subfolders. The Above Command deletes node_modules folder and its subfolders.

What happens if master goes down in Kubernetes? ›

Failure Impact of a Down Kubernetes Cluster

Even when the master node goes down, worker nodes may continue to operate and run the containers orchestrated on those nodes. If certain applications or pods were running on those master nodes, those applications and pods will go down.


1. Kubernetes Services explained | ClusterIP vs NodePort vs LoadBalancer vs Headless Service
(TechWorld with Nana)
2. Top 8 Docker Best Practices for using Docker in Production
(TechWorld with Nana)
3. Kubectl Basic Commands | Kubernetes for Beginners | Intellipaat
4. Kubernetes Crash Course for Absolute Beginners [NEW]
(TechWorld with Nana)
5. Kubernetes Security Best Practices - Ian Lewis, Google
(CNCF [Cloud Native Computing Foundation])
6. Ultimate Kubernetes Dashboard tool for beginners! Openlens GUI


Top Articles
Latest Posts
Article information

Author: Patricia Veum II

Last Updated: 03/13/2023

Views: 6269

Rating: 4.3 / 5 (64 voted)

Reviews: 87% of readers found this page helpful

Author information

Name: Patricia Veum II

Birthday: 1994-12-16

Address: 2064 Little Summit, Goldieton, MS 97651-0862

Phone: +6873952696715

Job: Principal Officer

Hobby: Rafting, Cabaret, Candle making, Jigsaw puzzles, Inline skating, Magic, Graffiti

Introduction: My name is Patricia Veum II, I am a vast, combative, smiling, famous, inexpensive, zealous, sparkling person who loves writing and wants to share my knowledge and understanding with you.