Switch Between Clusters with kubectl Contexts
One wrong context means running production commands on the wrong cluster.
What
kubectl contexts let you switch between multiple Kubernetes clusters and namespaces without reconfiguring. Each context stores a cluster, user, and namespace combination in your kubeconfig file. This means you can manage dev, staging, and production clusters from a single terminal.
Why It Matters
When you work with multiple clusters daily, context switching is critical for safety and speed. Without it, you risk running destructive commands against the wrong environment. A simple `kubectl delete` meant for dev can wipe production resources if you're pointed at the wrong cluster.
Example
# List all available contexts
kubectl config get-contexts
# See which context is currently active
kubectl config current-context
# Switch to the production context
kubectl config use-context production
# Set the default namespace for your current context
kubectl config set-context --current --namespace=my-app
# Rename a context for clarity
kubectl config rename-context old-name prod-clusterCommon Mistake
Running commands against the wrong cluster because you forgot to switch context. You meant to scale down in staging but just scaled down production.
Quick Fix
Always run `kubectl config current-context` before any destructive operation. Better yet, add it to your shell prompt so you always see which cluster you're targeting.
Key Takeaways
- 1kubectl contexts = saved cluster+user+namespace combos
- 2get-contexts: see all, current-context: see active
- 3use-context: switch clusters instantly
- 4set-context --current --namespace: change default ns
- 5Always verify context before destructive commands
Was this tip helpful?
Help us improve the DevOpsPath daily collection