kubectl contexts and namespaces

Understand kubeconfig structure, switch safely between clusters, and scope kubectl commands with namespaces.

Why Contexts and Namespaces Matter

One of the easiest ways to make a costly mistake is to run a command against the wrong cluster or namespace. Contexts and namespaces are your safety rails.

kubeconfig Structure

A kubeconfig file usually has three core sections:

SectionMeaning
clustersAPI Server endpoints and certificate data
usersCredentials or auth methods
contextsNamed combinations of cluster + user + namespace

List Contexts

kubectl config get-contexts

Switch Contexts

kubectl config use-context dev-cluster
kubectl config use-context prod-cluster

Always double-check before running write operations in production.

Use a Namespace with a Command

kubectl get pods -n kube-system
kubectl get services -n default

Set a Default Namespace in the Current Context

kubectl config set-context --current --namespace=dev

After that, kubectl commands use dev unless you override with -n.

Why This Helps

Think of a context like the combination of office building, badge, and floor. It tells you where you are going, who you are, and which area you work in by default.

kubens Tool Mention

Many engineers use kubens from the kubectx toolset to switch namespaces quickly. It is not required, but it can make frequent namespace changes easier.

Safe Habits

  • Run kubectl config get-contexts before important changes.
  • Keep production contexts clearly named.
  • Use -n explicitly when you want to be extra careful.
  • Avoid assuming the default namespace is always correct.
Exercise

Context Definition

What does a Kubernetes context usually combine?

Exercise

Current Namespace

What does `kubectl config set-context --current --namespace=dev` do?

Continue Learning

Explore Related Topics

Try the Tool

Related Resources