Delete 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. We do not need to specify any other information, such as namespace or label.
Delete resources by filenames, stdin, resources, and names, or by resources and label selector.
JSON and YAML formats are accepted.
Only one type of the arguments may be specified: filenames, resources, and names, or resources and label selector
Note that the delete command does NOT do resource version checks, so if someone submits an update to a resource right when you submit a delete, their update will be lost along with the rest of the resource.
Syntax
kubectl delete -f <path/to/file>
Example
kubectl delete -f namespace.yaml
Deleting Resources
A manifest file is not required for deleting resources. Instead, the resource can be targeted directly using the kubectl delete command. This method is more effective when targeting a group of resources or for deleting all resources in the cluster or a namespace.
Syntax
kubectl delete <type> <name> [-n <namespace>] | --all | -l <label>]
Dry-Run
Deleting resources can be a risky operation. When using complex matches for deleting resources it is a good practice to perform a dry-run of the deletion. This will allow you to preview exactly what Kubernetes will delete, ensuring you do not accidentally delete something in error.
kubectl delete ns --all --dry-run
Deleting All Resources
Current 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.
kubectl delete --all
Specific Namespace
To delete all resources from a specific namespace us the -n flag.
kubectl delete -n wordpress --all
All Namespaces
To delete all resources from all namespaces we can use the -A flag.
kubectl delete -A
Deleting Resource Types
Deleting Namespaces
Syntax
kubectl delete ns <name>
Example
kubectl delete ns myapp
Deleting Pods
Syntax
kubectl delete pod <name> [-n <namespace>]
Example #1
kubectl delete pod worker-cgxxv
To delete a pod located in a different namespace you must use the -n flag with the namespace's name. Example #2
kubectl delete pod worker-cgxxv -n myapp
Deleting Services
Syntax
kubectl delete svc <name>
Example 1
kibectl delete svc nginx
Example 2
kubectl delete svc nginx -n wordpress
Deleting Deployments
kubectl delete deployment <name>