Lesson 22 · Section 2: Core Concepts
Lesson 22: Namespaces: many teams, one cluster
What a namespace really is, what it separates and what it does not, how quotas, limits, RBAC and DNS hang off it, and the kubectl habits that stop you working in the wrong one. · 20 min read · 4 min video
Official competency this lesson covers
Narrated by the local narrator voice. Keys: Space plays and pauses, J and L step, C captions, F full screen.
Why namespaces exist
A cluster is expensive to run and tedious to maintain, so in practice one cluster is shared: several teams, many applications, often a few environments such as dev and staging. A flat, shared cluster runs into three problems quickly:
- Names collide. Two teams both want a Deployment called
weband a Secret calleddb-pass. - Permissions have no edge. You cannot say "team A may change its own objects and nothing else" if there is no such thing as "its own".
- Resources have no budget. One runaway application can take every CPU, and there is nothing to charge it against.
A namespace is the answer to all three: a named scope inside the cluster that object names, permissions and resource budgets are attached to.
What a namespace is
Parts:
- Service web (web.dev.svc), in Namespace dev
- Deployment web (2 replicas), in Namespace dev
- Secret db-pass (dev password), in Namespace dev
- Service web (web.prod.svc), in Namespace prod
- Deployment web (6 replicas), in Namespace prod
- Secret db-pass (prod password), in Namespace prod
- Nodes (run Pods of both), in No namespace
- PersistentVolumes (claimed from any), in No namespace
- ClusterRoles (usable in any), in No namespace
Connections:
- Service web to Deployment web: selects Pods
- Deployment web to Secret db-pass: uses
- Service web to Deployment web: selects Pods
- Deployment web to Secret db-pass: uses
A namespace is itself a small Kubernetes object (kind: Namespace, short name ns). Other objects point to it with
metadata.namespace, and the pair namespace + name must be unique for each kind. That is why web in dev and
web in prod can live side by side.
Not every object lives in a namespace. Anything that describes the cluster itself, or that namespaces themselves depend on, is cluster-scoped:
| Namespaced (most things) | Cluster-scoped (no namespace) |
|---|---|
| Pods, Deployments, ReplicaSets, StatefulSets, DaemonSets, Jobs | Nodes |
| Services, EndpointSlices, Ingresses, NetworkPolicies | Namespaces |
| ConfigMaps, Secrets, ServiceAccounts | PersistentVolumes, StorageClasses |
| PersistentVolumeClaims | ClusterRoles, ClusterRoleBindings |
| Roles, RoleBindings | CustomResourceDefinitions, IngressClasses, PriorityClasses |
| ResourceQuotas, LimitRanges, Events | CertificateSigningRequests |
You never need to memorise the list. The cluster tells you:
kubectl api-resources --namespaced=true # lives in a namespace
kubectl api-resources --namespaced=false # cluster-scoped
Every cluster starts with four namespaces:
| Namespace | What it is for |
|---|---|
default | Where objects go when you name no namespace. Fine for experiments, a poor home for real workloads |
kube-system | The cluster's own components: CoreDNS, kube-proxy, and on kubeadm clusters the control plane's static Pods |
kube-public | Readable by everyone, even unauthenticated clients. kubeadm puts the cluster-info ConfigMap here so joining nodes can find the cluster |
kube-node-lease | One Lease object per node. The kubelet renews it every few seconds as a cheap heartbeat |
Each new namespace is not quite empty. Two controllers fill it in within a second or so: a ServiceAccount called
default, which Pods use when they name no other, and a ConfigMap called kube-root-ca.crt, which holds the
cluster's CA certificate so Pods can verify the API server.
How it works underneath
Parts:
- kubectl -n shop (create a Pod)
- RBAC (Roles in shop)
- API server (namespaces/shop/pods)
- Admission (quota and limits)
- etcd (/registry/pods/shop/)
Connections:
- kubectl -n shop to API server: POST
- API server to RBAC: allowed?
- API server to Admission: within quota?
- API server to etcd: stores
Nothing is "inside" a namespace in a physical sense. Pods from ten namespaces run next to each other on the same node, in the same kernel, on the same Pod network. The namespace is a field on the object and a segment of its address, and four parts of the control plane read it:
- The API path. Namespaced objects are served under
/api/v1/namespaces/shop/pods/web-1(or/apis/apps/v1/namespaces/shop/deployments/web). Cluster-scoped objects have no such segment:/api/v1/nodes/node-1.kubectl -n shopsimply builds the first kind of URL. - Authorization. RBAC sees the namespace in every request. A Role and a RoleBinding live in one namespace and can only grant access there; a ClusterRoleBinding grants in all of them.
- Admission. Before an object is stored, admission plugins apply the namespace's own rules: its ResourceQuotas, its LimitRanges and its Pod Security level.
- Storage. etcd keeps the object under a key that contains the namespace, such as
/registry/pods/shop/web-1. A node is at/registry/minions/node-1, with no namespace in the key.
Under the hood · Why a namespace is not a security boundary on its own
- Network. The Pod network is flat. Without a NetworkPolicy, a Pod in
devcan open a connection to any Pod or Service inprod. - Nodes. The scheduler places Pods from every namespace on the same nodes. A container that escapes to the node can reach its neighbours whatever their namespace.
- Cluster-scoped objects. Anyone who can create PersistentVolumes, ClusterRoles or CustomResourceDefinitions affects every namespace at once.
- Linux namespaces are something else. The kernel's PID, network and mount namespaces isolate the processes of a container. Kubernetes namespaces are an API concept with the same name and no technical relation.
What a namespace does give you is a place to attach the rules that do isolate: RBAC, quotas, NetworkPolicies and Pod Security Admission. Real multi-tenancy is a namespace plus all of those.
Under the hood · What happens when you delete a namespace
kubectl delete namespace shop does not remove the namespace at once. The API server sets a deletion timestamp and
the namespace's phase changes from Active to Terminating. From that moment nothing new can be created in it.
The namespace controller then asks the API server for every namespaced resource type and deletes everything of
each type found in shop. Only when the namespace is empty does it remove the kubernetes entry from the
namespace's spec.finalizers, and the namespace disappears.
That is why a namespace can hang in Terminating: either some object inside has a finalizer of its own that
nobody is removing, or a resource type cannot be listed, typically because an aggregated API (such as metrics-server)
is registered but down. The namespace's status.conditions say which.
The rules that make it a boundary
Parts:
- LimitRange (per container)
- ResourceQuota (total for all)
- Namespace shop (names and scope)
- RoleBinding (who may do what)
- NetworkPolicy (who may connect)
Connections:
- ResourceQuota to Namespace shop: caps
- LimitRange to Namespace shop: defaults
- RoleBinding to Namespace shop: grants
- NetworkPolicy to Namespace shop: filters
Four namespaced objects turn a namespace from a naming scope into a boundary. All of them are created inside the namespace they govern, and none of them affects any other namespace.
| Object | Question it answers | When it is checked |
|---|---|---|
ResourceQuota | How much may the whole namespace use: CPU, memory, storage, object counts? | At admission, when an object is created or updated |
LimitRange | What does one container or Pod get by default, and what is the minimum and maximum? | At admission, when a Pod is created |
Role + RoleBinding | Who may do what to which resources here? | On every API request |
NetworkPolicy | Which Pods may connect to the Pods here, and where may they connect to? | By the CNI plugin, on every connection |
Two more settings live on the Namespace object itself, as labels. pod-security.kubernetes.io/enforce sets the Pod
Security level (privileged, baseline or restricted) for every Pod in the namespace. And the API server labels
each namespace with kubernetes.io/metadata.name: <its name>, which you cannot change, so that a NetworkPolicy's
namespaceSelector can always select a namespace by name.
Names across namespaces
Parts:
- Service db (db.shop.svc), in Namespace shop
- CoreDNS (search shop.svc...)
- frontend Pod (in namespace shop), in Namespace shop
- Service db (db.data.svc), in Namespace data
Connections:
- frontend Pod to CoreDNS: db?
- frontend Pod to Service db: db
- frontend Pod to Service db: db.data
Every Service gets the DNS name <service>.<namespace>.svc.cluster.local. The kubelet writes a search list into
each Pod's /etc/resolv.conf that starts with the Pod's own namespace:
search shop.svc.cluster.local svc.cluster.local cluster.local
nameserver 10.96.0.10
options ndots:5
So in a Pod in shop, the short name db is tried as db.shop.svc.cluster.local first and finds the local
Service. db.data is tried as db.data.svc.cluster.local on the second entry and reaches the Service in namespace
data. This is deliberate: the same manifest, calling plain db, works unchanged in dev, staging and prod.
DNS is the only thing that crosses namespaces this easily. Most references between objects are local by design:
| Reference | Can it cross namespaces? |
|---|---|
| A Pod mounting a ConfigMap, Secret or PersistentVolumeClaim | No. Same namespace only |
A Pod's serviceAccountName | No |
| A Service selecting Pods | No. The selector only sees Pods in the Service's namespace |
| An Ingress pointing at a backend Service | No |
| An owner reference (a ReplicaSet owning Pods) | No |
| A Pod calling a Service by DNS name | Yes: service.namespace |
| A RoleBinding naming a ServiceAccount as its subject | Yes: the subject has its own namespace field |
| A NetworkPolicy allowing traffic from elsewhere | Yes, with a namespaceSelector |
| A Gateway API route pointing at a Service elsewhere | Only if the target namespace allows it with a ReferenceGrant |
Using it
Example · Create a namespace and work inside it
Create the namespace shop, run a Deployment in it, and make it the default for your current context.
kubectl create namespace shop
kubectl -n shop create deployment web --image=nginx:1.29 --replicas=2
kubectl -n shop get pods
kubectl config set-context --current --namespace=shop # from now on, no -n needed
kubectl get pods # the same two Pods
kubectl config view --minify -o jsonpath='{..namespace}' # prints: shop
The default namespace is stored in your kubeconfig, per context. It is a setting of your client, not of the cluster, and switching context brings that context's own default with it.
Example · Write the namespace as a manifest, with labels
When the namespace needs labels, for example a Pod Security level, generate the manifest and add them:
kubectl create namespace shop --dry-run=client -o yaml > shop-ns.yaml
apiVersion: v1
kind: Namespace
metadata:
name: shop
labels:
team: storefront
pod-security.kubernetes.io/enforce: baseline
kubectl apply -f shop-ns.yaml
kubectl label namespace shop env=prod # labels can also be added afterwards
A namespace name must be a DNS label: lowercase letters, digits and dashes, 63 characters at most. Avoid the
kube- prefix, which is reserved for the system.
Example · Give the namespace a budget and sensible defaults
Limit shop to 10 Pods, 2 CPUs of requests and 4 CPUs of limits, and give containers default values so that Pods
without a resources block are still accepted.
kubectl -n shop create quota shop-quota \
--hard=pods=10,requests.cpu=2,requests.memory=4Gi,limits.cpu=4,limits.memory=8Gi
There is no kubectl create limitrange, so this one is a manifest:
apiVersion: v1
kind: LimitRange
metadata:
name: shop-defaults
namespace: shop
spec:
limits:
- type: Container
defaultRequest:
cpu: 100m
memory: 128Mi
default:
cpu: 500m
memory: 256Mi
kubectl apply -f shop-defaults.yaml
kubectl -n shop describe quota shop-quota # Used and Hard, side by side
kubectl -n shop describe limitrange shop-defaults
default is the default limit and defaultRequest the default request. Both rules apply only to Pods created
from now on; Pods that are already running are neither changed nor evicted.
Example · Reach a Service in another namespace
From a throwaway Pod in shop, call the Service db in namespace data:
kubectl -n shop run tmp --rm -it --restart=Never --image=busybox:1.37 -- nslookup db.data
kubectl -n shop run tmp --rm -it --restart=Never --image=busybox:1.37 -- nc -zv db.data 5432
If the name resolves but the connection times out, look for a NetworkPolicy in data: DNS crossing namespaces does
not mean traffic may.
Tricks
Common mistakes
- Working in the wrong namespace. By far the most common way to lose points.
kubectl get podssayingNo resources found in default namespaceis the hint: the message names the namespace it looked in. - A manifest and a flag that disagree. If the file says
namespace: devand you runkubectl apply -n prod, kubectl refuses: "the namespace from the provided object does not match". If the file names no namespace,-n(or your context's default) decides. - Trying to move an object.
metadata.namespacecannot be changed. To "move" something, export it, change the namespace, create it in the new place and delete the old one. - Expecting a Secret or ConfigMap from another namespace. A Pod can only mount what is in its own namespace.
Copy the object:
kubectl -n dev get secret db-pass -o yaml, edit the namespace, apply. - Putting
-non a cluster-scoped object.kubectl -n shop get nodesworks and silently ignores the flag, and anamespace:in a PersistentVolume or ClusterRole manifest means nothing. Do not let it suggest the object is namespaced. - Deleting a namespace to "clean up". It deletes every object inside, including PersistentVolumeClaims and, with
the usual
Deletereclaim policy, the data behind them. There is no undo. - Assuming isolation. Without NetworkPolicies,
devcan talk toprod. Without RBAC, anyone with cluster-wide rights can read the Secrets of both.
Recap
- A namespace is a scope for names, permissions and budgets;
namespace + nameis unique per kind. - Most objects are namespaced; Nodes, PersistentVolumes, StorageClasses, ClusterRoles and Namespaces are not.
kubectl api-resources --namespaced=falselists them. - It becomes a boundary only with ResourceQuota, LimitRange, RBAC and NetworkPolicy attached.
- DNS:
dbis the Service in your own namespace;db.datareaches namespacedata. Mounts and selectors never cross. - In the exam: read the task's namespace, use
-norset-context --current --namespace, and search with-A.
Official docs
Quiz: check what you learned
5 questions on this lesson · about 3 min · instant feedback. Missed questions come back in your review queue.
Sign in to take the quiz and keep your score.
Practise: try it on a real cluster
2 hands-on labs for this lesson. You get goals, not steps: any solution that reaches them passes.
Give a new team its own namespace with a limit on Pods, run their first workload, and point it at a Service in another namespace.
Build · Level 2 · standard · target 15 min
Section capstone. Take over a half-finished namespace: get its Deployment running under a Pod limit, repair its Service, open it on a node port, add a Pod that calls another namespace, and write it all down as a manifest.
Fix · Level 3 · challenge · target 30 min
Discussion
Learners ask and answer questions here. Sign in to read and join the discussion.