0
0
KubernetesHow-ToBeginner · 3 min read

How to Switch Namespace in Kubernetes Quickly and Easily

To switch namespace in Kubernetes, use the kubectl config set-context --current --namespace=your-namespace command to change the active namespace for your current context. Alternatively, you can specify the namespace per command using kubectl --namespace=your-namespace.
📐

Syntax

The main command to switch namespace in Kubernetes is:

  • kubectl config set-context --current --namespace=your-namespace: Changes the default namespace for your current kubectl context.
  • kubectl --namespace=your-namespace [command]: Runs a single command in the specified namespace without changing the default.
bash
kubectl config set-context --current --namespace=your-namespace
kubectl --namespace=your-namespace get pods
💻

Example

This example shows how to switch the current namespace to development and then list pods in that namespace.

bash
kubectl config set-context --current --namespace=development
kubectl get pods
Output
No resources found in development namespace.
⚠️

Common Pitfalls

Common mistakes when switching namespaces include:

  • Forgetting to set the namespace in the current context, causing commands to run in the default namespace.
  • Using kubectl get pods without specifying namespace or switching context, which shows pods only in the default namespace.
  • Assuming namespace change is permanent across terminals; it only applies to the current context configuration.
bash
Wrong way:
kubectl get pods

Right way:
kubectl config set-context --current --namespace=development
kubectl get pods
📊

Quick Reference

CommandDescription
kubectl config set-context --current --namespace=your-namespaceSet default namespace for current context
kubectl --namespace=your-namespace get podsRun a single command in a specific namespace
kubectl get podsGet pods in the current default namespace

Key Takeaways

Use 'kubectl config set-context --current --namespace=your-namespace' to switch the default namespace for your current context.
You can run commands in a specific namespace without switching context by adding '--namespace=your-namespace' to kubectl commands.
Namespace changes affect only the current kubectl context and terminal session unless changed again.
Always verify your current namespace with 'kubectl config view --minify | grep namespace' before running commands.
Forgetting to specify namespace can lead to confusion when resources appear missing.