One context contains a cluster, namespace, and user. According to the current context, the client will use the specified user information and namespace to send requests to the cluster. To set up a context, we will use the kubectl config set-context <CONTEXT_NAME> --user=<CREDENTIAL_NAME> --namespace=<NAMESPACE> --cluster=<CLUSTER_NAME> command to create or update it:
// in localhost cluster, create a context for accessing local cluster's default namespace
$ kubectl config set-context default/local/myself --user=myself@local --namespace=default --cluster=local-cluster
Context "default/local/myself" created.
// furthermore, create another context for remote cluster
$ kubectl config set-context default/remote/myself --user=myself@remote --namespace=default --cluster=remote-cluster
Context "default/remote/myself" created.
Let's check our current kubeconfig. We can find two new contexts:
$ kubectl config view
...
contexts:
- context:
cluster: local-cluster
namespace: default
user: myself@local
name: default/local/myself
- context:
cluster: remote-cluster
namespace: default
user: myself@remote
name: default/remote/myself
...
After creating contexts, we can switch contexts in order to manage different clusters. Here, we will use the kubectl config use-context <CONTEXT_NAME> command:
// check current context
$ kubectl config current-context
kubernetes-admin@kubernetes
// use the new local context instead
$ kubectl config use-context default/local/myself
Switched to context "default/local/myself".
// check resource for the status of context
$ kubectl get pod
NAME READY STATUS RESTARTS AGE
local-nginx-6484bbb57d-xpjp2 1/1 Running 0 2h
local-nginx-6484bbb57d-z4qgp 1/1 Running 0 2h
Yes, it looks fine. How about if we switch to the context with the remote cluster setting:
// switch to the context of remote cluster
$ kubectl config use-context default/remote/myself
Switched to context "default/remote/myself".
// check the pods
$ kubectl get pod
NAME READY STATUS RESTARTS AGE
remote-nginx-5dd7b9cb7d-fxr9m 1/1 Running 0 2h
remote-nginx-5dd7b9cb7d-gj2ft 1/1 Running 0 2h
remote-nginx-5dd7b9cb7d-h7lmj 1/1 Running 0 2h
remote-nginx-5dd7b9cb7d-hz766 1/1 Running 0 2h
All the operations we have done are in the localhost cluster. kubeconfig makes the scenario of working on multiple clusters with multiple users easier.