K8s - Namespace

Namespace basically is grouping resource in cluster. Namespace-based scoping is applicable only for namespaced objects (e.g. Deployments, Services, etc) and not for cluster-wide objects (e.g. StorageClass, Nodes, PersistentVolumes, etc).

Resources can communicate each other even on different namespace. To create a namespace can be done with the following yaml.

Creating namespace

apiVersion: v1
kind: Namespace
metadata:
  name: billing
# viewing namespaces
kubectl get namespace
kubectl get ns

Creating Pod inside a namespace

To create a Pod (example nginx.yaml) inside a namespace:

kubectl apply -f nginx.yaml --namespace billing

We can also add namespace information in the nginx.yam

apiVersion: v1
kind: Pod
metadata:
  name: nginx
  namespace: billing
  labels:
    name: nginx
spec:
  containers:
  - name: nginx
    image: nginx
kubectl get all --namespace=billing

Deleting namespace

# delete namespace
kubectl delete namespace {NAME_OF_NAMESPACE}
kubectl delete ns {NAME_OF_NAMESPACE}

Deleting a namespace will delete all the resource inside it.