Kubectl

Last update: 2025-10-02 07:12:04 +0800 +0800
Available translations: 日本語 / 中文(简体) / 中文(繁體)

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:

sh
kubectl config current-context
kubectl config view --minify
kubectl config view --minify -o jsonpath='{..namespace}'; echo

Use --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.yaml creates an object and fails if it already exists.
  • kubectl apply -f object.yaml performs declarative apply. Server-side apply tracks field ownership and is generally preferable for multi-writer declarative workflows.
  • kubectl patch changes selected fields of an existing object, usually for an operational exception.
  • kubectl replace -f object.yaml replaces the object specification and requires it to exist; it is not a safe shortcut for routine updates.
  • kubectl delete removes an object and may trigger cascading deletion of dependents.

Preview a declarative change before applying it:

sh
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:

sh
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 app

Use 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)