0
0
Kubernetesdevops~5 mins

Switching namespace context in Kubernetes - Commands & Configuration

Choose your learning style9 modes available
Introduction
Kubernetes organizes resources into namespaces to keep things separate. Switching namespace context lets you work in a specific namespace without typing it every time.
When you have multiple projects running in the same Kubernetes cluster and want to focus on one project.
When you want to avoid typing --namespace flag repeatedly for commands.
When you need to check resources like pods or services in a specific namespace quickly.
When you are troubleshooting issues isolated to one namespace.
When you want to create or delete resources only in a particular namespace.
Commands
This command lists all available contexts and shows the current namespace for each. It helps you see what namespaces you can switch to.
Terminal
kubectl config get-contexts
Expected OutputExpected
CURRENT NAME CLUSTER AUTHINFO NAMESPACE * my-cluster-context my-cluster user@example.com default
This command changes the current context's namespace to 'example-namespace'. After this, kubectl commands run in this namespace by default.
Terminal
kubectl config set-context --current --namespace=example-namespace
Expected OutputExpected
Context "my-cluster-context" modified.
--current - Modifies the current active context
--namespace - Sets the default namespace for the context
This command lists pods in the current namespace, which is now 'example-namespace'. It verifies that the namespace switch worked.
Terminal
kubectl get pods
Expected OutputExpected
NAME READY STATUS RESTARTS AGE my-app-pod-1234567890 1/1 Running 0 10m
This command shows the namespace currently set in the active context to confirm the switch.
Terminal
kubectl config view --minify | grep namespace:
Expected OutputExpected
namespace: example-namespace
--minify - Shows only the current context details
Key Concept

If you remember nothing else from this pattern, remember: setting the namespace in your current context saves you from typing --namespace every time.

Common Mistakes
Trying to switch namespace by running 'kubectl config set-context' without the --current flag.
This creates or modifies a context but does not change the active context's namespace, so your commands still run in the old namespace.
Always use '--current' to change the namespace of the active context.
Assuming 'kubectl get pods' shows pods from all namespaces after switching context namespace.
kubectl commands without --all-namespaces flag only show resources in the current namespace.
Use 'kubectl get pods --all-namespaces' to see pods across all namespaces.
Summary
Use 'kubectl config set-context --current --namespace=your-namespace' to switch your default namespace.
Verify the switch by running 'kubectl get pods' to see resources in the new namespace.
Check the current namespace with 'kubectl config view --minify | grep namespace:'.