kubectl and kubeconfig

Kubernetes · Essentials · 10 min

kubectl is the tool you will type a thousand times a day; its patterns are worth learning once.

kubectl reads connection details from a kubeconfig file (~/.kube/config, or the KUBECONFIG variable). It holds clusters (API URL, CA), users (credentials) and contexts that pair a cluster, a user and a default namespace.

  • kubectl config get-contexts lists them; kubectl config use-context prod switches.
  • kubectl config set-context --current --namespace=shop changes the default namespace.

Commands follow kubectl <verb> <resource> [name] [flags]:

  • get pods, get deploy,svc, get pods -o wide, -o yaml to see the full object, -w to watch.
  • describe pod web-123: human-readable detail plus recent events, the first place to look when something is wrong.
  • apply -f file.yaml: create or update from a file or directory.
  • delete -f file.yaml or delete pod web-123.
  • -n ns targets a namespace, -A all namespaces, -l app=web filters by label.

kubectl explain deployment.spec.strategy prints the schema documentation for any field, straight from the cluster. kubectl api-resources lists every kind and its short name (po, deploy, svc, cm).

Always know which context you're in before running a destructive command: many people show it in their shell prompt.

Example

kubectl config get-contexts
# CURRENT  NAME      CLUSTER   NAMESPACE
# *        kind-dev  kind-dev  default
#          prod      prod-eks  shop

kubectl get deploy,svc -n kube-system
kubectl get pods -l app=web -o wide
kubectl get pod web-6d4cf56db6-7qv9z -o yaml | head -20
kubectl describe pod web-6d4cf56db6-7qv9z     # read the Events at the bottom
kubectl explain pod.spec.containers.ports
kubectl api-resources | grep -i deploy
# deployments  deploy  apps/v1  true  Deployment

Remember

  • A context = cluster + user + default namespace
  • describe shows events; -o yaml shows the full object
  • kubectl explain documents any field from the live API

Watch out for

  • Running kubectl delete or apply against prod because the current context was not the one you thought.

Check yourself

  1. Where do you first look to see why a pod is stuck in Pending?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: kubernetes.io/docs/reference/kubectl/