3-Kubernetes
Kubectx

Practical Guide – kubectx & kubens

Managing multiple Kubernetes clusters and namespaces with plain kubectl can get repetitive. Two handy tools – kubectx and kubens – simplify switching contexts and namespaces.


1. πŸ”§ Installation

Linux / macOS

# Install both with brew
brew install kubectx
 
# Or manually
git clone https://github.com/ahmetb/kubectx.git ~/.kubectx
sudo ln -s ~/.kubectx/kubectx /usr/local/bin/kubectx
sudo ln -s ~/.kubectx/kubens /usr/local/bin/kubens

Windows (with Chocolatey)

choco install kubectx

2. βš™οΈ Setup & Verify

Ensure kubectl works with clusters:

kubectl config get-contexts

Then test:

kubectx --help
kubens --help

3. 🧭 Usage

πŸ”„ Switch Contexts (kubectx)

  • List available contexts:
kubectx
  • Switch to a context:
kubectx my-cluster
  • Rename a context:
kubectx old-name=new-name
  • Switch back to previous context:
kubectx -

πŸ“‚ Switch Namespaces (kubens)

  • List all namespaces:
kubens
  • Switch to namespace:
kubens dev
  • Switch back to previous namespace:
kubens -

4. πŸ“‘ Common Workflows

Example: Change Context + Namespace

kubectx production
kubens payments

Now all kubectl commands run in production cluster, payments namespace.


5. 🎨 Bonus Features

  • Fuzzy search support if fzf is installed β†’ lets you pick context/namespace interactively.
kubectx
kubens

Opens an interactive menu to choose from.

  • Works seamlessly with k9s β†’ if you already use it.

6. βœ… Summary

  • kubectx β†’ switch between clusters/contexts easily.
  • kubens β†’ switch between namespaces quickly.
  • Both save time and reduce human error vs typing full kubectl config commands.

⚑ These tools are must-haves for anyone managing multiple Kubernetes clusters/namespaces daily.

| Feature                | kubectl                      | kubectx/kubens               |
|------------------------|------------------------------|-------------------------------|
| Context Switching       | `kubectl config use-context` | `kubectx <context>`          |
| Namespace Switching     | `kubectl config set-context --namespace` | `kubens <namespace>`        |
| List Contexts          | `kubectl config get-contexts`| `kubectx`                    |
| List Namespaces        | `kubectl get namespaces`     | `kubens`                     |
| Interactive Selection   | No                           | Yes (with fzf)               |

πŸ’¬ Need a Quick Summary?

Hey! Don't have time to read everything? I get it. 😊
Click below and I'll give you the main points and what matters most on this page.
Takes about 5 seconds β€’ Uses Perplexity AI