Kubectl Fundamentals: Contexts, Namespaces, and the Commands You Use Daily

kubectl commands for daily work: kubeconfig, contexts and namespaces, get, describe, logs, exec, apply, diff, rollout and debug.

Executive Summary: kubectl is a client for the Kubernetes API. A kubeconfig file tells it which clusters exist, which credentials to use and which namespace to default to, grouped into contexts. Day to day, a small set of commands covers most work: get, describe, logs, exec, port-forward, apply, diff and rollout, plus explain and auth can-i for answering questions. The most valuable habit is making the current context impossible to miss, because the most expensive kubectl mistake is running the right command against the wrong cluster.
Isometric glass terminal showing kubectl get pods above a small cluster, with context labels for prod, staging and dev

An engineer runs kubectl delete namespace load-test to clean up after a performance test. The command succeeds. A minute later, alerts fire: the terminal was still pointed at production from a debugging session that morning, and production also had a load-test namespace that a partner integration depended on. kubectl did exactly what it was told. The context was the problem.

kubectl is the command-line client for the Kubernetes API server described in the control plane article. Every command becomes one or more HTTPS requests to the API. Which API, as whom, and in which namespace is decided by the kubeconfig file.

Kubeconfig, clusters and contexts

kubectl reads ~/.kube/config by default, or every file listed in the KUBECONFIG environment variable, merged. A kubeconfig has three lists and a pointer:

  • clusters: API server URLs and their CA certificates.
  • users: credentials, such as client certificates, tokens or an exec plugin that fetches a short-lived token from a cloud provider.
  • contexts: named combinations of a cluster, a user and a default namespace.
  • current-context: the context used when you do not specify one.
kubectl config get-contexts                       # list contexts; * marks the current one
kubectl config current-context
kubectl config use-context staging-eu
kubectl config set-context --current --namespace=billing   # change the default namespace

# Cloud CLIs add contexts for you
aws eks update-kubeconfig --name prod-eu --region eu-west-1
gcloud container clusters get-credentials prod-eu --region europe-west1

The open-source kubectx and kubens tools make switching faster. More important is visibility: show the current context and namespace in your shell prompt, with a loud color for production, using a tool like kube-ps1 or Starship. Some teams go further and keep production credentials in a separate kubeconfig that is only loaded in a dedicated terminal.

Namespaces

Namespaces divide a cluster into named scopes for most objects: pods, deployments, services, config maps and secrets. Names must be unique within a namespace, and RBAC, resource quotas and network policies are commonly applied per namespace. A few objects, such as nodes, persistent volumes, storage classes and namespaces themselves, are cluster-scoped.

kubectl get namespaces
kubectl get pods -n billing
kubectl get pods -A                      # all namespaces
kubectl create namespace billing

Every cluster starts with default, kube-system for system components, kube-public and kube-node-lease. Avoid putting real workloads in default; a namespace per application or team keeps permissions and quotas manageable.

The commands you use every day

Looking at things

kubectl get pods                                  # summary table
kubectl get pods -o wide                          # plus node and pod IP
kubectl get pods -l app=billing-api               # filter by label
kubectl get deploy,svc,ingress                    # several types at once
kubectl get pod billing-api-7c9f -o yaml          # the full object, including status
kubectl get pods -w                               # watch for changes
kubectl describe pod billing-api-7c9f             # human-readable detail plus recent events
kubectl get events --sort-by=.lastTimestamp       # what has been happening in the namespace

describe is the first command to run when something is wrong. Its Events section at the bottom explains most stuck pods: failed scheduling, image pull errors, failed probes, OOM kills.

Logs and getting inside

kubectl logs billing-api-7c9f                     # current container logs
kubectl logs billing-api-7c9f --previous          # logs from the last crashed instance
kubectl logs -f deploy/billing-api                # follow logs from a pod of the deployment
kubectl logs -l app=billing-api --tail=50         # recent logs from every matching pod
kubectl logs billing-api-7c9f -c migrate          # a specific container in the pod
kubectl exec -it billing-api-7c9f -- sh           # shell inside the container
kubectl port-forward svc/billing-api 8080:80      # reach a service from your laptop

