Kubernetes Namespace ‐ Detailed Explanation - ashwani-cse/next-gen-pizza-backend GitHub Wiki

What is a Namespace in Kubernetes?

Namespace is like a folder inside Kubernetes where you group your resources (like pods, services, deployments) separately.

  • It helps organize and isolate resources.

  • It allows multi-team or multi-project use inside the same Kubernetes cluster.

  • It provides scope for names: pod names, service names can be the same if they are in different namespaces.


Why do we need Namespace?

  • Separation: Different teams or projects can have their own isolated environments.

  • Avoid Name Clashes: Two teams can both have a frontend service without conflict.

  • Resource Control: You can apply resource quotas (like CPU/Memory limits) on a namespace.

  • Security & Access Control: Different users can be given permissions to only their namespace.

  • Better Management: Easier to organize and manage hundreds or thousands of resources.


How Kubernetes treats Namespaces

  • Some resources are namespaced (e.g., Pods, Services, Deployments).

  • Some resources are not namespaced (e.g., Nodes, PersistentVolumes).

Namespaced resources must belong to one namespace.


Example - Creating a Pod in a Namespace

apiVersion: v1
kind: Pod
metadata:
  name: mypod
  namespace: dev
spec:
  containers:
    - name: mycontainer
      image: nginx

In this example, pod mypod will be created inside the dev namespace. If you don't specify a namespace, it will be created inside the default namespace.


Default Namespaces in Kubernetes

Namespace Purpose
default Default namespace for user-created resources.
kube-system Kubernetes system components (e.g., kube-dns, kube-proxy).
kube-public Publicly readable resources (rarely used).
kube-node-lease Used for node heartbeats to improve performance.

Practical Example

Step 1: Create a Namespace

kubectl create namespace test-env

Step 2: Create a Pod YAML

apiVersion: v1
kind: Pod
metadata:
  name: nginx-pod
  namespace: test-env
spec:
  containers:
    - name: nginx
      image: nginx

Step 3: Deploy the Pod

kubectl apply -f nginx-pod.yaml

Step 4: Check Pod in Namespace

kubectl get pods -n test-env

Advanced Usage

  • Network Policies: Restrict network communication between namespaces.

  • Resource Quotas: Limit CPU, memory, storage usage per namespace.

  • Role-Based Access Control (RBAC): Control who can access what in a namespace.

Example ResourceQuota YAML:

apiVersion: v1
kind: ResourceQuota
metadata:
  name: mem-cpu-limit
  namespace: dev
spec:
  hard:
    requests.cpu: "2"
    requests.memory: 4Gi
    limits.cpu: "4"
    limits.memory: 8Gi

In Simple Words

"Namespace is like a virtual boundary inside a Kubernetes cluster, so that teams, apps, and resources don't collide and can live peacefully without fighting for names or resources."

⚠️ **GitHub.com Fallback** ⚠️