Kubernetes: Up and Running, 3rd Edition
by Brendan Burns, Joe Beda, Kelsey Hightower, Lachlan Evenson
Chapter 4. Common kubectl Commands
The kubectl command-line utility is a powerful tool, and in the following chapters, you will use it to create objects and interact with the Kubernetes API. Before that, however, it makes sense to go over the basic kubectl commands that apply to all Kubernetes objects.
Namespaces
Kubernetes uses namespaces to organize objects in the cluster. You
can think of each namespace as a folder that holds a set of objects.
By default, the kubectl command-line tool interacts with the default
namespace. If you want to use a different namespace, you can pass
kubectl the --namespace flag. For example, kubectl --namespace=mystuff references objects in the mystuff namespace. You can also use the shorthand
-n flag if you’re feeling concise. If you want to interact with all namespaces—for example, to list all Pods in your cluster—you can pass the --all-namespaces
flag.
Contexts
If you want to change the default namespace more permanently, you can use a context. This gets recorded in a kubectl configuration file, usually located at $HOME/.kube/config. This configuration file also stores how to both find and authenticate to your cluster. For example, you can create a context with a different default namespace for your kubectl commands using:
$ kubectl config set-context my-context --namespace=mystuff
This creates a new context, but it doesn’t actually start using it yet. To use this newly created context, you can run:
$ kubectl config use-context my-context