Skip to content

Creating a Context in kubeconfig

How do I create a new context?

In Kubernetes, a context is a logical configuration element within your kubeconfig file that binds together three distinct parameters: a cluster, a user (credentials), and a default namespace. When you create a new context, you are building a shortcut that tells kubectl exactly which API server to communicate with, what identity to assume, and which logical partition (namespace) to target by default.

To create a new context, you use the kubectl config set-context command.

The Operational Workflow: Creating a Context

Because a context is essentially the "glue" between a cluster and a user, both the cluster and the user must exist in your kubeconfig file before the context can be useful. If you are interacting with a completely new environment, you follow a three-step workflow. If your cluster and user are already defined, you can skip directly to Step 3.

Step 1: Define the Cluster

First, inform kubectl about the Kubernetes API server's network location and its certificate authority.

bash
kubectl config set-cluster development \
  --server=https://1.2.3.4 \
  --certificate-authority=fake-ca-file

This creates a cluster entry named development in your configuration.

Step 2: Define the User Credentials

Next, define the identity (user) that will authenticate to this cluster. This identity could be backed by client certificates, bearer tokens, or external identity providers.

bash
kubectl config set-credentials developer \
  --client-certificate=fake-cert-file \
  --client-key=fake-key-file

This creates a user entry named developer.

Step 3: Create the Context (The Binding)

Now, you create the context that links the cluster, the user, and an optional default namespace together.

bash
kubectl config set-context dev-frontend \
  --cluster=development \
  --namespace=frontend \
  --user=developer

This command successfully creates a new context named dev-frontend. Operationally, this context dictates: "Use the developer credentials to access the frontend namespace on the development cluster".

Verifying and Using Your New Context

Once the context is created, you can review your configuration to ensure the binding is correct. To see a list of all contexts defined in your kubeconfig or view the raw configuration, run:

bash
# View all contexts
kubectl config get-contexts

# View the full kubeconfig file output
kubectl config view

To make this newly created context your active working environment, switch to it using:

bash
kubectl config use-context dev-frontend

From this point onward, any declarative or imperative command you run (such as kubectl apply -f app.yaml or kubectl get pods) will automatically route to the development cluster, authenticate as the developer user, and operate exclusively within the frontend namespace.

Based on Kubernetes v1.35 (Timbernetes). Changelog.