Namespaces

Namespaces divide a single cluster into multiple virtual sub clusters.

Creating namespaces

You can create a namespace imperatively or with a manifest:

# imperatively, in the terminal
kubectl create namespace staging

# or in a manifest
apiVersion: v1
kind: Namespace
metadata:
  name: staging

Using a namespace

You can specify them in the terminal like this:

kubectl apply -f deployment.yaml -n staging

You can also use a manifest:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: my-app
  namespace: staging  # add this line

Using a namespace context

Instead of having to specify -n staging on commands, you can set a namespace as the current context

kubectl config set-context --current --namespace=staging

kubectx has a companion tool called kubens that simplify the listing and selection.

Namespace DNS

You can reach services by name within the same namespace.

curl http://simple-nginx-service  

You can reach services in another namespace by using the full DNS name:

curl http://simple-nginx-service.staging.svc.cluster.local

The pattern is <service>.<namespace>.svc.cluster.local.

What namespaces contain

# these are NOT namespaced
Nodes
PersistentVolumes
ClusterRoles
StorageClasses

# these ARE namespaced
Pods
Deployments
Services
ConfigMaps
Secrets

Important: namespaces don’t provice network isolation by default, as seen in the DNS section. For real isolation NetworkPolicies exist.