Skip to main content

Containers and Kubernetes · Beginner · 15 min

Switch between Kubernetes clusters and namespaces with kubeconfig contexts

By Padding · Updated 18 Nov 2026
Ubuntu 26.04 · kubectl 1.37.3 · kubectx 0.9.5

You will build two kubeconfig files by hand, merge them, switch clusters and namespaces with kubectl and kubectx, export a single context for someone else, and keep production behind a confirmation prompt.

On this page

kubectl does not remember clusters on its own. Everything it needs to reach one, the API server address, the certificate that proves the server is genuine and your own credentials, sits in a YAML file called a kubeconfig. By default that is ~/.kube/config. kind, k3s and every cloud CLI write to it, and once you look after more than one cluster the question "which cluster will this command hit?" matters more than any other.

A kubeconfig has three lists and one pointer:

  • clusters: a name, a server URL and the server's CA certificate.
  • users: a name and a way to authenticate (a client certificate and key, a token, or a command that fetches one).
  • contexts: a name that pairs one cluster with one user and, optionally, a default namespace.
  • current-context: the context kubectl uses when you do not say otherwise.

Switching clusters means changing the current context. Switching namespaces means changing the namespace stored in a context.

In this tutorial you build a dev and a prod kubeconfig in a practice folder, with stand-in certificates, so you can see every part without a running cluster. Every kubectl config command here only reads and writes local files, so it all works offline and uses no mobile data. That is handy if you manage clusters for several clients from one laptop on a prepaid connection. At the end you remove the practice folder, and the same commands work on your real file.

Step 1 · Make a practice folder with stand-in certificates

Create a folder for the practice files and move into it. Run the rest of the tutorial from this folder, in the same terminal:

Bash
mkdir -p ~/kubeconfig-demo
cd ~/kubeconfig-demo

A real cluster gives you its CA certificate and your client certificate and key. Here you make throwaway self-signed ones for each pretend cluster. They are never sent anywhere. The commands run inside ( umask 077; ... ) so the key files are private from the moment they are created, and the umask does not stay changed in your shell:

Bash
(
  umask 077
  for env in dev prod; do
    openssl req -x509 -newkey rsa:2048 -nodes -days 30 -subj "/CN=$env-ca" \
      -keyout "$env-ca.key" -out "$env-ca.crt" 2>/dev/null
    openssl req -x509 -newkey rsa:2048 -nodes -days 30 -subj "/CN=$env-me" \
      -keyout "$env-me.key" -out "$env-me.crt" 2>/dev/null
  done
)

Check it worked

Bash
ls -l

You see eight files: dev-ca.crt, dev-ca.key, dev-me.crt, dev-me.key and the same four for prod. Each line starts with -rw-------, which means only your user can read the file.

Step 2 · Build a kubeconfig for the dev cluster

Build the dev file one part at a time. --kubeconfig=dev.yaml tells kubectl which file to write; without it kubectl would edit ~/.kube/config. The first command adds a cluster, the second a user, the third a context that ties them together with a default namespace of web, and the last makes that context current:

Bash
kubectl config set-cluster dev --kubeconfig=dev.yaml \
  --server=https://127.0.0.1:6443 --certificate-authority=dev-ca.crt
kubectl config set-credentials dev-me --kubeconfig=dev.yaml \
  --client-certificate=dev-me.crt --client-key=dev-me.key
kubectl config set-context dev --kubeconfig=dev.yaml \
  --cluster=dev --user=dev-me --namespace=web
kubectl config use-context dev --kubeconfig=dev.yaml

Each command prints a short confirmation such as Cluster "dev" set. or Switched to context "dev".. Now read the file:

Bash
cat dev.yaml

The output looks something like this. The order of the keys may differ, and the file paths may be written in full:

YAML
apiVersion: v1
clusters:
- cluster:
    certificate-authority: dev-ca.crt
    server: https://127.0.0.1:6443
  name: dev
contexts:
- context:
    cluster: dev
    namespace: web
    user: dev-me
  name: dev
current-context: dev
kind: Config
users:
- name: dev-me
  user:
    client-certificate: dev-me.crt
    client-key: dev-me.key

The cluster, user and context are separate entries joined by name. That is why one user can appear in several contexts, and why a context name like dev tells you nothing until you look at which cluster it points to.

Check it worked

Bash
kubectl config get-contexts --kubeconfig=dev.yaml

