Introducing Autopilot, an AI coding assistant
gradient
Using kubectl delete

Using kubectl delete

Jun 16, 2022
7 min read

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

One of the commands associated with this tool is the kubectl delete command. This command allows you to terminate running resources gracefully.  Some of the use cases for the kubectl delete command include the termination of running pods, deployments, services, StatefulSets, and many other resources.

In this guide, you'll learn how to appropriately use kubectl delete to stop resources, and about the various parameters that this command offers. You’ll learn some best practices to guide you in the safe and correct use of this command.

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. The graceful termination of resources using the kubectl delete command is to be done with utmost discretion, because once the command has been run, there's no way to undo the deletion of the resource.

Kubernetes doesn't provide users with the ability to simply pause and resume resources. There are several ways to get around this limitation, one of which is to simply stop (delete) the desired resource to pause, and reapply the resource definition to the cluster to resume.

The kubectl delete command is especially handy during clean up after the deployment of an application. During development, the creation and deployment of resources is a top concern, but the management of these resources sometimes falls to the wayside after deployment.

Some of these resource-management responsibilities involve deleting unused pods. These pods, while running and unused in the Kubernetes cluster, take up some of the node's resources, thereby limiting other, more important, running pods.

In some cases, a Kubernetes node needs to be shut down, and the Kubernetes deployments and services will need to be terminated. Another resource-management concern could be the deletion of StatefulSets that manage pods that rely on durable storage configurations, such as persistent volumes.

Using kubectl delete

Before you begin with this tutorial, you need to have an understanding of the following Kubernetes concepts:

To get started with using kubectl delete, you need to have a single-node Kubernetes cluster running with at least 4 GB of RAM available. You can create one locally with lightweight Kubernetes distributions, such as minikube, K3s, or MicroK8s, or you can provision one with a cloud provider such as Google Kubernetes Engine (GKE), Azure Kubernetes Service, or Amazon Elastic Kubernetes Service (EKS).

Kubectl delete basic use case

With your cluster set up, you can now begin with a basic use case of the kubectl delete command.

Deploy a sample NGINX deployment by creating a file named deployment.yaml, then adding the following code snippet:

yaml

You then run the configurations on your Kubernetes cluster with the kubectl apply command:

bash

The command above will create an NGINX deployment with a ReplicaSet and three NGINX pods deployed and running in the default namespace in your Kubernetes cluster. To verify this, you can simply perform the kubectl get pod command, and you'll get the following response:

NAMEREADYSTATUSRESTARTSAGE
nginx-deployment-9456bbbf9-grdtc1/1Running04m24s
nginx-deployment-9456bbbf9-dd5g21/1Running04m24s
nginx-deployment-9456bbbf9-4nzn21/1Running04m24s

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. In order to prevent this from happening, you need to delete the deployment configuration using either the filename, deployment.yaml, or the deployment name, nginx-deployment, as configured in the metadata section in the YAML code snippet above.

The NGINX Deployment can be deleted in two ways:

bash

Once the deployment resource has been deleted, you shouldn't be able to see any pods, deployments, or ReplicaSets in the default namespace. You'll see only a single Kubernetes service active when you perform the kubectl get services command:

bash

This will display the available services in the default namespace:

NAMETYPECLUSTER-IPEXTERNAL-IPPORT(S)AGE
service/kubernetesClusterIP10.43.0.1<none>443/TCP45h

Please note that depending on the type of Kubernetes distribution you are running, the output shown above may differ slightly.

Kubectl delete advanced use case

In the previous section, you created a simple NGINX deployment, then deleted it properly. In this section, you’ll look at a more advanced use case for the kubectl delete command, and see the steps involved in applying the command.

In this example, you’ll deploy the popular WordPress CMS. To do this, you’ll create the WordPress service, the wp-pv-claim PersistentVolumeClaim, and deploy the Wordpress app using the latest Docker Hub image.

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

yaml

Apply the above configuration to your cluster by running the kubectl apply command:

bash

You’ll see output similar to the following:

bash

Verify that the changes were executed correctly using the kubectl get all command:

bash

You should get output similar to this:

shell

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

As before, trying to delete the pods is futile, since the deployment specification will recreate them as many times as necessary. Fortunately, you only have to use one command to remove the newly created deployment, service, and PVC:

shell

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

bash

The output should be similar to the following:

NAMETYPECLUSTER-IPEXTERNAL-IPPORT(S)AGE
kubernetesClusterIP10.43.0.1<none>443/TCP9d

No resources found in default namespace.

Another way to check that there are no remaining traces of WordPress is to use the kubectl get all command again:

$ kubectl get all

NAMETYPECLUSTER-IPEXTERNAL-IPPORT(S)AGE
service/kubernetesClusterIP10.43.0.1<none>443/TCP9d

As you can see, the kubectl delete command is suitable for both simple and more advanced use cases.

However, note that this was possible because a single YAML file was used to configure all the moving parts. This may or may not be a good idea, as you could mistakenly delete even data stored on a persistent volume. This leads us to the next section, best practices.

Best practices

A single misused kubectl delete command can destroy a whole application and render it useless. There are no safety measures, such as prompts to ask if you truly want to delete the resource or not, attached to the command. Before you perform an operation with the kubectl delete command, you need to know exactly what you want to delete and how you want it deleted.

You can use the kubectl delete --help command to view a list of flags and options that can be applied.

Know when and how to use kubectl delete

Understanding when to delete Kubernetes resources requires that you know your application’s tolerance for the unavailability of one or more of the resources. If one of the resources is taken down, your application should still be able to function.

Similarly, knowing how to delete resources is essential to keeping your services and applications running. For instance, deleting resources with the --force flag set to true should be avoided, as this may result in resource inconsistency, leading to application runtime failure or data loss. Unless you're very certain that doing this won't create problems for your application, this should be used only as a last resort.

Don’t use kubectl delete unless absolutely needed

It is strongly advised that you use the kubectl delete command sparingly, unless during important operations such as clean-up operations for resource optimization once all deployments are done with.

It's also advisable to hold off on deleting PersistentVolumeClaims until all necessary data is retrieved or copied, using the kubectl cp command from the mountPath on to your host machine.

Final thoughts

In this article, you learned about the kubectl delete command: what it is, the different use cases for it, and the recommended ways to use it. The kubectl delete command can be a great help when it comes to managing resources, but it's important to note that while it can prevent bottlenecks in your application, kubectl delete can also break your application entirely if used carelessly.

Kubernetes deployments are best paired with a monitoring solution, such as Airplane, that allows you to keep an eye on your resources, analyze the logs, and trace potential problems, keeping you informed about your cluster's health and enabling you to better manage your resources.

Airplane is the developer platform for building custom internal tools. With Airplane, you can build powerful UIs and workflows that can help you monitor your resources and trace potential issues in your applications. Airplane also offers robust audit logging and job scheduling features out-of-the-box that can help you track historical runs and automate your most critical operations. With a tool like Airplane, monitoring your cluster's health is simple and can enable you to manage your resources efficiently.

To test it out and start monitoring your cluster's health, sign up for a free account or book a demo.

Share this article:
Joseph Eshiett
Joseph is a DevOps practitioner who is fascinated by cloud technologies, software development, and deployment processes. Currently, he works as a DevOps Engineer for Sabino LLC.

Subscribe to new blog posts from Airplane.