Simplify infrastructure self-service with Blueprints

→ Register for the webinar

Kubernetes

Kubectl Config Set-Context Command [Tutorial & Examples]

kubernetes set context

Kubectl is the official CLI for interacting with Kubernetes clusters. Because many users work across multiple clusters, the tool supports configuration contexts that store different groups of settings, letting you switch efficiently between them.

A Kubectl context defines a cluster to target, the user to connect as, and the default namespace your Kubectl commands will apply to. Creating a context for each of your clusters means you don’t have to supply these properties each time you change environments, saving time and avoiding errors.

This guide will walk you through setting up and using Kubectl contexts to simplify your Kubernetes management processes. We’ll also provide some tips for troubleshooting context-related problems.

What we will cover:

  1. Why use Kubectl contexts?
  2. What is the kubectl command to set context?
  3. How to use the kubectl set-context command to create a new context?
  4. How to switch between Kubectl contexts with kubectl config use context and current context?
  5. How to modify existing contexts?
  6. How to delete a Kubernetes context?
  7. Tips for troubleshooting context-related issues

Why use Kubectl contexts?

Kubectl contexts group the config options used to set up a connection to a Kubernetes cluster. They’re designed to simplify multi-cluster Kubectl workflows for users who regularly work across several independent cluster environments.

Contexts are useful in any situation where you need to interact with multiple clusters — or as multiple users — using a single Kubectl installation. They allow you to store each cluster’s access parameters as named profiles in a single Kubeconfig file.

You can switch contexts to change the cluster that Kubectl commands like kubectl get pods and kubectl apply will target. Once a cluster has been selected, it remains active until you manually switch to another. You don’t have to include any extra --cluster or –user console flags with your individual commands, as these properties are automatically inherited from the active context.

What is the kubectl command to set context?

The kubectl config set-context command is used to set and update Kubernetes contexts. You specify the name of a new or existing context, then set the following flags to populate the context’s properties:

  • --cluster — The name of the Kubeconfig cluster entry to assign to the context.
  • --user — The name of the Kubeconfig user entry to assign to the context.
  • --namespace — The name of the cluster namespace that will be the default for Kubectl commands when the context is selected.

When you run this command, Kubectl will save the context details into your active Kubeconfig file. You can specify a different file to save the context to by setting the --kubeconfig flag or KUBECONFIG environment variable.

How to use the kubectl set-context command to create a new context?

Let’s walk through how to set up a new Kubectl context.

1. Create a cluster entry

Kubeconfig cluster entries contain the settings required to open a connection to a specific Kubernetes cluster. Once you’ve created a cluster entry, you can reference it in one or more contexts.

Use the set-cluster command to create an entry for your cluster. You will need to set the following flags:

  • --server — The URL of the cluster’s API server
  • --certificate-authority — The path to the cluster’s certificate authority file, used for TLS validation.

You can find more information about these flags and alternative options in the Kubernetes documentation.

$ kubectl config set-cluster minikube \
	--server https://192.168.49.2:8443 \
	--certificate-authority $USER/minikube/ca.crt
Cluster "minikube" set.

The example above shows how to add a cluster entry for a local Minikube cluster deployed in its default configuration. The entry is called minikube — this name will be used later to link the cluster to your context.

2. Create a credentials entry

Next, you need to define the credentials your context will use to access the cluster. Credentials are created using the set-credentials command. The following example uses the client certificate authentication method, but options such as basic authentication and external provider integrations are also supported, depending on how your cluster is configured.

$ kubectl config set-credentials minikube-user \
	--client-certificate $USER/minikube/profiles/minikube/client.crt \
	--client-key $USER/minikube/profiles/minikube/client.key
User "minikube-user" set.

The user credentials are named minikube-user, ready to reference in your context.

3. Create a context

Now you can create a Kubectl context that allows you to connect to your minikube cluster as the minikube-user user.

Use the set-context command, specifying the name of your new context — we’re calling ours minikube — and the cluster and user entries to link:

$ kubectl config set-context minikube \
	--cluster minikube \
	--user minikube-user
Context "minikube" created.

Your minikube context now allows you to connect to the minikube cluster using the details configured earlier. The credentials specified by the minikube-user Kubeconfig entry will be supplied.

Contexts can also optionally specify a default namespace for Kubectl commands. To enable this function, include the --namespace flag when you use set-context:

$ kubectl config set-context minikube \
	--cluster minikube \
	--user minikube-user \
	--namespace development

This means that Kubectl commands will query and apply operations to your cluster’s development namespace, unless you specify a different namespace for each command using the regular --namespace/-n flag.

How to activate and switch between Kubectl contexts?

You can switch between Kubectl contexts with the kubectl config use-context command. This will replace your currently active context with the named context that you specify. Your new selection will be saved to your Kubeconfig file, so it’ll remain active until you repeat the use-context command.

$ kubectl config use-context minikube
Switched to context "minikube".

You can check which context is currently selected by running the current-context command:

$ kubectl config current-context
minikube

The get-contexts command provides a table of all the contexts defined in your Kubeconfig file:

$ kubectl config get-contexts
CURRENT   NAME               CLUSTER            AUTHINFO                 NAMESPACE
          do-lon1-heronweb   do-lon1-heronweb   do-lon1-heronweb-admin   default
