Understanding Kubernetes Namespaces

Kubernetes namespaces are a way of organizing and isolating resources within a cluster. They can be useful for dividing a cluster into logical units, such as different environments (dev, test, prod), teams (frontend, backend, data), or projects (app1, app2, app3).

In this blog post, we will cover the following topics:

  • Listing namespaces
  • Creating and using a namespace
  • Deleting a namespace

Listing Namespaces

To list the existing namespaces in a cluster, you can use the kubectl command with the get option and the namespace resource type:

kubectl get namespaces

This will display the name and status of each namespace. By default, Kubernetes creates three namespaces:

  • default: The default namespace for objects that do not belong to any other namespace.
  • kube-system: The namespace for objects created by the Kubernetes system.
  • kube-public: The namespace for objects that are publicly accessible to all users.

You can also use the kubectl describe command to get more details about a specific namespace:

kubectl describe namespace default

This will show the name, labels, annotations, and events of the default namespace.

Creating and Using a Namespace

To create a new namespace, you can use the kubectl create command with the namespace resource type and the name of the namespace:

kubectl create namespace my-namespace

This will create a new namespace called my-namespace. You can verify that it exists by listing the namespaces again:

kubectl get namespaces

To use a namespace for creating or accessing objects, you can use the –namespace or -n flag with any kubectl command:

kubectl create pod my-pod –namespace my-namespace
kubectl get pod my-pod –namespace my-namespace

Alternatively, you can set the default namespace for your current context using the kubectl config command:

kubectl config set-context –current –namespace my-namespace

This will make all subsequent kubectl commands use the my-namespace namespace by default, unless you specify a different one with the –namespace flag.

Deleting a Namespace

To delete a namespace, you can use the kubectl delete command with the namespace resource type and the name of the namespace:

kubectl delete namespace my-namespace

This will delete the my-namespace namespace and all the objects in it. You can verify that it is gone by listing the namespaces again:

kubectl get namespaces