>_
EngineeringNotes
Back to Kubernetes

Namespace & Practical

What is a Namespace?

In Kubernetes, namespaces provide a mechanism for isolating groups of resources within a single cluster. You can think of a namespace as a virtual cluster built on top of the same physical cluster.

Namespaces are intended for use in environments with many users spread across multiple teams, or projects. Resources like Pods, Services, and Deployments are created within a specific namespace. If no namespace is specified, they are placed in the default namespace.

Why use Namespaces?

Namespaces are important to use because they help solve several problems:

  1. If we do kubectl get pods then all pods will come up, but if you are a backend developer then other than backend pods all pods are irrelevant to you.
  2. For security purposes, you can configure RBAC (Role-Based Access Control) to allow a backend developer to access ONLY backend pods.

Creating a new namespace

  • Create a new namespace
    Terminal
    bash
    kubectl create namespace backend-team
  • Get all the namespaces
    Terminal
    bash
    kubectl get namespaces
  • Get all pods in the namespace
    Terminal
    bash
    kubectl get pods -n my-namespace
  • Create the manifest for a deployment in the namespace
    yaml
    yaml
    apiVersion: apps/v1
    kind: Deployment
    metadata:
      name: nginx-deployment
      namespace: backend-team
    spec:
      replicas: 3
      selector:
        matchLabels:
          app: nginx
      template:
        metadata:
          labels:
            app: nginx
        spec:
          containers:
          - name: nginx
            image: nginx:latest
            ports:
            - containerPort: 80
  • Apply the manifest
    Terminal
    bash
    kubectl apply -f deployment-ns.yml
  • Get the deployments in the namespace
    Terminal
    bash
    kubectl get deployment -n backend-team
  • Get the pods in the namespace
    Terminal
    bash
    kubectl get pods -n backend-team
  • Set the default context to be the namespace
    Terminal
    bash
    kubectl config set-context --current --namespace=backend-team
  • Try seeing the pods now
    Terminal
    bash
    kubectl get pods
  • Revert back the kubectl config
    Terminal
    bash
    kubectl config set-context --current --namespace=default