*         minikube           minikube           minikube                 default

The active context is highlighted by an asterisk in the first column.

How to modify the existing Kubectl contexts

The existing context can be edited using the set-context command as if you’re creating a new context. You must specify the name of the context to update and then set the --cluster, --user and --namespace flags to update its properties:

$ kubectl config set-context demo --cluster minikube
Context "demo" modified.

The example above will adjust the context called demo, so it now uses the Kubeconfig cluster entry named minikube.

You only need to pass the flags for the context properties you want to change. The changes are applied on top of the context’s existing configuration, so the other values (the user and namespace in this example) will be left intact.

There’s an alternative way to update the currently active context without specifying its name. You can simply set the --current flag when you run the set-context command:

$ kubectl config set-context --current --namespace demo-app

This example changes the currently active context’s default namespace to demo-app.

Renaming Kubectl contexts

The rename-context command provides the option to rename a context. Pass the context’s existing name as the first parameter, then the new name afterward:

Rename the "demo" context to "example"
$ kubectl config rename-context demo example
Context "demo" renamed to "example".

How to delete a Kubernetes context?

The kubectl config delete-context command allows you to remove redundant contexts from your Kubeconfig file:

$ kubectl config delete-context demo-context
deleted context demo-context from /home/james/.kube/config

This won’t affect the Kubeconfig cluster and user entries that the context referenced. To clean those up, too, you must use the separate delete-cluster and delete-user commands:

$ kubectl config delete-cluster demo-cluster
deleted cluster demo-cluster from /home/james/.kube/config
$ kubectl config delete-user demo-user
deleted user demo-user from /home/james/.kube/config

When using these commands, you should be careful not to delete clusters or users that are required by one of your contexts. Kubectl won’t warn you if you accidentally delete actively used entries, but this will break the contexts that use them.

Tips for troubleshooting context-related issues

The use of contexts can sometimes lead to unexpected errors that could be tricky to diagnose. Here are a few common problems and how to troubleshoot them.

“Nocontext exists” error

You might see a no context exists error when trying to select a context:

$ kubectl config use-context demo
error: no context exists with the name: "demo"

This means the named context doesn’t exist in your active Kubeconfig file. You should use the set-context command to create the context first, before you select it, or set the --kubeconfig flag or KUBECONFIG environment variable to the correct kubeconfig path if the context was added to a different file.

“Context was not found” error

Another possible error is a context was not found message when running Kubectl commands. 

For example, when you run the following command, you might get an error below:

$ kubectl get pods
Error in configuration: context was not found for specified context: demo

This occurs when your Kubeconfig file references an invalid context (demo in this case) as the active one. If you run the current-context command, you’ll see that the context it displays doesn’t exist in the list of available contexts reported by the get-contexts command:

$ kubectl config current-context
demo

$ kubectl config get-contexts
CURRENT   NAME               CLUSTER            AUTHINFO                 NAMESPACE
          minikube           minikube           minikube                 default

You can fix this by running the use-context command to switch back to one of the valid contexts listed in the get-contexts command’s output.

Connection to the server refused

Receiving connection to the server <url> was refused messages while running Kubectl commands often indicates a problem with your active context’s configuration. It means the Kubernetes API server is inaccessible, either because it’s offline or an incorrect URL is being used.

If you see this message, then you should first check you’ve selected the context you expected. Use the kubectl config  current-context and use-context commands to confirm which context is active and change it to the correct one if required.

$ kubectl config current-context
demo

$ kubectl config use-context production
Switched to context "production".

This error can also occur when your Kubeconfig file includes incorrect parameters for the cluster entry the context uses. In this case, you should either use the set-cluster command or manually edit your Kubeconfig file to correct the settings for the cluster entry. Kubectl should then be able to connect to the cluster successfully when the context is selected.

Managing Kubernetes with Spacelift

If you need assistance managing your Kubernetes projects, look at Spacelift. It brings with it a GitOps flow, so your Kubernetes Deployments are synced with your Kubernetes Stacks, and pull requests show you a preview of what they’re planning to change. 

To take this one step further, you could add custom policies to reinforce the security and reliability of your configurations and deployments. Spacelift provides different types of policies and workflows that are easily customizable to fit every use case. For instance, you could add plan policies to restrict or warn about security or compliance violations or approval policies to add an approval step during deployments. 

You can try Spacelift for free by creating a trial account or booking a demo with one of our engineers.

Key points

Kubectl contexts are named configurations that set up a connection to a Kubernetes cluster. Creating contexts makes it quicker and easier to switch between your environments in multi-cluster management scenarios, eliminating the need to use multiple Kubeconfig files or repeat --cluster, --user and --namespace flags.

This article showed you how to set up contexts, switch between them, and apply changes. Now, you can use contexts to efficiently handle your multi-cluster access requirements.

Manage Kubernetes Easier and Faster

Spacelift allows you to automate, audit, secure, and continuously deliver your infrastructure. It helps overcome common state management issues and adds several must-have features for infrastructure management.

Learn more

The Practitioner’s Guide to Scaling Infrastructure as Code

Transform your IaC management to scale

securely, efficiently, and productively

into the future.

ebook global banner
Share your data and download the guide