You see one row with a * in the CURRENT column, dev under NAME and CLUSTER, dev-me under AUTHINFO and web under NAMESPACE.

Step 3 · Build a self-contained kubeconfig for prod

The dev file points at certificate files by path, so it breaks if you move it to another machine. Add --embed-certs=true and kubectl copies the file contents into the kubeconfig as base64 instead. Cloud CLIs and kind write files this way. Build the prod file with embedded certificates:

Bash
kubectl config set-cluster prod --kubeconfig=prod.yaml \
  --server=https://k8s.prod.example.com:6443 --certificate-authority=prod-ca.crt --embed-certs=true
kubectl config set-credentials prod-me --kubeconfig=prod.yaml \
  --client-certificate=prod-me.crt --client-key=prod-me.key --embed-certs=true
kubectl config set-context prod --kubeconfig=prod.yaml \
  --cluster=prod --user=prod-me --namespace=default
kubectl config use-context prod --kubeconfig=prod.yaml

Check it worked

Bash
grep -n -- '-data:' prod.yaml | cut -c1-60

You see three lines, for certificate-authority-data, client-certificate-data and client-key-data, each followed by the start of a long base64 string. prod.yaml now holds a private key, so treat the whole file like a password.

Step 4 · Merge both files with KUBECONFIG

The KUBECONFIG environment variable takes a list of files, separated by : on Linux and macOS (; on Windows). kubectl reads them all and treats them as one config. Load both files:

Bash
export KUBECONFIG="$HOME/kubeconfig-demo/dev.yaml:$HOME/kubeconfig-demo/prod.yaml"
kubectl config get-contexts
kubectl config current-context

get-contexts lists dev and prod. The current context is dev, because when several files set current-context, the first file in the list wins.

Look at the merged result:

Bash
kubectl config view

The dev user still shows file paths. The prod entries show DATA+OMITTED where the base64 data is: view hides credentials unless you ask for them with --raw or --flatten.

Check it worked

Bash
kubectl config get-contexts -o name

This prints just the names, dev and prod, one per line. If you only see one, check the KUBECONFIG line for a typo; kubectl skips a file that does not exist without warning.

Step 5 · Switch clusters and namespaces

Switch to prod, then change the default namespace of the context you are on. --current means "the current context", so you do not have to type its name:

Bash
kubectl config use-context prod
kubectl config set-context --current --namespace=payments
kubectl config get-contexts

The * has moved to prod, and its NAMESPACE column now reads payments. From here a plain kubectl get pods would list pods in the payments namespace on the prod cluster.

With several files loaded, kubectl has to decide which file each change goes into. A change to an existing entry is written to the file that defines it, so the new namespace lands in prod.yaml. The current-context line is kept in the first file, dev.yaml:

Bash
grep -n 'current-context\|namespace' dev.yaml prod.yaml

That second rule has a catch. dev.yaml now says current-context: prod, a context it does not contain, so if you later use dev.yaml on its own, kubectl cannot find its context. Switch back before you move on:

Bash
kubectl config use-context dev

To run a single command somewhere else without switching, pass --context and --namespace. The setting lasts for that one command:

Bash
kubectl --context prod --namespace payments get pods

Check it worked

Bash
kubectl config current-context
kubectl config view --minify -o jsonpath='{..namespace}'; echo
kubectl config view --minify --context=prod -o jsonpath='{..namespace}'; echo

The first line prints dev, the second web, the namespace of the current context, and the third payments. --minify cuts the output down to one context, which makes it a quick way to answer "where am I?".

Step 6 · Export one context into its own file

To give a teammate or a CI job access to one cluster, do not send your whole kubeconfig. Cut out a single context with --minify, and add --flatten to copy every referenced certificate file into the output, so it works on any machine. As with the keys, create the file private from the start:

Bash
( umask 077; kubectl config view --minify --flatten --context=dev > dev-only.yaml )

The new file holds working credentials. Send it over a channel you would trust with a password, and give each person or job its own user where you can, so one can be removed without touching the others.

Your real ~/.kube/config deserves the same protection. If ls -l shows it readable by anyone other than you, fix it:

Bash
ls -l ~/.kube/config
chmod 600 ~/.kube/config

Check it worked

Bash
ls -l dev-only.yaml
kubectl config get-contexts --kubeconfig=dev-only.yaml
grep -c -- '-data:' dev-only.yaml

