BLOG02a: Understanding Kubernetes Contexts

When you start working with Kubernetes, one of the first tools you use is kubectl. But did you know that kubectl can talk to multiple clusters, with different users and namespaces—all from one file? This magical piece of configuration is called a context.

In this blog, we’ll break down:

  • What exactly a Kubernetes context is

  • Why it is important

  • How kubectl chooses which cluster you talk to

  • How to create your own contexts

  • How to map contexts to specific clusters, users, and namespaces

This is an essential concept for every DevOps and Kubernetes student.


🔹 What is a Kubernetes Context?

A context in Kubernetes is a shortcut that tells kubectl:

“Which cluster should I connect to?” “Who am I when I connect?” “Which namespace should I work in?”

A context is made of three things:

Part
Meaning

cluster

The Kubernetes API server you talk to

user

The identity (cert/token) you authenticate with

namespace

The default namespace for commands

Think of a context like a profile for using kubectl.


🔹 Where Are Contexts Stored?

In the kubeconfig file:

Run this to see all contexts:

Example output:

The * indicates the current context kubectl is using.


🔹 Why Are Contexts Important?

❗ Prevent mistakes

Imagine running a delete command in production by accident!

If your current context is production… that's a disaster.

Contexts help you separate environments like:

  • development

  • staging

  • production

  • testing


🔹 Check Your Current Context


🔹 How kubectl Uses Context

Every kubectl command automatically uses the current context.

Example:

This gets pods in:

  • the cluster of the current context

  • the namespace of the current context

Unless you override it with:


🔹 Creating a New Context (Step-by-Step)

Let’s create a context manually.

Step 1: Create a cluster entry

This points to an API server.

Step 2: Create a user entry

This defines authentication.

Step 3: Create the context

Combine cluster + user + namespace:

Step 4: Switch to that context


🔹 Create Context Mapping to a Specific Namespace

You can set default namespace:

Now running:

is equal to:


🔹 How to Change Namespace Only (Without Creating New Context)


🔹 How to Rename a Context


🔹 How to Delete a Context


🔹 Real-Life Example (Best Practice for DevOps)

A common setup:

Environment
Context Name
Namespace

Development

dev-context

dev

Staging

stg-context

staging

Production

prod-context

prod

You switch safely:

And double-check:

This prevents mistakes in production.


🔹 Quick Cheat Sheet


🎓 Conclusion

Kubernetes contexts are one of the simplest but most powerful concepts in cluster administration.

They help you:

  • Organize access to multiple clusters

  • Map namespaces to default views

  • Prevent production mistakes

  • Switch environments effortlessly

Every DevOps engineer must understand and use them daily.

Last updated