Skip to content

Organizing Pods and other Resources using Namespaces and Labels

Namespaces and Labels

Organizing objects into Namespaces

Namespaces in Kubernetes help organize Kubernetes API objects into non-overlapping groups.

Namespaces divide a single physical kubernetes cluster into many virtual clusters.

Listing namespaces and the objects they obtain.

kubectl get namespaces

or 

kubectl get ns

Namespaces prefixed with kube- are reserved for kubernetes system namespaces.

Listing objects in a specific namespace

kubectl get pods --namespace kube-system

Listing objects across all namespaces

kubectl get pods --all-namespaces

Creating namespaces

kubectl create namespace backend

Creating a namespace from a manifest file.

apiVersion: v1
Kind: Namespace
metadata:
    name: backend

To execute the manifest file :

kubectl apply -f filename.yaml

To get all namespaces :

kubectl get ns # to list all namespaces

Creating objects in a specific namespace

kubectl apply -f filename.yaml -n backend

Making Kubectl default to a different namespace

To switch to a different namespace, you must update the current context.

kubectl config set-context --current --namespace backend

Organizing Pods with Labels

A canary release is a deployment pattern where you deploy a new version of an application alongside the stable version, and direct only a small portion of requests to the new version to see how it behaves before rolling it out to all users. This prevents a bad release from being made available to too many users.

Introducing Labels

-Labels are used to organize kubernetes api objects.

  • A label is a key value pair you attach to an object that allows any user of the cluster to identify the object's role in the system.

  • Both the key and value are simple strings that you can specify as you wish.

  • An object can have more than one label, but the label keys must be unique within that object.

Using labels to provide additional information about an object.

We can use labels to distinguish between the type of the release.

To help indentify the application and the release running in each pod, we use pod labels.

Kubernetes does not care what labels you add to your objects. You can choose the keys and value however you want.

Adding Labels to Pods

Creating a namespace :

kubectl create namespace kiada

Configuring kubernetes to use the new namespace :

kubectl config set-context --current --namespace kiada

Defining labels in Object Manifest

apiVersion: v1
kind: Pod
metadata: 
    name: app-1
    labels:
        app: api
        rel: stable

spec:
    ...

Labels are supported by all object kinds. You specify them in the metadata.labels map.

Displaying pods with label names :

kubectl get pods --show-labels

Deleting objects using a label selector

kubectl delete pods -l rel=canary