
Do you have a namespace in your Kubernetes cluster stuck in “Terminating” state? When a namespace is stuck in this state it usually means Kubernetes is not successful in cleaning up resources in that namespace. The main reason is finalizers or resources are not properly cleaned up or stuck. See example below:
$ kubectl get ns
NAME STATUS AGE
calico-apiserver Active 4d13h
calico-system Active 4d13h
default Active 4d13h
kube-node-lease Active 4d13h
kube-public Active 4d13h
kube-system Active 4d13h
longhorn-system Terminating 18m
tigera-operator Active 4d13h
I can confirm the pods and other resources are deleted but the state remains “Terminating“. Let’s consider few ways we can force delete his namespace in Kubernetes.
Set the stuck namespace name in NS variable.
NS=longhorn-system
Before forcing the deletion of the namespace, check for any pending resources that may be causing issues:
kubectl get all --namespace=$NS
1. Unset finalizers manually
If a namespace have finalizers not being properly removed, it can be stuck in “terminating” state. You can edit the namespace object yaml file:
kubectl edit namespace $NS
In the editor, locate finalizers
field and delete by setting as below:
finalizers: []
2. Force Delete Using kubectl
If the first option is not successful, you can force namespace deletion by patching it.
Force deletion of the stuck namespace in kubernetes.
kubectl get $NS -o json | jq '.spec.finalizers=[]' | kubectl replace --raw "/api/v1/ $NS/longhorn-system/finalize" -f -
Note: jq
should be installed to enable you to modify JSON output. Be informed that this method bypasses the finalizers.
3. Forcefully delete the namespace
The--grace-period=0
and --force
flags can be used to force namespace delete in Kubernetes. However, this method might leave orphaned resources and it should be used with caution:
kubectl delete namespace $NS --grace-period=0 --force
You can confirm if the namespace has been deleted by running the command:
kubectl get $NS
The output below shows it doesn’t exist:
error: the server doesn't have a resource type "longhorn-system"