How to Use Namespaces in Kubernetes

03.15.2022

Intro

Namespaces allow you to section off parts of your Kubernetes cluster and resources. This prevents name collisions and incorrect usage. For example, you may have many pods named redis and deploy a number of pod to use redis. Without using namespaces, your pods may use the same redis and share data. In this article, we will learn how to use namespaces in Kubernetes.

The Quick Answer

If you are here for the quick answer, here it is. Otherwise, continue to Getting Started.

Save the following to a file namespace.yaml

apiVersion: v1
kind: Namespace
metadata:
  name: my-app-1

Then use the following command.

kubectl create -f ./namespace.yaml

Getting Setup

We will be working with minikube for most tutorials. This creates a local kubernetes cluster that you can develop on.

Feel free to use another kubernetes cluster for these tutorials as well. There will be articles underneath our kubernetes tags on how to run clusters on multiple providers such as AWS, Google Cloud, and Azure.

Once you have minikube installed, start the cluster using the following command.

minikube start

Creating our Namespace

To create a namespace, we will first need a yaml file to store our job information. Create a new file

touch namespace.yaml

Now, let's add the following lines

apiVersion: v1
kind: Namespace
metadata:
   name: my-namespace

The file creates a Namespace resource by specifying the kind on the kind property. We also name the namespace using the metadata.name property.

Now, we can use the following command to create a namespace

kubectl create -f ./namespace.yaml

If we want to get our namespace we can use the following:

kubectl get namespace

or we can get the namespace directly

kubectl get namespace my-namespace

Let's create a redis service using our namespace. Create a new file called redis-deployment.yaml and add the following.

apiVersion: apps/v1
kind: Deployment
metadata:
  name: redis-leader
  namespace: my-namespace
spec:
  replicas: 1
  selector:
    matchLabels:
      app: redis
  template:
    metadata:
      labels:
        app: redis
        role: leader
        tier: backend
    spec:
      containers:
      - name: leader
        image: "docker.io/redis:6.0.5"
        resources:
          requests:
            cpu: 100m
            memory: 100Mi
        ports:
        - containerPort: 6379

Now create the redis deployment using the following:

kubectl apply -f redis-deployment.yaml

We can now get our deployments filtered by the namespace.

kubectl get deployments --namespace=my-namespace

NAME READY UP-TO-DATE AVAILABLE AGE redis-leader 1/1 1 1 24s

Cleanup

Let's clean up our resources now that we are done.

$ kubectl delete deployment redis-leader --namespace=my-namespace
$ kubectl delete namespace my-namespace