Kubernetes Namespaces

A Namespace provides a way of organising or categorising resources in a Kubernetes cluster. Every resource you create is associated with a Namespace. When an objects Namespace isn’t specified explicitly, it will be associated with the default Namespace.

Namespaces are a great way of logically grouping or partitioning resources in a cluster. For example multiple teams in a company using the same cluster could partition resources by namespace.

Creating & Viewing Namespaces

To create a Namespace run kubectl create namespace some-namespace as follows. You can then view all Namespaces in the cluster by running kubectl get namespaces.

Creating a Pod with a Custom Namespace

When you create a Kubernetes object you can specify the Namespace as part of the metadata. The Pod definition below uses the demo-namespace created above.

apiVersion: v1
kind: Pod
metadata:
 name: demo-pod
 namespace: demo-namespace
 labels:
  app: demo-app
spec:
 containers:
 - name: demo-app-container
   image: busybox
   command: ['sh', '-c', 'echo hello KCAD & sleep 3600']

If we run kubectl get pods after creating the Pod we’ll see no reference to the object we just created. This is because kubectl get pods will only list resources in the default Namespace.

To see demo-pod you’ll need to specify the target Namespace with -n demo-namespace. The full command is kubectl get pods -n demo-namespace.

You’ll also need to specify the Namespace if you’re describing the Pod, as shown below.

The sample code for this post is available here.