Kubernetes - Namespaces

Kubernetes Namespaces

Namespace

Namespace is used to group resources for multiple teams and projects. Kubernetes provides isolation between different namespaces.

Kubernetes starts with three initial namespaces:

  • default The default namespace for objects with no other namespace
  • kube-system The namespace for objects created by the Kubernetes system
  • kube-public This namespace is created automatically and is readable by all users (including those not authenticated). This namespace is mostly reserved for cluster usage, in case that some resources should be visible and readable publicly throughout the whole cluster. The public aspect of this namespace is only a convention, not a requirement.

Create a Namespace

namespace-dev.yaml

1
2
3
4
5
6
apiVersion: v1
kind: Namespace
metadata:
name: dev
labels:
name: dev

use kubectl apply to create the namespace

1
2
$ kubectl apply -f namespace-dev.yaml 
namespace/dev created

use kubectl get namespaces command to get all available namespace

1
2
3
4
5
6
7
$ kubectl get namespaces
NAME STATUS AGE
default Active 12d
dev Active 89s
kube-node-lease Active 12d
kube-public Active 12d
kube-system Active 12d

Create Resource in a namespace

myapp.yaml: Example to create a deployment in dev namespace

1
2
3
4
5
6
7
8
9
10
11
12
apiVersion: apps/v1
kind: Deployment
metadata:
name: myapp
namespace: dev
spec:
replicas: 2
selector:
matchLabels:
app: myapp
template:
...

To list the deployname in dev namespace

1
2
3
$ kubectl get deployment -n dev
NAME READY UP-TO-DATE AVAILABLE AGE
myapp 2/2 2 2 37s

If you don’t want to set the namespace in yaml file, you can set the namespace in the kubectl apply command

1
kubectl apply -f myapp -n dev

To list resources for all namespaces, use --all-namespaces option

1
2
3
4
5
# get all deployments
$ kubectl get deployment --all-namespaces

# get all pods
$ kubectl get pods --all-namespaces

Setting Current Namespace

permanently save the namespace for all subsequent kubectl commands in that context.

1
kubectl config set-context --current --namespace=dev

use kubectl config get-contexts to check the current namespace.

1
2
3
$ kubectl config get-contexts
CURRENT NAME CLUSTER AUTHINFO NAMESPACE
* minikube minikube minikube default

Delete a Namespace

1
2
$ kubectl delete namespace dev
namespace "dev" deleted

Resources under namespace dev will be deleted.

kubens

ubens is a utility to quickly switch between Kubernetes namespaces. You can download kubens from https://github.com/ahmetb/kubectx and then add kubens to system PATH.

1
2
3
USAGE:
kubens : list the namespaces
kubens <NAME> : change the active namespace

Reference