Namespace and context are two totally different concepts in Kubernetes. Sometimes, we confuse them or think they are very related.
Namespace is a K8s API object or resource that uses to group and isolate resources in a Kubernetes cluster for different group of users.
On the other hand:
Context is a concept outside of the Kubernetes resources and runtime components! It is a concept in Kubectl client that enables us to work with more than one K8s cluster at a time.
We can consider the context as connection information and the namespace as a group of resources.
One important relation between namespace and context is that each context needs to have a default namespace.
We can set the default namespace for a context with this command:
kubectl config set-context cluster-prod --namespace=bar
To select a namespace on which the kubectl command should run, we need to use the “--namespace” or “-n” parameter, otherwise, the default namespace will be used.
To change the current context, we need to use this command:
kubectl config use-context cluster-test
To create a new namespace using the kubectl imperatively with this command:
kubectl create namespace foo
Or declaratively using a manifest resource file.
apiVersion: v1
kind: Namespace
metadata:
name: foo ## name of the namespace
To create a new context using the kubectl command, we can use the “kubectl config set-context“ command with different options or edit the kubectl config file (the default config file is in this path “~/.kube/config” or set by the “KUBECONFIG” environment variable)
To get the list of all available namespaces, we can use this command:
kubectl get namespaces
To get the list of all available context, we can use this command:
kubectl config get-contexts
You can also support me in buying a latte ☕️ !(one time or monthly):