kubectl is the Kubernetes command-line client. It reads connection and credential information from a kubeconfig, selects a context and namespace, and sends requests to the API server. Treat kubeconfig files as sensitive because they can contain bearer tokens, client certificates, and private keys.
Select Configuration and Context #
kubectl uses an explicit --kubeconfig file first, then the files named by KUBECONFIG, then $HOME/.kube/config. Inspect the active target before changing anything:
kubectl config current-context
kubectl config view --minify
kubectl config view --minify -o jsonpath='{..namespace}'; echoUse --context and --namespace for scripts that must not rely on ambient state. Prefer short-lived exec credentials or OIDC authentication over copying long-lived administrator credentials among machines.
Create, Apply, Patch, and Replace #
These commands have different ownership and update semantics:
kubectl create -f object.yamlcreates an object and fails if it already exists.kubectl apply -f object.yamlperforms declarative apply. Server-side apply tracks field ownership and is generally preferable for multi-writer declarative workflows.kubectl patchchanges selected fields of an existing object, usually for an operational exception.kubectl replace -f object.yamlreplaces the object specification and requires it to exist; it is not a safe shortcut for routine updates.kubectl deleteremoves an object and may trigger cascading deletion of dependents.
Preview a declarative change before applying it:
kubectl diff -f manifests/
kubectl apply --server-side --dry-run=server -f manifests/
kubectl apply --server-side -f manifests/Avoid mixing client-side apply, server-side apply, imperative patches, and multiple controllers on the same fields without understanding field ownership. A conflict is often useful evidence that another actor owns the field.
Inspect and Troubleshoot #
Start with the object’s desired state, current status, events, and controller logs:
kubectl get deployment web -n app -o wide
kubectl describe deployment web -n app
kubectl get events -n app --sort-by=.lastTimestamp
kubectl logs deployment/web -n app --all-containers=true
kubectl rollout status deployment/web -n appUse labels to select workloads instead of relying on generated names. kubectl exec and kubectl port-forward are valuable diagnostics tools, but production fixes should be encoded in declared configuration. Krew can install third-party plugins; review a plugin’s source and required permissions before installing it.
Comments
Read or comment on GitHub (sign-in required to comment)