The file starts with -rw-------. It contains one context, dev, marked current. The grep prints 3: the CA, the client certificate and the key that dev.yaml only pointed at are now inside the file. --kubeconfig takes priority over KUBECONFIG, which is why only this file was read.

Step 7 · Switch faster with kubectx and kubens

kubectx switches contexts and kubens switches namespaces, with less typing than kubectl config. Ubuntu 26.04 packages both:

Bash
sudo apt update
sudo apt install -y kubectx

On macOS, install them with Homebrew instead:

Bash
brew install kubectx

kubectx reads a single kubeconfig file, not a list in KUBECONFIG. kubectl config view --flatten with both files loaded writes the merged config as one file, so make that and point KUBECONFIG at it:

Bash
( umask 077; kubectl config view --flatten > merged.yaml )
export KUBECONFIG="$HOME/kubeconfig-demo/merged.yaml"
kubectx
kubectx prod
kubectx -c
kubectx -
kubectx -c

kubectx on its own lists dev and prod; in a terminal the current one is highlighted. kubectx prod switches, -c prints the current context, and kubectx - goes back to the previous one, like cd -. kubectx remembers that previous context in ~/.kube/kubectx.

kubens works the same way for namespaces, but it asks the cluster which namespaces exist, so it needs a running cluster such as the one from the kind tutorial:

Bash
kubens
kubens kube-system
kubens -

Check it worked

Bash
kubectx -c
command -v kubectx kubens

The first line prints dev. The second prints the paths of both commands, /usr/bin/kubectx and /usr/bin/kubens.

Step 8 · Keep production behind a guard rail

Switching is easy, and that is the danger: a kubectl delete typed into the wrong terminal goes to whichever context is current. Two habits help. First, keep production out of your everyday config, so the default context can never be prod. Second, make the production route ask before it acts.

Write both into a small shell file. kprod runs kubectl against prod.yaml only, and for anything other than a kubectl config command it asks you to type yes. The last block puts the current context in your bash prompt; zsh needs its own prompt syntax, so that block only runs in bash:

Bash
cat > guard.sh <<'EOF'
# Everyday work: only the dev file is loaded.
export KUBECONFIG="$HOME/kubeconfig-demo/dev.yaml"

# Production: its own file, reached only through kprod, which asks first.
kprod() {
  if [ "${1:-}" != "config" ]; then
    printf 'Run "kubectl %s" on PRODUCTION? Type yes to continue: ' "$*"
    read -r answer
    if [ "$answer" != "yes" ]; then
      echo "Cancelled."
      return 1
    fi
  fi
  KUBECONFIG="$HOME/kubeconfig-demo/prod.yaml" command kubectl "$@"
}

# Show the current context in the bash prompt.
if [ -n "${BASH_VERSION:-}" ]; then
  PS1='[k8s:$(kubectl config current-context 2>/dev/null)] \w \$ '
fi
EOF
source guard.sh

Your prompt now starts with [k8s:dev]. Try a production command and answer anything but yes:

Bash
kprod get pods

kubectl never runs, and you see Cancelled.. Typing yes runs the command against prod. To keep this setup, copy the lines of guard.sh into your ~/.bashrc (or ~/.zshrc without the prompt block) and point the paths at where you keep your real files.

This guards against slips, not against a determined mistake. For real protection, the user in your day-to-day prod kubeconfig should only be allowed to read; RBAC does that on the cluster side.

Check it worked

Bash
kubectl config get-contexts -o name
kprod config current-context

The first command prints only dev: prod is not reachable by accident from your normal kubectl. The second prints prod, without a prompt, because config commands only read local files.

Step 9 · Clean up

Remove the practice folder, the function and the variable, and the file kubectx used to remember your previous context. Check that ~/kubeconfig-demo is the practice folder before you delete it; it holds nothing else from this tutorial:

Bash
unset KUBECONFIG
unset -f kprod
rm -rf ~/kubeconfig-demo
rm -f ~/.kube/kubectx
cd ~

Open a new terminal to get your usual prompt back. If you do not want kubectx any more, remove it with sudo apt remove kubectx.

Check it worked

Bash
test ! -e ~/kubeconfig-demo && echo "practice folder removed"

You see practice folder removed. Your real ~/.kube/config was never touched, because every command used --kubeconfig or KUBECONFIG to point at the practice files.

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.