How to switch namespace in kubernetes

I like my answers short, to the point and with references to official documentation:

Answer:

kubectl config set-context --current --namespace=my-namespace

From:

https://kubernetes.io/docs/reference/kubectl/cheatsheet/

# permanently save the namespace for all subsequent kubectl commands in that context.
kubectl config set-context --current --namespace=ggckad-s2

There are a few options:

  • Switch namespace only using the kubectl commands::
kubectl config set-context --current --namespace=<namespace>
  • Or, Create a new context with namespace defined:
kubectl config set-context gce-dev --user=cluster-admin --namespace=dev
kubectl config use-context gce-dev
  • Or, Use addons, like kubectx & kubens, the below command will switch the context to kube-system:
$ kubens kube-system 
  • Or, Another easy alternative that I like without installing third party tools, is using bash alias(linux).
$ alias kubens='kubectl config set-context --current --namespace '
$ alias kubectx='kubectl config use-context '

// Usage
$ kubens kube-system    //Switch to a different namespace
$ kubectx docker        //Switch to separate context