Namespaces
A namespace is a virtual cluster inside the cluster: a scope for names. Two teams can each have a Deployment called api as long as they are in different namespaces. Namespaces are also the unit you attach access control (RBAC), quotas and network policies to.
A fresh cluster comes with four:
| Namespace | Contents |
|---|---|
default |
Where objects go if you don't say otherwise |
kube-system |
Cluster components: CoreDNS, kube-proxy, control-plane Pods |
kube-public |
Readable by everyone, rarely used |
kube-node-lease |
Node heartbeat Lease objects |
Working with namespaces
apiVersion: v1
kind: Namespace
metadata:
name: shop-dev
labels:
team: shop
environment: devkubectl create namespace shop-dev # or: kubectl apply -f ns.yaml
kubectl get pods -n shop-dev
kubectl get pods --all-namespaces # short: -A
kubectl config set-context --current --namespace=shop-dev # change your default
kubectl delete namespace shop-dev # deletes EVERYTHING inside itPut metadata.namespace in manifests, or pass -n when applying. If a manifest says namespace: a and you pass -n b, kubectl refuses with an error rather than guessing.
Namespaced vs cluster-scoped
Not every kind lives in a namespace. Nodes, PersistentVolumes, StorageClasses, ClusterRoles and Namespaces themselves are cluster-scoped.
kubectl api-resources --namespaced=true # Pods, Services, Deployments, ConfigMaps, Secrets, ...
kubectl api-resources --namespaced=false # Nodes, PersistentVolumes, Namespaces, ClusterRoles, ...An object's identity is therefore (kind, namespace, name) for namespaced kinds and (kind, name) for cluster-scoped ones. A model of the API's uniqueness check:
CLUSTER_SCOPED = {"Node", "Namespace", "PersistentVolume", "ClusterRole", "StorageClass"}
store = {}
def create(kind, name, namespace="default"):
key = (kind, name) if kind in CLUSTER_SCOPED else (kind, namespace, name)
if key in store:
where = "" if kind in CLUSTER_SCOPED else f" in {namespace}"
return f'Error: {kind.lower()} "{name}" already exists{where}'
store[key] = {"kind": kind, "name": name}
return f"{kind.lower()}/{name} created" + ("" if kind in CLUSTER_SCOPED else f" ({namespace})")
print(create("Deployment", "api", "team-a"))
print(create("Deployment", "api", "team-b"))
print(create("Deployment", "api", "team-a"))
print(create("PersistentVolume", "disk-1", "team-a"))
print(create("PersistentVolume", "disk-1", "team-b"))deployment/api created (team-a)
deployment/api created (team-b)
Error: deployment "api" already exists in team-a
persistentvolume/disk-1 created
Error: persistentvolume "disk-1" already exists
Namespaces and DNS
Each Service gets a DNS name that includes its namespace: <service>.<namespace>.svc.cluster.local. Inside the same namespace the short name api is enough; from another namespace use api.team-a. The DNS lesson covers this in detail.
Note: Namespaces separate names and policies, not networks. By default a Pod in
team-acan reach a Pod inteam-b. Use Network Policies to isolate traffic.
Deleting a namespace
kubectl delete namespace removes every object inside it, and the namespace stays Terminating until all of them (including those with finalizers) are gone. The deletion order is: mark the namespace, delete its contents, then remove the namespace itself. A model with one object that has a finalizer still pending:
namespace = {"name": "shop-dev", "phase": "Active"}
objects = [
{"kind": "Deployment", "name": "api", "finalizers": []},
{"kind": "Service", "name": "api", "finalizers": []},
{"kind": "PersistentVolumeClaim", "name": "data", "finalizers": ["kubernetes.io/pvc-protection"]},
]
def namespace_controller_pass():
namespace["phase"] = "Terminating"
for obj in list(objects):
if obj["finalizers"]:
print(f"waiting for {obj['kind']}/{obj['name']} (finalizers: {obj['finalizers']})")
else:
objects.remove(obj)
print(f"deleted {obj['kind']}/{obj['name']}")
if not objects:
print(f"namespace {namespace['name']} removed")
else:
print(f"namespace {namespace['name']} is {namespace['phase']}")
namespace_controller_pass()
print("-- the PVC protection controller clears its finalizer --")
objects[0]["finalizers"].clear()
namespace_controller_pass()deleted Deployment/api
deleted Service/api
waiting for PersistentVolumeClaim/data (finalizers: ['kubernetes.io/pvc-protection'])
namespace shop-dev is Terminating
-- the PVC protection controller clears its finalizer --
deleted PersistentVolumeClaim/data
namespace shop-dev removed
When to use namespaces
- Per team or per application in a shared cluster (
payments,search). - Per environment for small setups (
shop-dev,shop-staging). For production, separate clusters give stronger isolation. - Don't over-split: namespaces with one object each add friction without benefit.
Test yourself
Which of these is cluster-scoped (not inside a namespace)?
- Pod
- Service
- Node
- ConfigMap
Two Deployments named api exist in namespaces a and b. Is that allowed?
- No, names are cluster-wide
- Yes, names only need to be unique per namespace and kind
- Only if their images differ
- Only in kube-system
Do namespaces block network traffic between Pods by default?
- Yes, always
- No, you need NetworkPolicies for that
- Only for Services
- Only on managed clusters