Kubernetes Tutorial · Kubernetes Basics · Lesson 5 of 26

Namespaces, Labels and Selectors

Organise resources with namespaces, and connect them with labels and selectors.

Create a free account to save this page, take notes and track your progress. Sign in

Namespaces

Namespaces divide a cluster into named scopes for teams or environments: names must be unique within a namespace, and RBAC, resource quotas and network policies can apply per namespace. They are not a hard security boundary on their own.

Labels and selectors

Labels are key-value pairs on any object (app: web, tier: backend, env: prod). Selectors find objects by label, and that is how Kubernetes wires things together: a Deployment manages pods matching its selector, a Service sends traffic to pods matching its selector.

kubectl get pods -l app=web,env=prod
kubectl get pods -l 'tier in (frontend, backend)'

Use the recommended labels (app.kubernetes.io/name, .../version, .../part-of) so tools understand your objects.

Select pods by label
kubectl create namespace demo-labels > /dev/null
trap 'kubectl delete namespace demo-labels --wait=false > /dev/null' EXIT
for p in api-1:backend api-2:backend web-1:frontend; do
  kubectl -n demo-labels run "${p%%:*}" --image=busybox:1.37 --labels="tier=${p##*:},env=prod" -- sleep 3600 > /dev/null
done
echo "backend pods:  $(kubectl -n demo-labels get pods -l tier=backend -o name | sort | tr '\n' ' ')"
echo "frontend pods: $(kubectl -n demo-labels get pods -l tier=frontend -o name | tr '\n' ' ')"
kubectl -n demo-labels label pod web-1 env=staging --overwrite > /dev/null
echo "env=prod now:  $(kubectl -n demo-labels get pods -l env=prod -o name | sort | tr '\n' ' ')"

Output

backend pods:  pod/api-1 pod/api-2 
frontend pods: pod/web-1 
env=prod now:  pod/api-1 pod/api-2 

Run this on your computer — see “Get Started” for setup.

Test yourself

How does a Service know which pods to send traffic to?

  1. By pod name
  2. Its label selector matches the pods' labels
  3. By namespace only
  4. Through DNS records the pods create
Show answer

Answer: Its label selector matches the pods' labels

Labels and selectors connect Services, Deployments and pods.

Was this page helpful?