Introduction
Kubernetes is a powerful container orchestration platform, and as clusters grow in size and complexity, it becomes essential to logically separate resources for different teams, environments, or applications. This is where Namespaces in Kubernetes come into play.
Namespaces provide a mechanism for isolating groups of resources within a single Kubernetes cluster.
What is a Namespace?
A namespace is a way to divide cluster resources between multiple users or teams. It allows you to create multiple virtual clusters within the same physical Kubernetes cluster.
Each namespace is a logical partition and can have its own set of:
- Pods
- Services
- Deployments
- ConfigMaps, Secrets
- Resource quotas and limits
Why Use Namespaces?
Namespaces are useful when:
- You have multiple teams sharing the same cluster
- You want to avoid resource conflicts (e.g., two apps using the same service name)
- You need to apply resource constraints and access controls
- You want to separate different environments (e.g., dev, staging, production)
Default Namespaces in Kubernetes
Kubernetes includes the following namespaces by default:
Namespace | Description |
default | Used when no other namespace is specified. |
kube-system | Contains resources created by the Kubernetes system (like kube-dns). |
kube-public | Mostly reserved for cluster-wide public resources. Visible to all users. |
kube-node-lease | Stores node heartbeats for determining node availability. |
Creating a Namespace
You can create a namespace using a YAML file or the kubectl
command line.
Using kubectl:
kubectl create namespace dev
Using YAML:
apiVersion: v1 kind: Namespace metadata: name: dev
Apply the file:
kubectl apply -f namespace.yaml
Using a Namespace
To deploy a resource in a specific namespace, specify the namespace in your YAML or use the --namespace
flag.
Example:
kubectl create deployment nginx --image=nginx --namespace=dev
Or in YAML:
apiVersion: apps/v1 kind: Deployment metadata: name: nginx namespace: dev spec: replicas: 2 selector: matchLabels: app: nginx template: metadata: labels: app: nginx spec: containers: - name: nginx image: nginx
Viewing and Switching Namespaces
List all namespaces:
kubectl get namespaces
Get resources in a namespace:
kubectl get pods --namespace=dev
Set default namespace using context:
kubectl config set-context --current --namespace=dev
Resource Quotas and Limits in Namespaces
Namespaces support resource limits to prevent one team from consuming all cluster resources.
ResourceQuota Example:
apiVersion: v1 kind: ResourceQuota metadata: name: dev-quota namespace: dev spec: hard: pods: "10" requests.cpu: "4" requests.memory: "4Gi" limits.cpu: "10" limits.memory: "10Gi"
Apply the quota:
kubectl apply -f quota.yaml
Deleting a Namespace
Warning: Deleting a namespace deletes all resources in it.
kubectl delete namespace dev