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:
| Section | Meaning |
|---|---|
clusters | API Server endpoints and certificate data |
users | Credentials or auth methods |
contexts | Named 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-contextsbefore important changes. - Keep production contexts clearly named.
- Use
-nexplicitly when you want to be extra careful. - Avoid assuming the default namespace is always correct.
Context Definition
What does a Kubernetes context usually combine?
Current Namespace
What does `kubectl config set-context --current --namespace=dev` do?