Sign In

Curriculum 10: Working with Namespaces

Switching Context

12 min · 15 XP

Switching Namespace Context

Typing -n my-namespace on every command gets tedious fast. Kubernetes lets you set a default namespace for your current context so all commands automatically target it.

Setting the Default Namespace

Use kubectl config set-context to change the namespace for your current context:

# Set "development" as the default namespace
kubectl config set-context --current --namespace=development

# Verify the change
kubectl config view --minify | grep namespace

Now every kubectl command runs against the development namespace without needing the -n flag.

Using the --namespace Flag

You can always override the default by passing --namespace (or its shorthand -n) directly:

# Get pods in staging, regardless of your default
kubectl get pods -n staging

# Describe a service in production
kubectl describe service api-gateway -n production

This is useful for quick one-off checks in a different namespace.

Faster Switching with kubens

The kubens tool (part of the kubectx package) simplifies namespace switching dramatically:

# Install kubectx + kubens
brew install kubectx

# List all namespaces (current one highlighted)
kubens

# Switch to staging
kubens staging

# Switch back to the previous namespace
kubens -

The kubens - shortcut toggles between your two most recent namespaces, similar to cd - in your shell.

Viewing Your Current Context

To check which cluster, user, and namespace you are currently targeting:

# Full context details
kubectl config current-context

# Show namespace in the active context
kubectl config view --minify --output='jsonpath={..namespace}'

If no namespace is set, commands default to the default namespace.

Key Takeaways

  • Use kubectl config set-context --current --namespace=NAME to set a default
  • The -n flag overrides the default for a single command
  • Install kubens for fast, interactive namespace switching
  • Always verify your active namespace before running destructive commands