Comprehensive reference for kubernetes kubectl reference covering essential concepts, practical examples, and production best practices.
Kubectl is the command-line interface for managing Kubernetes clusters. Use it to deploy applications, inspect running pods, scale services, troubleshoot failures, and update configurations—all from the terminal. This reference documents precise, production-grade usage patterns, common pitfalls, and exact syntax for kubectl operations that engineers rely on daily.
kubectl apply -f deployment.yaml
Applies the configuration in deployment.yaml to the cluster. Creates or updates resources based on the apiVersion, kind, and metadata.name.
Key behavior:
apply command updates the kubectl.kubernetes.io/last-applied-configuration annotation on the object, which tracks the last applied configuration.Common pitfall:
kubectl apply -f but forgetting to include spec.template.spec.containers in the YAML leads to no container updates when the image is changed in spec.template.spec.containers[0].image, because the apply merge only updates fields present in the input YAML.Use --prune to remove obsolete resources:
kubectl apply -f manifests/ --prune --selector=app=nginx
manifests/ that match the app=nginx label but are not defined in the current manifests/ directory.kubectl rollout status deployment/frontend
kubectl rollout history deployment/frontend
kubectl rollout undo deployment/frontend --to-revision=3
rollout status waits until all pods in the deployment are ready. Returns 0 on success, 1 on timeout.rollout history shows revision history with kubectl.kubernetes.io/last-applied-configuration and spec changes.rollout undo rolls back to a previous revision, using --to-revision=N or --to-revision=1 for the latest revision.Sharp edge:
rollout undo does not trigger a new rollout unless --wait is specified.--wait, the rollout is asynchronous, and kubectl rollout status may report success even though the new pods are not yet ready.kubectl logs frontend-7d5b9c4b8f
kubectl logs -f frontend-7d5b9c4b8f
kubectl logs -c nginx frontend-7d5b9c4b8f
kubectl logs -c nginx --tail=50 frontend-7d5b9c4b8f
kubectl logs -c nginx --since=1h --timestamps frontend-7d5b9c4b8f
-f enables streaming logs (like tail -f).-c <container> selects a specific container in a multi-container pod.--tail=N shows the last N lines of logs.--since=duration filters logs from duration ago (e.g., 1h, 10m, 30s).--timestamps adds timestamps to each log line.Critical gotcha:
kubectl logs -f, logs from a restarted pod appear as a separate stream, but kubectl logs -f does not automatically reattach to a new pod when a pod restarts.--follow or --tail=0 with --since=0 and --timestamps: kubectl logs -f -c app --tail=0 --since=0 --timestamps frontend-7d5b9c4b8f
kubectl exec -it frontend-7d5b9c4b8f -- /bin/sh
kubectl exec -it frontend-7d5b9c4b8f -c nginx -- bash
kubectl exec -it frontend-7d5b9c4b8f -- ls -la /app
-i keeps stdin open (interactive).-t allocates a pseudo-TTY.-- separates kubectl options from the command to run inside the pod.Common mistake:
kubectl exec -it pod-name -- command runs command in the pod, but if command includes flags, they are parsed by the local shell, not the remote pod shell: # Wrong: runs 'ls -la' on local machine
kubectl exec -it pod-123 -- ls -la /app
# Correct: runs 'ls -la' inside the pod
kubectl exec -it pod-123 -- sh -c 'ls -la /app'
kubectl describe pod/frontend-7d5b9c4b8f
kubectl describe deployment/frontend
kubectl describe svc/frontend
kubectl describe nodes
FailedScheduling, FailedMount, Pulled, Created)Ready, Initialized, ContainersReady)Useful for diagnosing:
nodeSelector, affinity, and taints/tolerations.PersistentVolume, PersistentVolumeClaim, and StorageClass configurations.imagePullSecrets, imagePullPolicy, and initContainers.kubectl patch deployment/frontend -p '{"spec":{"replicas":5}}'
kubectl patch deployment/frontend -p '{"metadata":{"labels":{"env":"prod"}}}' --type=merge
kubectl patch deployment/frontend -p '{"spec":{"template":{"spec":{"containers":[{"name":"app","image":"new:latest"}]}}}}' --type=merge
--type=merge applies a JSON merge patch (default).--type=strategic uses strategic merge patch (supports nested arrays and maps).--type=apply uses apply-style patching with last-applied-configuration tracking.Critical behavior:
--type=strategic is required for patching fields in a list (e.g., spec.template.spec.containers), where merge only updates the top-level map.--type=apply is not idempotent unless last-applied-configuration is present.Use --patch-format=merge or --patch-format=strategic to force the patch type.
kubectl create configmap app-config --from-file=app.conf --from-literal=debug=true
kubectl create secret generic db-creds --from-file=creds.json --from-literal=password=secret123
kubectl apply -f configmap.yaml
kubectl apply -f secret.yaml
--from-file reads from a file into a key named after the filename.--from-literal creates a key-value pair in the ConfigMap/Secret.Key gotcha:
kubectl apply, existing ConfigMaps and Secrets are updated in place, but new keys are not added unless --force is used.--force: kubectl apply -f configmap.yaml --force
kubectl annotate pod/frontend-7d5b9c4b8f "deployer=jenkins" "release=1.2.3"
kubectl annotate pod/frontend-7d5b9c4b8f "deployer=jenkins" --overwrite
kubectl annotate pod/frontend-7d5b9c4b8f "monitoring=true" --all
kubectl annotate pod/frontend-7d5b9c4b8f "monitoring=true" --local -f - --save-config
--overwrite replaces existing annotations.--all applies the annotation to all matching pods.--local applies the annotation to the local object, not the cluster.Use --local with --save-config to persist changes to a file before applying to the cluster.
kubectl scale deployment/frontend --replicas=10
kubectl scale deployment/frontend --current-replicas=5 --replicas=10
kubectl scale deployment/frontend --replicas=5 -l env=prod
--current-replicas ensures the scale command only runs if the current replica count matches the expected value.-l env=prod applies scaling to all deployments with env=prod label.Critical detail:
kubectl scale does not wait for the new replicas to be ready.kubectl rollout status: kubectl scale deployment/frontend --replicas=10
kubectl rollout status deployment/frontend
kubectl set image deployment/frontend app=nginx:latest --record
kubectl set image deployment/frontend app=nginx:1.21 --record --all
--record adds the command to kubectl.kubernetes.io/last-applied-configuration.--all applies the image update to all replicasets of the deployment.Important:
--record is not the same as --save-config. Use both: kubectl set image deployment/frontend app=nginx:latest --record --save-config
kubectl config use-context prod-cluster
kubectl config use-context staging-cluster
kubectl config get-contexts
kubectl config current-context
kubectl config set-context prod-cluster --namespace=prod
kubectl config set-context prod-cluster --cluster=prod-cluster --namespace=prod
kubectl config use-context changes the active context.kubectl config set-context updates the context configuration.Sharp edge:
kubectl config set-context does not switch to the context unless --current-context is specified. kubectl config use-context prod-cluster --namespace=prod
kubectl config view
kubectl config view --output=yaml
kubectl config view --output=json
kubectl config get-clusters
kubectl config get-contexts
kubectl config get-namespaces
kubectl config set-cluster prod-cluster --server=https://prod.example.com
kubectl config set-credentials jenkins --token=abc123
kubectl config view shows the full kubeconfig with all clusters, contexts, and credentials.--output=yaml and --output=json allow exporting the config for version control.Tip:
kubeconfig in version control and use kubectl config use-context in CI/CD pipelines to target different environments.Error from server (NotFound): pods "frontend" not found → The pod name is incorrect or the pod is not in the current namespace. Use kubectl get pods -A to list pods across all namespaces.
Error from server (BadRequest): Cannot bind to port 80: Address already in use → A container in the pod is already listening on port 80. Check the container’s livenessProbe and readinessProbe.
Error from server (InternalError): the server has asked for the client to provide a response → The Kubernetes API server is under load or has a misconfigured etcd. Check kubectl get events -A and kubectl describe pod <pod>.
Error: unknown flag: --my-flag → The flag is not recognized by the current version of kubectl. Use kubectl version to verify the version and kubectl help to see available flags.
kubectl get with Custom Columnskubectl get pods -o=custom-columns=NAME:.metadata.name,STATUS:.status.phase,AGE:.metadata.creationTimestamp
custom-columns=NAME:.path.to.field.jsonpath for complex formatting: kubectl get pods -o=jsonpath='{range .items[*]}{.metadata.name}{"\t"}{.status.phase}{"\n"}{end}'
Use case:
kubectl get pods -o=custom-columns=NAME:.metadata.name,READY:.status.readyReplicas,UPDATES:.status.updateRevision --no-headers
> Note: All commands assume the current context is set via kubectl config use-context. Use kubectl config current-context to verify.
This page was rewritten on 10 October 2026. It replaced a templated version that was not specific to its own title. How these pages are written and checked. If anything here is wrong, tell us at [email protected] and we will correct it.
We use cookies for analytics (Google Analytics) and advertising (Google AdSense) to improve your experience and support free content. Privacy Policy