Mastering kubectl Context in Kubernetes

Understanding the concept of context and how to use it with kubectl

Ok lets start from the begining, to understand what is context what we need to understand is that many softwares to connect to the kubernetes api they use a configuration file that holds three main pieces of information:

This configuration file is often located at ~.kube/config and it looks like this:

apiVersion: v1
kind: Config
clusters:
- name: dev-cluster
  cluster:
    server: https://dev.k8s.example.com
    certificate-authority: /path/to/ca.crt

users:
- name: dev-user
  user:
    client-certificate: /path/to/dev.crt
    client-key: /path/to/dev.key

contexts:
- name: dev-context
  context:
    cluster: dev-cluster
    user: dev-user
    namespace: development

current-context: dev-context

Why we dont put all the cluster conection in the same section, For one really good reason, decoupling this sections give us the posibility to combine them without reapinting or duplicating configuration. Often we can config several contexts that connect to the same cluster but with diferent user or name spaces config. A configuration file often host many clusters,user and context. This is great because it let us switch clusters really easy just by saying what context we wan to use.

For this post we are going to use kubectl to manage context.

Here are some esential KubeCtl Commands
1. List all available contexts
kubectl config get-contexts

Lists all contexts in your kubeconfig. The current context is marked with *.

2. View the current context
kubectl config current-context

Displays the name of the active context.

3. Switch to a different context
kubectl config use-context <context-name>

Changes the active context to the one specified.

4. Set the default namespace for the current context
kubectl config set-context --current --namespace=<namespace>

Sets a default namespace for your active context. This helps avoid needing --namespace in every command.

5. Creating or Modifying a Context

You can create or update a context like this:

kubectl config set-context <context-name> \
--cluster=<cluster-name> \
--user=<user-name> \
 --namespace=<namespace>

Use this to script environment setups or define custom workflows.

6. Things to Remember:

Use clear and descriptive names: e.g., dev-cluster, prod-eks, test-gke

Install tools like kubectx for quick switching

Always double-check your current context before running critical commands

Back up your kubeconfig file, especially when working with production