Tested with kubectl 1.37, and it works the same against any recent cluster: EKS, AKS, GKE, k3s or kind. Commands run in the current context and namespace. Add -n to pick a namespace, or --context to pick a cluster. JSONPath is written in double quotes, which works in bash, zsh, PowerShell and Command Prompt.
Official links: kubectl overview, kubectl quick reference.
Setup and help #
-
Show the kubectl versionLinux, macOS, Windows
kubectl version --client -
Show the kubectl and cluster versionsLinux, macOS, Windows
kubectl version -
Show the cluster's API addressLinux, macOS, Windows
kubectl cluster-info -
List every resource type, with short namesLinux, macOS, Windows
kubectl api-resources -
List the API versions the cluster supportsLinux, macOS, Windows
kubectl api-versions -
Explain a resource's fieldsLinux, macOS, Windows
kubectl explain pod.spec.containers -
Show every field of a resource as a treeLinux, macOS, Windows
kubectl explain deployment --recursive -
Turn on tab completionLinux, macOS
source <(kubectl completion bash)Windowskubectl completion powershell | Out-String | Invoke-Expression -
Turn on tab completion in zshLinux, macOS
source <(kubectl completion zsh) -
Use k as a short name for kubectlLinux, macOS
alias k=kubectlWindowsSet-Alias -Name k -Value kubectl -
List the kubectl plugins you haveLinux, macOS, Windows
kubectl plugin list -
List the flags every command takesLinux, macOS, Windows
kubectl options
Contexts and kubeconfig #
-
List contexts (clusters you can talk to)Linux, macOS, Windows
kubectl config get-contexts -
Show the current contextLinux, macOS, Windows
kubectl config current-context -
Switch to another contextLinux, macOS, Windows
kubectl config use-context prod-cluster -
Set the default namespace for the current contextLinux, macOS, Windows
kubectl config set-context --current --namespace=my-app -
Run one command against another contextLinux, macOS, Windows
kubectl get pods --context prod-cluster -
Show the current context's settingsLinux, macOS, Windows
kubectl config view --minify -
Show the kubeconfig with keys and tokensLinux, macOS, Windows
kubectl config view --minify --rawWarning: Prints a secret in plain text. Don't paste the output anywhere it could be saved or shared.
-
Rename a contextLinux, macOS, Windows
kubectl config rename-context prod-cluster prod -
Delete a contextLinux, macOS, Windows
kubectl config delete-context prod-cluster -
Use another kubeconfig file for one commandLinux, macOS, Windows
kubectl get nodes --kubeconfig ~/.kube/lab.yaml -
Use another kubeconfig file in this terminalLinux, macOS
export KUBECONFIG=~/.kube/lab.yamlWindows$env:KUBECONFIG = "~/.kube/lab.yaml" -
Merge a new kubeconfig into your main oneLinux, macOS
KUBECONFIG=~/.kube/config:~/.kube/lab.yaml kubectl config view --flatten > ~/.kube/config.new && mv ~/.kube/config.new ~/.kube/configWarning: Back up ~/.kube/config first.
-
Show who the cluster thinks you areLinux, macOS, Windows
kubectl auth whoami
Viewing resources #
-
List pods in the current namespaceLinux, macOS, Windows
kubectl get pods -
List pods in a namespaceLinux, macOS, Windows
kubectl get pods -n my-app -
List pods in every namespaceLinux, macOS, Windows
kubectl get pods --all-namespaces -
List pods with their node and IP addressLinux, macOS, Windows
kubectl get pods -o wide -
Watch pods change liveLinux, macOS, Windows
kubectl get pods --watch -
List pods with their labelsLinux, macOS, Windows
kubectl get pods --show-labels -
List pods with a labelLinux, macOS, Windows
kubectl get pods -l app=web -
List pods that are pendingLinux, macOS, Windows
kubectl get pods --field-selector=status.phase=Pending -
List pods on one nodeLinux, macOS, Windows
kubectl get pods --all-namespaces --field-selector=spec.nodeName=worker-1 -
List pods, newest lastLinux, macOS, Windows
kubectl get pods --sort-by=.metadata.creationTimestamp -
List pods by restart countLinux, macOS, Windows
kubectl get pods --sort-by=.status.containerStatuses[0].restartCount -
List the common resources in a namespaceLinux, macOS, Windows
kubectl get all -n my-app -
List several kinds of resource at onceLinux, macOS, Windows
kubectl get deployments,services,ingresses -n my-app -
Show a resource's details and recent eventsLinux, macOS, Windows
kubectl describe pod web-7d4b9c6f5-x2k8p -
Show a resource as YAMLLinux, macOS, Windows
kubectl get deployment web -o yaml -
Print just the namesLinux, macOS, Windows
kubectl get pods -o name -
Show your own columnsLinux, macOS, Windows
kubectl get pods -o custom-columns=NAME:.metadata.name,STATUS:.status.phase,NODE:.spec.nodeName -
Print one field with JSONPathLinux, macOS, Windows
kubectl get pod web-7d4b9c6f5-x2k8p -o jsonpath="{.status.podIP}" -
List every container image in useLinux, macOS, Windows
kubectl get pods --all-namespaces -o jsonpath="{.items[*].spec.containers[*].image}" -
List the names of running pods with JSONPathLinux, macOS, Windows
kubectl get pods -o jsonpath="{.items[?(@.status.phase=='Running')].metadata.name}" -
List recent events, newest lastLinux, macOS, Windows
kubectl get events --sort-by=.lastTimestamp -
List warning events onlyLinux, macOS, Windows
kubectl events --types=Warning -
List the events for one resourceLinux, macOS, Windows
kubectl events --for pod/web-7d4b9c6f5-x2k8p -
Show CPU and memory for pods (needs metrics-server)Linux, macOS, Windows
kubectl top pods -
Show CPU and memory for nodes (needs metrics-server)Linux, macOS, Windows
kubectl top nodes
Creating and applying #
-
Create or update resources from a fileLinux, macOS, Windows
kubectl apply -f app.yaml -
Apply every file in a folderLinux, macOS, Windows
kubectl apply -f k8s/ -
Apply a Kustomize folderLinux, macOS, Windows
kubectl apply -k overlays/prod -
Show what kustomize would buildLinux, macOS, Windows
kubectl kustomize overlays/prod -
See what applying a file would changeLinux, macOS, Windows
kubectl diff -f app.yaml -
Check a file with the cluster without changing anythingLinux, macOS, Windows
kubectl apply -f app.yaml --dry-run=server -
Delete the resources in a fileLinux, macOS, Windows
kubectl delete -f app.yamlWarning: Deletes everything the file defines.
-
Make a deploymentLinux, macOS, Windows
kubectl create deployment web --image=nginx:1.29 --replicas=3 -
Write a deployment's YAML to a file, without creating itLinux, macOS, Windows
kubectl create deployment web --image=nginx:1.29 --dry-run=client -o yaml > app.yaml -
Run a single podLinux, macOS, Windows
kubectl run nginx --image=nginx:1.29 -
Expose a deployment as a serviceLinux, macOS, Windows
kubectl expose deployment web --port=443 --target-port=8080 -
Expose a deployment outside the cluster on a node portLinux, macOS, Windows
kubectl expose deployment web --type=NodePort --port=443 --target-port=8080 -
Make a namespaceLinux, macOS, Windows
kubectl create namespace my-app -
Run a one-off jobLinux, macOS, Windows
kubectl create job db-backup --image=nginx:1.29 -- date -
Make a cron job that runs every night at 2amLinux, macOS, Windows
kubectl create cronjob nightly-backup --image=nginx:1.29 --schedule="0 2 * * *" -- date -
Run a cron job nowLinux, macOS, Windows
kubectl create job db-backup --from=cronjob/nightly-backup -
Add or change a labelLinux, macOS, Windows
kubectl label pod web-7d4b9c6f5-x2k8p env=prod --overwrite -
Remove a labelLinux, macOS, Windows
kubectl label pod web-7d4b9c6f5-x2k8p env- -
Add a note (annotation)Linux, macOS, Windows
kubectl annotate deployment web owner=platform-team -
Edit a resource in your editorLinux, macOS, Windows
kubectl edit deployment web -
Change part of a resource from a patch fileLinux, macOS, Windows
kubectl patch deployment web --type=merge --patch-file=patch.yaml -
Delete a resourceLinux, macOS, Windows
kubectl delete deployment web -
Delete every resource with a labelLinux, macOS, Windows
kubectl delete deployment,service -l app=webWarning: Deletes every matching resource in the namespace.
-
Delete a namespace and everything in itLinux, macOS, Windows
kubectl delete namespace my-appWarning: Deletes every resource in the namespace, with no undo.
Deployments and rollouts #
-
Scale a deploymentLinux, macOS, Windows
kubectl scale deployment web --replicas=3 -
Change a deployment's imageLinux, macOS, Windows
kubectl set image deployment/web web=nginx:1.29.3 -
Watch a rollout until it finishesLinux, macOS, Windows
kubectl rollout status deployment/web -
Show a deployment's rollout historyLinux, macOS, Windows
kubectl rollout history deployment/web -
Show what changed in one revisionLinux, macOS, Windows
kubectl rollout history deployment/web --revision=2 -
Roll back to the previous versionLinux, macOS, Windows
kubectl rollout undo deployment/web -
Roll back to a particular revisionLinux, macOS, Windows
kubectl rollout undo deployment/web --to-revision=2 -
Restart every pod in a deployment, one at a timeLinux, macOS, Windows
kubectl rollout restart deployment/web -
Pause a rollout to make several changesLinux, macOS, Windows
kubectl rollout pause deployment/web -
Resume a paused rolloutLinux, macOS, Windows
kubectl rollout resume deployment/web -
Set an environment variable on a deploymentLinux, macOS, Windows
kubectl set env deployment/web LOG_LEVEL=debug -
List a deployment's environment variablesLinux, macOS, Windows
kubectl set env deployment/web --list -
Set CPU and memory requests and limitsLinux, macOS, Windows
kubectl set resources deployment web --requests=cpu=100m,memory=128Mi --limits=cpu=500m,memory=512Mi -
Scale a deployment on CPU useLinux, macOS, Windows
kubectl autoscale deployment web --min=2 --max=10 --cpu-percent=70 -
List autoscalersLinux, macOS, Windows
kubectl get hpa -
Wait until a deployment is availableLinux, macOS, Windows
kubectl wait --for=condition=Available deployment/web --timeout=120s -
Restart a stateful set or daemon setLinux, macOS, Windows
kubectl rollout restart statefulset/postgres
Pods: logs, shells and files #
-
Show a pod's logsLinux, macOS, Windows
kubectl logs web-7d4b9c6f5-x2k8p -
Follow a pod's logs liveLinux, macOS, Windows
kubectl logs -f web-7d4b9c6f5-x2k8p -
Show the logs from before a container crashed and restartedLinux, macOS, Windows
kubectl logs web-7d4b9c6f5-x2k8p --previous -
Show one container's logs in a pod with severalLinux, macOS, Windows
kubectl logs web-7d4b9c6f5-x2k8p -c web -
Show the last hour of logsLinux, macOS, Windows
kubectl logs web-7d4b9c6f5-x2k8p --since=1h -
Show the last 100 linesLinux, macOS, Windows
kubectl logs web-7d4b9c6f5-x2k8p --tail=100 -
Show logs from every pod with a labelLinux, macOS, Windows
kubectl logs -l app=web --all-containers --prefix -
Show logs from a deployment, without finding a pod nameLinux, macOS, Windows
kubectl logs deployment/web -
Open a shell in a podLinux, macOS, Windows
kubectl exec -it web-7d4b9c6f5-x2k8p -- sh -
Open a shell in one container of a podLinux, macOS, Windows
kubectl exec -it web-7d4b9c6f5-x2k8p -c web -- sh -
Run one command in a podLinux, macOS, Windows
kubectl exec web-7d4b9c6f5-x2k8p -- env -
Copy a file from a podLinux, macOS, Windows
kubectl cp web-7d4b9c6f5-x2k8p:/var/log/app.log app.log -
Copy a file into a podLinux, macOS, Windows
kubectl cp app.log web-7d4b9c6f5-x2k8p:/var/log/app.log -
Forward a local port to a podLinux, macOS, Windows
kubectl port-forward pod/web-7d4b9c6f5-x2k8p 8080:8080 -
Forward a local port to a serviceLinux, macOS, Windows
kubectl port-forward service/web 8080:443 -
Start a throwaway pod with a shell, deleted when you exitLinux, macOS, Windows
kubectl run tmp-shell --rm -it --image=busybox:1.37 --restart=Never -- sh -
Add a debug container to a running podLinux, macOS, Windows
kubectl debug -it web-7d4b9c6f5-x2k8p --image=busybox:1.37 --target=web -
Debug a pod with a copy you can changeLinux, macOS, Windows
kubectl debug web-7d4b9c6f5-x2k8p -it --copy-to=web-7d4b9c6f5-x2k8p-debug --container=web -- sh -
Open a shell on a nodeLinux, macOS, Windows
kubectl debug node/worker-1 -it --image=busybox:1.37Warning: The node's file system is mounted at /host, with full access.
-
Delete a pod (its deployment makes a new one)Linux, macOS, Windows
kubectl delete pod web-7d4b9c6f5-x2k8p -
Force delete a pod stuck in TerminatingLinux, macOS, Windows
kubectl delete pod web-7d4b9c6f5-x2k8p --grace-period=0 --forceWarning: The container may still be running on the node. Use it only when the node is gone or broken.
-
Show why a pod's containers restartedLinux, macOS, Windows
kubectl get pod web-7d4b9c6f5-x2k8p -o jsonpath="{.status.containerStatuses[*].lastState}"
ConfigMaps and Secrets #
-
Make a ConfigMap from valuesLinux, macOS, Windows
kubectl create configmap web-config --from-literal=LOG_LEVEL=info -
Make a ConfigMap from a fileLinux, macOS, Windows
kubectl create configmap web-config --from-file=nginx.conf -
Make a ConfigMap from a .env fileLinux, macOS, Windows
kubectl create configmap web-config --from-env-file=.env -
Show a ConfigMapLinux, macOS, Windows
kubectl describe configmap web-config -
Make a Secret from a fileLinux, macOS, Windows
kubectl create secret generic db-credentials --from-file=password.txt -
Make a Secret from a valueLinux, macOS, Windows
kubectl create secret generic db-credentials --from-literal=password=MyPasswordWarning: The value ends up in your shell history. Use --from-file to avoid that.
-
Make a Secret for pulling from a private registryLinux, macOS, Windows
kubectl create secret docker-registry db-credentials --docker-server=registry.example.com --docker-username=deploy --docker-password=MyRegistryTokenWarning: The password ends up in your shell history.
-
Make a TLS Secret from a certificate and keyLinux, macOS, Windows
kubectl create secret tls db-credentials --cert=tls.crt --key=tls.key -
List the keys in a Secret, without the valuesLinux, macOS, Windows
kubectl describe secret db-credentials -
Read one value from a SecretLinux, macOS
kubectl get secret db-credentials -o jsonpath="{.data['password']}" | base64 --decodeWindows[Text.Encoding]::UTF8.GetString([Convert]::FromBase64String((kubectl get secret db-credentials -o jsonpath="{.data['password']}")))Warning: Prints a secret in plain text. Don't paste the output anywhere it could be saved or shared.
-
Write a Secret's YAML without creating it, for GitOps toolsLinux, macOS, Windows
kubectl create secret generic db-credentials --from-file=password.txt --dry-run=client -o yaml > app.yamlWarning: The YAML holds the secret, only base64-encoded. Encrypt it (for example with Sealed Secrets or SOPS) before committing it.
-
Load every key in a ConfigMap as environment variablesLinux, macOS, Windows
kubectl set env deployment/web --from=configmap/web-config -
Load every key in a Secret as environment variablesLinux, macOS, Windows
kubectl set env deployment/web --from=secret/db-credentials
Services and networking #
-
List servicesLinux, macOS, Windows
kubectl get services -
Show the pods behind a serviceLinux, macOS, Windows
kubectl get endpointslices -l kubernetes.io/service-name=web -
List ingressesLinux, macOS, Windows
kubectl get ingress --all-namespaces -
Show an ingress's rules and backendsLinux, macOS, Windows
kubectl describe ingress web -
Make an ingress for a hostLinux, macOS, Windows
kubectl create ingress web --class=nginx --rule="app.example.com/*=web:443" -
List network policiesLinux, macOS, Windows
kubectl get networkpolicies --all-namespaces -
Test a service from inside the clusterLinux, macOS, Windows
kubectl run tmp-curl --rm -it --image=curlimages/curl --restart=Never -- curl -s http://web.my-app.svc.cluster.local -
Test DNS from inside the clusterLinux, macOS, Windows
kubectl run tmp-dns --rm -it --image=busybox:1.37 --restart=Never -- nslookup kubernetes.default -
List Gateway API gateways and routes (needs the Gateway API CRDs)Linux, macOS, Windows
kubectl get gateways,httproutes --all-namespaces
Nodes and cluster #
-
List nodesLinux, macOS, Windows
kubectl get nodes -
List nodes with their IPs, OS and runtimeLinux, macOS, Windows
kubectl get nodes -o wide -
Show a node's capacity, conditions and podsLinux, macOS, Windows
kubectl describe node worker-1 -
Stop new pods being scheduled on a nodeLinux, macOS, Windows
kubectl cordon worker-1 -
Move every pod off a node, for maintenanceLinux, macOS, Windows
kubectl drain worker-1 --ignore-daemonsets --delete-emptydir-dataWarning: Evicts every pod on the node, and data in emptyDir volumes is lost.
-
Let pods be scheduled on a node againLinux, macOS, Windows
kubectl uncordon worker-1 -
Taint a node so only some pods run thereLinux, macOS, Windows
kubectl taint nodes worker-1 dedicated=gpu:NoSchedule -
Remove a taintLinux, macOS, Windows
kubectl taint nodes worker-1 dedicated=gpu:NoSchedule- -
Label a nodeLinux, macOS, Windows
kubectl label nodes worker-1 env=prod -
Check the API server is healthyLinux, macOS, Windows
kubectl get --raw=/readyz?verbose -
List certificate signing requestsLinux, macOS, Windows
kubectl get csr -
Approve a certificate signing requestLinux, macOS, Windows
kubectl certificate approve csr-8x2kq -
List custom resource types (CRDs)Linux, macOS, Windows
kubectl get crds
Access control (RBAC) #
-
Check whether you can do somethingLinux, macOS, Windows
kubectl auth can-i create deployments -n my-app -
List everything you can do in a namespaceLinux, macOS, Windows
kubectl auth can-i --list -n my-app -
Check what another user or service account can doLinux, macOS, Windows
kubectl auth can-i get secrets -n my-app --as=system:serviceaccount:my-app:deployer -
Make a service accountLinux, macOS, Windows
kubectl create serviceaccount deployer -n my-app -
Get a short-lived token for a service accountLinux, macOS, Windows
kubectl create token deployer -n my-app --duration=1hWarning: Prints a secret in plain text. Don't paste the output anywhere it could be saved or shared.
-
Make a role that can read podsLinux, macOS, Windows
kubectl create role pod-reader --verb=get,list,watch --resource=pods -n my-app -
Give a service account a roleLinux, macOS, Windows
kubectl create rolebinding deployer-pod-reader --role=pod-reader --serviceaccount=my-app:deployer -n my-app -
Give a user read-only access to a namespaceLinux, macOS, Windows
kubectl create rolebinding deployer-pod-reader --clusterrole=view [email protected] -n my-app -
Give a user admin over the whole clusterLinux, macOS, Windows
kubectl create clusterrolebinding deployer-pod-reader --clusterrole=cluster-admin [email protected]Warning: cluster-admin can do anything in every namespace.
-
List role bindings in every namespaceLinux, macOS, Windows
kubectl get rolebindings,clusterrolebindings --all-namespaces
Storage #
-
List persistent volume claimsLinux, macOS, Windows
kubectl get pvc -
List persistent volumesLinux, macOS, Windows
kubectl get pv -
List storage classesLinux, macOS, Windows
kubectl get storageclass -
Show why a volume claim is pendingLinux, macOS, Windows
kubectl describe pvc data-postgres-0 -
Delete a volume claimLinux, macOS, Windows
kubectl delete pvc data-postgres-0Warning: With the usual Delete reclaim policy, the volume and its data are deleted too.
Troubleshooting #
-
Find pods that aren't runningWindows
kubectl get pods --all-namespaces --field-selector=status.phase!=Running,status.phase!=SucceededLinux, macOSkubectl get pods --all-namespaces --field-selector='status.phase!=Running,status.phase!=Succeeded' -
Find pods in CrashLoopBackOffLinux, macOS
kubectl get pods --all-namespaces | grep CrashLoopBackOff -
Show the API calls kubectl makesLinux, macOS, Windows
kubectl get pods -v=6 -
Show the full API requests and responsesLinux, macOS, Windows
kubectl get pods -v=9Warning: The output can include your token. Check it before you share it.
-
Remove a stuck finalizer so a resource can deleteLinux, macOS, Windows
kubectl patch namespace/my-app --type=merge --patch-file=patch.yamlWarning: Skips the clean-up the finalizer was waiting for, which can leave things behind outside the cluster.
-
List the resources left in a namespace that won't deleteLinux, macOS
kubectl api-resources --verbs=list --namespaced -o name | xargs -n 1 kubectl get --show-kind --ignore-not-found -n my-app -
Check a manifest's fields against the clusterLinux, macOS, Windows
kubectl apply -f app.yaml --dry-run=server --validate=strict -
Convert a manifest to a newer API version (kubectl-convert plugin)Linux, macOS, Windows
kubectl convert -f app.yaml --output-version apps/v1