# Namespaces in Kubernetes

In 
Published 2022-12-03

This tutorial explains what is and how we can use a namespace in Kubernetes.

You can think of a Namespace as a virtual cluster inside your Kubernetes cluster. You can have multiple namespaces inside a single Kubernetes cluster, and they are all logically isolated from each other.

The namespaces are helpful when different teams or projects share a Kubernetes cluster. Any number of namespaces are supported within a cluster, each logically separated from others but with the ability to communicate with each other.

The namespaces can be created in 2 ways:

  • using imperative approach (kubectl create command)
  • using declarative approach (kubectl apply command)

Using imperative approach, we can run a command like this:

kubectl create namespace my-namespace-1

Using declarative approach, we need to create a yaml file ("my-first-namespace.yaml") as below :

my-first-namespace.yaml
apiVersion: v1
kind: Namespace
metadata:
  name: my-namespace-2
  labels:
    environment: dev
    project: data-moving

and after that we need to run the following command in order to have the namespaces created:

kubectl apply -f my-first-namespace.yaml

If we want to see all the namespaces created so far, we can run the following command:

kubectl get namespaces --show-labels

or

kubectl get ns --show-labels

The result could be like this:

NAME              STATUS   AGE   LABELS
default           Active   14h   kubernetes.io/metadata.name=default
kube-node-lease   Active   14h   kubernetes.io/metadata.name=kube-node-lease
kube-public       Active   14h   kubernetes.io/metadata.name=kube-public
kube-system       Active   14h   kubernetes.io/metadata.name=kube-system
my-namespace-1    Active   18m   kubernetes.io/metadata.name=my-namespace-1
my-namespace-2    Active   9s    environment=dev,kubernetes.io/metadata.name=my-namespace-2,project=data-moving

We can obtain more information on a particular namespace using the following command:

kubectl describe ns my-namespace-1

The result could be like this:

Name:         my-namespace-1
Labels:       kubernetes.io/metadata.name=my-namespace-1
Annotations:  <none>
Status:       Active

No resource quota.

No LimitRange resource.

A namespace can be deleted using the following command:

kubectl delete namespace my-namespace-2