Skip to content
xt-tools

Kubernetes cheatsheet

Searchable reference of kubectl commands for pods, deployments, services, logs and debugging.

142 of 142 commands

kubectl commands
SectionCommandDescription
Config & contextkubectl config get-contextsList contexts in your kubeconfig; the current one is marked with *.
Config & contextkubectl config current-contextPrint the current context.
Config & contextkubectl config use-context <context>Switch to another cluster or user.
Config & contextkubectl config set-context --current --namespace=<namespace>Change the default namespace of the context.
Config & contextkubectl config view --minifyShow only the configuration of the current context.
Config & contextkubectl config rename-context <old> <new>Rename a context.
Config & contextkubectl config delete-context <context>Remove a context from the kubeconfig.
Config & contextKUBECONFIG=<file1>:<file2> kubectl config view --flatten > <merged>Merge several kubeconfig files into one.
Config & contextkubectl --context <context> get podsRun one command against another context.
Config & contextkubectl cluster-infoShow the API server and core service addresses.
Config & contextkubectl versionClient and server versions.
Config & contextkubectl api-resourcesList resource types with their short names and API groups.
Config & contextkubectl explain <resource>.specDocument the fields of a resource, e.g. pod.spec.containers.
Config & contextkubectl explain deployment --recursiveShow the full field tree of a resource.
Config & contextsource <(kubectl completion bash)Enable shell completion (also zsh, fish, powershell).
Get & describekubectl get podsList pods in the current namespace.
Get & describekubectl get pods -AList pods in every namespace.
Get & describekubectl get pods -n <namespace>List pods in a given namespace.
Get & describekubectl get pods -o wideInclude node, pod IP and more columns.
Get & describekubectl get pods -wWatch for changes.
Get & describekubectl get allList common resources: pods, services, deployments, replica sets, jobs.
Get & describekubectl get deploy,svc,ingressList several resource types at once.
Get & describekubectl get pods -l app=<name>Filter by label.
Get & describekubectl get pods --field-selector status.phase=RunningFilter by a field.
Get & describekubectl get pods --sort-by=.metadata.creationTimestampSort by a field, oldest first.
Get & describekubectl get namespacesList namespaces.
Get & describekubectl get crdList CustomResourceDefinitions.
Get & describekubectl describe pod <pod>Detailed state of a pod, including recent events.
Get & describekubectl describe deployment <name>Detailed state of a deployment and its rollout.
Get & describekubectl describe svc <service>Show the selector, ports and endpoints of a service.
Apply & deletekubectl apply -f <file>.yamlCreate or update resources from a manifest.
Apply & deletekubectl apply -f <dir>/Apply every manifest in a directory (add -R for subdirectories).
Apply & deletekubectl apply -k <dir>Apply a kustomization.
Apply & deletekubectl apply --server-side -f <file>.yamlServer-side apply with field ownership tracking.
Apply & deletekubectl diff -f <file>.yamlShow what apply would change.
Apply & deletekubectl apply -f <file>.yaml --dry-run=serverValidate against the API server without saving.
Apply & deletekubectl create deployment <name> --image=<image>Create a deployment imperatively.
Apply & deletekubectl create deployment <name> --image=<image> --dry-run=client -o yaml > <file>.yamlGenerate a manifest skeleton without creating anything.
Apply & deletekubectl expose deployment <name> --port=80 --target-port=8080Create a service for a deployment.
Apply & deletekubectl run <name> --image=<image>Start a single pod.
Apply & deletekubectl create namespace <namespace>Create a namespace.
Apply & deletekubectl create job <name> --from=cronjob/<cronjob>Run a CronJob now as a one-off job.
Apply & deletekubectl edit deployment <name>Edit a live resource in your editor.
Apply & deletekubectl patch deployment <name> -p '{"spec":{"replicas":2}}'Patch fields of a live resource.
Apply & deletekubectl replace --force -f <file>.yamlDelete and recreate a resource from a manifest.
Apply & deletekubectl delete -f <file>.yamlDelete the resources defined in a manifest.
Apply & deletekubectl delete pod <pod>Delete a pod; its controller creates a new one.
Apply & deletekubectl delete pods -l app=<name>Delete every pod with a label.
Apply & deletekubectl delete pod <pod> --grace-period=0 --forceRemove a stuck pod immediately. Use with care.
Apply & deletekubectl delete namespace <namespace>Delete a namespace and everything in it.
Logs, exec & port-forwardkubectl logs <pod>Print the logs of a pod’s container.
Logs, exec & port-forwardkubectl logs -f <pod>Follow the logs.
Logs, exec & port-forwardkubectl logs <pod> -c <container>Logs of one container in a multi-container pod.
Logs, exec & port-forwardkubectl logs <pod> --previousLogs of the previous, crashed instance of the container.
Logs, exec & port-forwardkubectl logs <pod> --since=1h --tail=100Only recent lines.
Logs, exec & port-forwardkubectl logs <pod> --timestampsPrefix each line with its timestamp.
Logs, exec & port-forwardkubectl logs deploy/<name>Logs of one pod of a deployment.
Logs, exec & port-forwardkubectl logs -l app=<name> --all-containers --prefixLogs of every pod with a label, prefixed with the source.
Logs, exec & port-forwardkubectl exec -it <pod> -- shOpen a shell in a pod.
Logs, exec & port-forwardkubectl exec -it <pod> -c <container> -- shOpen a shell in a specific container.
Logs, exec & port-forwardkubectl exec <pod> -- envRun one command in a pod.
Logs, exec & port-forwardkubectl port-forward <pod> 8080:80Forward local port 8080 to port 80 of a pod.
Logs, exec & port-forwardkubectl port-forward svc/<service> 8080:80Forward to a pod behind a service.
Logs, exec & port-forwardkubectl port-forward --address 0.0.0.0 <pod> 8080:80Listen on every local interface, not only localhost.
Logs, exec & port-forwardkubectl cp <pod>:<path> <local-path>Copy files out of a pod (needs tar in the container).
Logs, exec & port-forwardkubectl cp <local-path> <pod>:<path>Copy files into a pod.
Logs, exec & port-forwardkubectl attach -it <pod>Attach to the main process of a running container.
Logs, exec & port-forwardkubectl proxyProxy the API server on localhost port 8001 using your credentials.
Debug & troubleshootkubectl debug -it <pod> --image=busybox --target=<container>Add an ephemeral debug container that shares the target’s process namespace.
Debug & troubleshootkubectl debug <pod> -it --copy-to=<pod>-debug --container=<container> -- shDebug a copy of the pod with a shell in place of the container command.
Debug & troubleshootkubectl debug node/<node> -it --image=busyboxShell on a node; its filesystem is mounted at /host.
Debug & troubleshootkubectl run tmp --rm -it --image=busybox --restart=Never -- shThrowaway pod for testing DNS or connectivity.
Debug & troubleshootkubectl get events --sort-by=.lastTimestampRecent events in the namespace, newest last.
Debug & troubleshootkubectl events --for pod/<pod>Events about one object.
Debug & troubleshootkubectl get pods -A --field-selector=status.phase!=RunningFind pods that are not running.
Debug & troubleshootkubectl top podsCPU and memory use per pod (needs metrics-server).
Debug & troubleshootkubectl top pod <pod> --containersCPU and memory use per container.
Debug & troubleshootkubectl top nodesCPU and memory use per node.
Debug & troubleshootkubectl get endpointslices -l kubernetes.io/service-name=<service>Check that a service has ready endpoints.
Debug & troubleshootkubectl wait --for=condition=Ready pod -l app=<name> --timeout=120sBlock until pods are ready.
Debug & troubleshootkubectl auth can-i create deploymentsCheck whether you may perform an action.
Debug & troubleshootkubectl auth can-i --list --as=system:serviceaccount:<namespace>:<sa>List what a service account is allowed to do.
Debug & troubleshootkubectl auth whoamiShow the user and groups the API server sees for you.
Debug & troubleshootkubectl get pod <pod> -o yamlFull spec and status, including container state and exit codes.
Rolloutkubectl rollout status deployment/<name>Wait for a rollout to finish.
Rolloutkubectl rollout history deployment/<name>List revisions of a deployment.
Rolloutkubectl rollout history deployment/<name> --revision=2Show the pod template of one revision.
Rolloutkubectl rollout undo deployment/<name>Roll back to the previous revision.
Rolloutkubectl rollout undo deployment/<name> --to-revision=2Roll back to a specific revision.
Rolloutkubectl rollout restart deployment/<name>Recreate all pods with a rolling restart.
Rolloutkubectl rollout pause deployment/<name>Pause a rollout to batch several changes.
Rolloutkubectl rollout resume deployment/<name>Resume a paused rollout.
Rolloutkubectl set image deployment/<name> <container>=<image>:<tag>Update a container image, starting a rollout.
Rolloutkubectl set env deployment/<name> KEY=valueSet an environment variable on a deployment.
Rolloutkubectl set resources deployment/<name> -c <container> --limits=cpu=500m,memory=256MiSet resource limits (or --requests).
Rolloutkubectl annotate deployment/<name> kubernetes.io/change-cause="<reason>"Record why a revision was made; shown in rollout history.
Scalekubectl scale deployment/<name> --replicas=3Set the number of replicas.
Scalekubectl scale statefulset/<name> --replicas=0Stop all pods of a StatefulSet, keeping its volumes.
Scalekubectl autoscale deployment/<name> --min=2 --max=10 --cpu-percent=80Create a HorizontalPodAutoscaler that targets 80% CPU (needs metrics-server).
Scalekubectl get hpaList autoscalers with current and target metrics.
Scalekubectl describe hpa <name>Show autoscaler conditions and scaling events.
Labels & annotationskubectl get pods --show-labelsShow all labels as a column.
Labels & annotationskubectl get pods -L app,envShow the values of specific labels as columns.
Labels & annotationskubectl label pod <pod> env=prodAdd a label.
Labels & annotationskubectl label pod <pod> env=staging --overwriteChange an existing label.
Labels & annotationskubectl label pod <pod> env-Remove a label (trailing minus).
Labels & annotationskubectl get pods -l 'env in (prod,staging)'Set-based selector.
Labels & annotationskubectl get pods -l 'app=<name>,tier!=db'Combine selectors; all must match.
Labels & annotationskubectl annotate pod <pod> note="<text>"Add an annotation.
Labels & annotationskubectl annotate pod <pod> note-Remove an annotation.
Output formatskubectl get pods -o yamlFull objects as YAML.
Output formatskubectl get pods -o jsonFull objects as JSON.
Output formatskubectl get pods -o nameOnly <type>/<name>, handy for piping into other commands.
Output formatskubectl get pods --no-headersOmit the header row.
Output formatskubectl get pods -o jsonpath='{.items[*].metadata.name}'Extract one field from every item.
Output formatskubectl get pods -o jsonpath='{range .items[*]}{.metadata.name}{"\t"}{.status.phase}{"\n"}{end}'One line per item with tab-separated fields.
Output formatskubectl get pods -o jsonpath='{.items[?(@.status.phase=="Running")].metadata.name}'Filter items inside a JSONPath expression.
Output formatskubectl get pods -o custom-columns=NAME:.metadata.name,IMAGE:.spec.containers[*].imageChoose your own columns.
Output formatskubectl get pods -o json | jq -r '.items[].metadata.name'Post-process JSON with jq.
Nodeskubectl get nodes -o wideList nodes with IPs, OS image and container runtime.
Nodeskubectl get nodes -L topology.kubernetes.io/zoneShow the zone of each node.
Nodeskubectl describe node <node>Capacity, allocated resources, conditions and taints.
Nodeskubectl get pods -A --field-selector spec.nodeName=<node>List the pods running on a node.
Nodeskubectl cordon <node>Mark a node unschedulable; running pods stay.
Nodeskubectl drain <node> --ignore-daemonsets --delete-emptydir-dataEvict pods before maintenance.
Nodeskubectl uncordon <node>Allow scheduling on the node again.
Nodeskubectl taint nodes <node> key=value:NoScheduleOnly pods that tolerate the taint will be scheduled.
Nodeskubectl taint nodes <node> key=value:NoSchedule-Remove a taint.
Nodeskubectl label nodes <node> disktype=ssdLabel a node for nodeSelector or affinity rules.
Secrets & ConfigMapskubectl create secret generic <name> --from-literal=password=<value>Create a secret from a literal.
Secrets & ConfigMapskubectl create secret generic <name> --from-file=<file>Create a secret with a file as a key.
Secrets & ConfigMapskubectl create secret generic <name> --from-env-file=.envOne key per line of a .env file.
Secrets & ConfigMapskubectl create secret docker-registry <name> --docker-server=<registry> --docker-username=<user> --docker-password=<token>Credentials for pulling private images (imagePullSecrets).
Secrets & ConfigMapskubectl create secret tls <name> --cert=tls.crt --key=tls.keyTLS secret, e.g. for an Ingress.
Secrets & ConfigMapskubectl get secret <name> -o jsonpath='{.data.<key>}' | base64 -dDecode one value of a secret.
Secrets & ConfigMapskubectl create secret generic <name> --from-literal=<key>=<value> --dry-run=client -o yaml | kubectl apply -f -Create or update a secret idempotently.
Secrets & ConfigMapskubectl create configmap <name> --from-literal=KEY=valueCreate a ConfigMap from a literal.
Secrets & ConfigMapskubectl create configmap <name> --from-file=<file>Create a ConfigMap from a file.
Secrets & ConfigMapskubectl get configmap <name> -o yamlShow the contents of a ConfigMap.
Secrets & ConfigMapskubectl set env deployment/<name> --from=configmap/<name>Import every key of a ConfigMap as env variables.
Secrets & ConfigMapskubectl create serviceaccount <name>Create a service account.
Secrets & ConfigMapskubectl create token <serviceaccount>Issue a short-lived token for a service account.