Browse topics

Namespaces

Version
1.37
Review
Draft

Summary#

A namespace scopes object names, so two namespaces can each hold an object with the same name. It is also a common boundary for access rules and quotas. Nodes, PersistentVolumes and namespaces themselves are cluster-scoped.

Syntax#

sh
kubectl create namespace NAME
kubectl get pods --namespace NAME
kubectl get pods --all-namespaces
kubectl config set-context --current --namespace=NAME
kubectl api-resources --namespaced=false

Example#

sh
(
  set -eu
  blue="ref-ns-blue-$$"
  green="ref-ns-green-$$"
  kubectl create namespace "$blue" >/dev/null
  trap 'kubectl delete namespace "$blue" >/dev/null' EXIT
  kubectl create namespace "$green" >/dev/null
  trap 'kubectl delete namespace "$blue" "$green" >/dev/null' EXIT

  kubectl create configmap -n "$blue" settings --from-literal=color=blue
  kubectl create configmap -n "$green" settings --from-literal=color=green
  for namespace in "$blue" "$green"; do
    kubectl get configmap -n "$namespace" settings -o jsonpath='color={.data.color}{"\n"}'
  done

  label=$(kubectl get namespace "$blue" -o jsonpath='{.metadata.labels.kubernetes\.io/metadata\.name}')
  [ "$label" = "$blue" ] && echo "metadata.name label matches"
  kubectl api-resources --namespaced=false --api-group='' -o name |
    grep -E '^(namespaces|nodes|persistentvolumes)$' | sort
)

Expected output#

Text
configmap/settings created
configmap/settings created
color=blue
color=green
metadata.name label matches
namespaces
nodes
persistentvolumes

Common mistakes#

A namespace by itself does not block network traffic between Pods. Isolation needs NetworkPolicy objects and a network plugin that enforces them. Also check the target before deleting a namespace: deletion removes the namespaced objects inside it.

kubectl config set-context --current --namespace=NAME saves the default in kubeconfig. Use -n NAME for a single command.

Version applicability#

The example targets Kubernetes 1.37. The automatic, immutable kubernetes.io/metadata.name label on namespaces is stable since 1.22. Names beginning with kube- are reserved for the system.

Sources#

Attribution
DevLookup contributors
License
CC-BY-4.0