--previous is the one people forget: when a container is in CrashLoopBackOff, the current container has barely started, and the reason for the crash is in the previous instance’s logs.

Changing things

kubectl diff -f k8s/                              # what would change, before applying
kubectl apply -f k8s/                             # create or update from files
kubectl apply -k overlays/prod                    # apply a Kustomize overlay
kubectl delete -f k8s/old-worker.yaml
kubectl rollout status deploy/billing-api         # wait for a rollout to finish
kubectl rollout history deploy/billing-api
kubectl rollout undo deploy/billing-api           # back to the previous revision
kubectl rollout restart deploy/billing-api        # recreate pods, for example after a secret change
kubectl scale deploy/billing-api --replicas=5

Prefer the declarative workflow: manifests in Git, kubectl diff to review, kubectl apply to change. Imperative commands such as scale and edit are useful in an emergency, but whatever they change will be overwritten by the next apply of the files, or will silently drift from them.

Generating YAML instead of typing it

kubectl create deployment billing-api --image=ghcr.io/acme/billing-api:1.9.0 \
  --replicas=3 --dry-run=client -o yaml > deployment.yaml

kubectl create secret generic db-creds --from-literal=password=change-me \
  --dry-run=client -o yaml

--dry-run=client -o yaml turns any imperative create command into a starting manifest, with correct indentation and API versions.

Answering questions

kubectl explain deployment.spec.strategy           # documentation for any field
kubectl explain pod.spec.containers.resources --recursive
kubectl api-resources                              # every resource type, short name and scope
kubectl auth can-i create deployments -n billing   # am I allowed?
kubectl auth can-i --list -n billing               # everything I can do here
kubectl top pods -n billing                        # CPU and memory, needs metrics-server
kubectl get pods -o jsonpath='{.items[*].spec.containers[*].image}'   # extract fields

kubectl explain is faster than searching the web for a field name, and it always matches your cluster’s version.

Debugging minimal images

kubectl debug -it billing-api-7c9f --image=busybox:1.36 --target=api

kubectl debug adds an ephemeral container to a running pod, sharing its process namespace with the target container, so you can inspect a distroless container that has no shell. Ephemeral containers became stable in Kubernetes 1.25. kubectl debug node/NAME similarly gives you a shell on a node.

Habits that protect production

  • Show context and namespace in your prompt, colored by environment.
  • Pass --context explicitly in scripts and runbooks rather than relying on the current context.
  • Run kubectl diff before every apply to a shared cluster.
  • Give most people read-only access to production, and make write access a deliberate step.
  • Short aliases such as alias k=kubectl are fine, but avoid aliases that hide the namespace or context.

Frequently Asked Questions

What is a kubectl context?

A context is a named combination of a cluster, a user’s credentials and a default namespace in the kubeconfig file. kubectl config use-context switches between them, and the current context decides where every command goes.

How do I change the default namespace in kubectl?

Run kubectl config set-context –current –namespace=NAME. Every subsequent command in that context uses the namespace unless you pass -n or –namespace.

How do I see logs of a crashed pod?

Run kubectl logs POD –previous to see the output of the last terminated container instance. kubectl describe pod shows the exit code and the reason, such as OOMKilled or Error.

What is the difference between kubectl apply and kubectl create?

kubectl create makes a new object and fails if it already exists. kubectl apply creates the object or updates it to match the file, which makes it suitable for a declarative workflow with manifests stored in Git.

The API, from your terminal

kubectl is a thin client over a powerful API, so a few dozen commands go a long way. Learn get, describe, logs --previous, diff and apply first, lean on explain and auth can-i for questions, and make the current context visible at all times. With that in place, objects such as pods and Deployments are easy to explore hands-on. For the full reference, see the kubectl quick reference and the kubectl reference documentation. Related reading on this site: Docker debugging habits.

Originally posted on 6 February 2024 and post last modified on 6 February 2024

CLI DevOps kubectl Kubernetes

Share this article

Leave a Reply

Your email address will not be published. Required fields are marked *