Kubernetes (kubectl) commands

kubectl command lines for Kubernetes v1.37, taken from the Quick Reference and the generated command reference in the Kubernetes documentation and grouped by task: contexts, viewing, creating and applying, rollouts, scaling, logs, exec, debugging, nodes, deleting and output formats. Names such as my-pod, nginx or foo are the documentation's sample values, so replace them with your own. Rows that begin with a dash are flags to add to a command. Plugin, kuberc and certificate commands are left out.

180 commands in 13 sections. Checked row by row against Kubernetes documentation (v1.37): kubectl Quick Reference on . Edited by Jay.

Context and configuration 23

CommandWhat it does
kubectl config viewShow merged kubeconfigPrints the configuration kubectl ends up with after reading every kubeconfig file.
kubectl config view --rawShow kubeconfig with secretsAlso prints certificate data and other sensitive values that the plain view hides.
--minifyLimit view to active contextOption of kubectl config view that drops every entry the context in use does not need.
kubectl config view -o jsonpath='{.users[].name}'Show first kubeconfig userWithout the asterisk the JSONPath expression returns a single user entry.
kubectl config view -o jsonpath='{.users[*].name}'List kubeconfig user namesThe asterisk makes the expression return the name of every user entry.
kubectl config get-contextsList contextsShows each context entry stored in the kubeconfig file.
kubectl config get-contexts -o nameList context names onlyLeaves out every column except the context name.
kubectl config current-contextShow active contextPrints the name of the context that commands are sent to right now.
kubectl config use-context my-cluster-nameSwitch contextMakes my-cluster-name the default for every command that follows.
kubectl config set-context --current --namespace=ggckad-s2Set default namespaceStores the namespace in the active context, so later commands need no -n flag.
kubectl config rename-context old-name new-nameRename a context
kubectl config delete-context minikubeDelete a contextRemoves the minikube context entry from the kubeconfig file.
kubectl config set-cluster my-cluster-nameAdd a cluster entryWrites the named cluster into the kubeconfig file.
kubectl config set-credentials kubeuser/foo.kubernetes.com --username=kubeuser --password=kubepasswordAdd a basic-auth userStores a user entry with a username and password in the kubeconfig.
kubectl config unset users.fooDelete a kubeconfig userRemoves the property users.foo, which is the entry of user foo.
--namespaceTarget a namespaceGlobal flag, short form -n: scopes one request to the given namespace.
--contextUse another context onceGlobal flag naming the kubeconfig context for a single command.
--kubeconfigUse another kubeconfig fileGlobal flag with the path of the file this request should read.
kubectl optionsList global flagsPrints the flags that every kubectl command inherits.
source <(kubectl completion bash)Enable bash completionLoads completion for this shell session only; the bash-completion package has to be present.
source <(kubectl completion zsh)Enable zsh completionLoads completion into the running zsh session only.
alias k=kubectlShorten kubectl to kFollow it with the complete command from the same block to keep completion working.
kubectl versionShow kubectl and cluster versionReports the version of the client and of the server behind the active context.

Viewing and finding resources 18

CommandWhat it does
kubectl get podsList podsOutput is a table limited to the namespace in use.
kubectl get pods --all-namespacesList pods cluster-wideIgnores the namespace of the active context.
-AShort flag for all namespacesEquivalent to --all-namespaces on commands that accept it.
kubectl get pods -o wideList pods with extra columnsAdds details such as the node name to the table.
kubectl get servicesList services
kubectl get deployment my-depShow one deploymentNaming a resource after its type limits the table to that object.
kubectl get pod my-pod -o yamlPrint a pod as YAMLOutputs the complete API object instead of a table row.
kubectl get deployments.apps --namespace backendList in another namespaceReads from namespace backend instead of the one in the active context.
kubectl get pods --show-labelsShow the labels columnWorks for any object type that supports labels, not just pods.
--selectorFilter by labelShort form -l; an object is listed only when all the label constraints match.
kubectl get pods --field-selector=status.phase=RunningList running pods onlyA field selector filters on object fields rather than on labels.
kubectl get node --selector='!node-role.kubernetes.io/control-plane'List worker nodesThe exclamation mark excludes nodes that carry the control-plane role label.
kubectl get services --sort-by=.metadata.nameSort services by nameThe value of --sort-by is a JSONPath to the field used for ordering.
kubectl get pods --sort-by='.status.containerStatuses[0].restartCount'Sort pods by restartsOrders the list by how often the first container of each pod restarted.
--watchWatch for changesShort form -w; kubectl get prints the list once and then keeps reporting updates.
kubectl describe pods my-podDescribe a podPrints a detailed report on the pod, including related events.
kubectl describe nodes my-nodeDescribe a node
kubectl describe pods frontendDescribe pods by name prefixWith no pod called exactly frontend, every pod whose name starts with it is described.

Creating and applying objects 21

Manifests can be written in YAML or JSON; the extensions .yaml, .yml and .json are accepted.

CommandWhat it does
kubectl apply -f ./my-manifest.yamlApply a manifestCreates the resources defined in the file, or updates them when they already exist.
kubectl apply -f ./my1.yaml -f ./my2.yamlApply several filesRepeat -f once for each manifest.
kubectl apply -f ./dirApply a directoryEvery manifest file found in the directory is processed.
kubectl apply -f https://example.com/manifest.yamlApply from a URLThe address is a placeholder domain that holds no real manifest.
kubectl apply -k dir/Apply a kustomizationThe directory has to contain a kustomization.yaml file.
cat pod.json | kubectl apply -f -Apply from standard inputA dash in place of the file name makes kubectl read the piped manifest.
kubectl diff -f ./my-manifest.yamlPreview a manifest's changesCompares the live objects with what applying the file would produce.
--dry-runRun without persistingTakes client or server: client only prints the object, server sends the request but saves nothing.
--server-sideUse server-side applyOption of kubectl apply: the apply runs in the API server rather than in the client.
kubectl create deployment nginx --image=nginxCreate a deploymentStarts one nginx instance under a Deployment named nginx.
kubectl create deployment my-dep --image=nginx --replicas=3Create deployment with replicasThe default is a single replica when --replicas is left out.
kubectl create namespace my-namespaceCreate a namespace
kubectl create configmap my-config --from-literal=key1=config1 --from-literal=key2=config2Create ConfigMap from literalsEach --from-literal adds one key and its value.
kubectl create secret generic my-secret --from-literal=key1=supersecret --from-literal=key2=topsecretCreate secret from literalsUse --from-file instead to load the values from files on disk.
kubectl create secret tls tls-secret --cert=path/to/tls.crt --key=path/to/tls.keyCreate a TLS secretTakes the certificate file and its private key file.
kubectl create job hello --image=busybox:1.28 -- echo "Hello World"Create a jobEverything after the double dash is the command the job's container runs.
kubectl create cronjob hello --image=busybox:1.28 --schedule="*/1 * * * *" -- echo "Hello World"Create a cron jobThe schedule is written in cron syntax; this one fires once a minute.
kubectl create job test-job --from=cronjob/a-cronjobStart job from a CronJobUses the existing cron job a-cronjob as the source of the new job.
kubectl create token myappRequest a service account tokenThe token authenticates to the API server as service account myapp.
kubectl expose deployment nginx --port=80 --target-port=8000Expose a deployment as a serviceThe service listens on port 80 and sends traffic to container port 8000.
kubectl run nginx --image=nginx --dry-run=client -o yaml > pod.yamlGenerate a pod manifestNothing is created in the cluster; the pod spec lands in pod.yaml.

Updating resources and rollouts 20

CommandWhat it does
kubectl set image deployment/frontend www=image:v2Update a container imageChanges the www container of deployment frontend, which starts a rolling update.
kubectl set env deployment/registry STORAGE_DIR=/localSet an environment variableGives deployment registry the new variable STORAGE_DIR with the value /local.
kubectl set env deployments --all --containers="c1" ENV-Remove an environment variableA dash after the variable name deletes it, here from container c1 of all deployments.
kubectl set resources deployment nginx --limits=cpu=200m,memory=512Mi --requests=cpu=100m,memory=256MiSet requests and limitsApplies the CPU and memory values to every container of the deployment.
kubectl rollout status -w deployment/frontendWatch rollout statusFollows the rolling update of deployment frontend until it has finished.
kubectl rollout history deployment/frontendShow rollout historyLists the recorded revisions, which rollout undo can return to.
kubectl rollout undo deployment/frontendRoll back a deploymentReturns to the revision that was live before the latest change.
kubectl rollout undo deployment/frontend --to-revision=2Roll back to a revisionThe number comes from the rollout history of the same deployment.
kubectl rollout restart deployment/frontendRestart a deploymentReplaces the pods of deployment frontend through a rolling restart.
kubectl rollout pause deployment/nginxPause a rolloutWhile paused, changes to the deployment take no effect; what already runs keeps running.
kubectl rollout resume deployment/nginxResume a paused rollout
kubectl label pods my-pod new-label=awesomeAdd a label
kubectl label pods my-pod new-label-Remove a labelThe key followed by a dash deletes that label from the pod.
kubectl label pods my-pod new-label=new-value --overwriteOverwrite a labelWithout --overwrite, an update to a label that already exists is rejected.
kubectl annotate pods my-pod icon-url=http://goo.gl/XXBTWqAdd an annotation
kubectl annotate pods my-pod icon-url-Remove an annotationSame dash suffix as for labels: the key icon-url is deleted.
kubectl edit svc/docker-registryEdit a live resourceOpens service docker-registry in the editor set by KUBE_EDITOR or EDITOR.
KUBE_EDITOR="nano" kubectl edit svc/docker-registryEdit with another editorThe KUBE_EDITOR variable picks the editor for this one command.
kubectl patch node k8s-node-1 -p '{"spec":{"unschedulable":true}}'Patch a resourceChanges only the fields named in the patch, here marking the node unschedulable.
kubectl replace --force -f ./pod.jsonForce replace a resourceDeletes the object and builds it again from the file, which interrupts the service.

Scaling resources 6

CommandWhat it does
kubectl scale --replicas=3 rs/fooScale a ReplicaSetSets the desired replica count of foo to three.
kubectl scale --replicas=3 -f foo.yamlScale resource from a fileThe type and name of the resource are read from foo.yaml.
kubectl scale --current-replicas=2 --replicas=3 deployment/mysqlScale with a preconditionNothing changes unless mysql has exactly two replicas at that moment.
kubectl scale --replicas=5 rc/foo rc/bar rc/bazScale several controllersOne command sets the same replica count on all three replication controllers.
kubectl autoscale deployment foo --min=2 --max=10Autoscale a deploymentKeeps 2 to 10 pods; with no CPU target given, the default autoscaling policy applies.
kubectl autoscale rc foo --max=5 --cpu=80%Autoscale on a CPU targetAims at 80% CPU utilization with at most five pods.

Logs 13

CommandWhat it does
kubectl logs my-podPrint pod logsDumps what the pod's container has written to stdout so far.
kubectl logs -f my-podStream pod logsThe -f flag, long form --follow, keeps printing lines as they arrive.
kubectl logs my-pod --previousLogs of the previous containerShows output from the container instance that ran before the one running now.
kubectl logs my-pod -c my-containerLogs of one containerNeeded for a pod with several containers; with a single container the name is optional.
kubectl logs my-pod -c my-container --previousPrevious logs of one containerCombines the container name with the earlier instance of that container.
kubectl logs -f my-pod -c my-containerStream one container's logs
kubectl logs -l name=myLabelLogs by labelSelects pods through the label name=myLabel rather than a pod name.
kubectl logs -l name=myLabel -c my-containerContainer logs by label
kubectl logs -f -l name=myLabel --all-containersStream logs by labelFollows every container of every pod that carries the label.
kubectl logs deploy/my-deploymentLogs of a deploymentAddresses the pod through its Deployment; fits pods with a single container.
kubectl logs deploy/my-deployment -c my-containerDeployment logs of one container
kubectl logs --tail=20 nginxShow the last log linesLimits output to the 20 newest lines of pod nginx.
kubectl logs --since=1h nginxShow recent logsAccepts a relative duration such as 5s, 2m or 3h.

Exec, attach and run 10

When the command you run in the pod has flags of its own, put two dashes before it, and do not wrap the command in quotes.

CommandWhat it does
kubectl exec my-pod -- ls /Run a command in a podWorks as is for a pod with one container; the command follows the double dash.
kubectl exec --stdin --tty my-pod -- /bin/shOpen a shell in a podThe two flags, -i and -t in short form, connect your terminal to the shell.
kubectl exec my-pod -c my-container -- ls /Run command in one containerThe -c flag chooses the container when the pod holds several.
kubectl exec mypod -c ruby-container -i -t -- bash -ilOpen bash in a containerPuts the terminal in raw mode and wires stdin and stdout to bash in ruby-container.
kubectl exec deploy/my-deployment -- lsRun command via a deploymentkubectl picks the first pod of the deployment and its first container.
kubectl attach my-pod -iAttach to a running containerConnects to the process already running in the pod and passes your stdin to it.
kubectl run -i --tty busybox --image=busybox:1.28 -- shStart a pod with a shellCreates a busybox pod and attaches your terminal to sh inside it.
kubectl run nginx --image=nginx -n mynamespaceStart a pod in a namespaceRuns a single nginx pod in mynamespace instead of the default one.
kubectl run -i -t busybox --image=busybox --restart=NeverRun a pod in the foregroundWith --restart=Never the pod is not started again once it exits.
--rmDelete the pod when it exitsOption of kubectl run, valid only when attaching, for example together with -i.

Copying files and port forwarding 12

kubectl cp needs the tar binary inside the container image; without it the copy fails.

CommandWhat it does
kubectl cp /tmp/foo_dir my-pod:/tmp/bar_dirCopy a directory into a podSource is a local directory, target a path in a pod of the namespace in use.
kubectl cp /tmp/foo my-pod:/tmp/bar -c my-containerCopy a file into one container
kubectl cp /tmp/foo my-namespace/my-pod:/tmp/barCopy into a pod elsewherePrefix the pod with its namespace and a slash.
kubectl cp my-namespace/my-pod:/tmp/foo /tmp/barCopy a file out of a podWith the pod path first, the file travels from the container to your machine.
kubectl exec -n my-namespace my-pod -- tar cf - /tmp/foo | tar xf - -C /tmp/barCopy out with tarStreams a tar archive through exec, for cases kubectl cp does not handle.
tar cf - /tmp/foo | kubectl exec -i -n my-namespace my-pod -- tar xf - -C /tmp/barCopy in with tarThe reverse direction: a local archive is unpacked inside the pod.
kubectl port-forward my-pod 5000:6000Forward a local port to a podThe first number is the port on your machine, the second the port in the pod.
kubectl port-forward svc/my-service 5000Forward to a serviceA single number is used for both the local and the remote side.
kubectl port-forward svc/my-service 5000:my-service-portForward to a named service portThe target can be the name of a port instead of its number.
kubectl port-forward deploy/my-deployment 5000:6000Forward to a deployment's podTraffic goes to a pod that the deployment created.
kubectl port-forward --address 0.0.0.0 pod/mypod 8888:5000Forward on all addressesBy default only localhost is bound; --address changes the listening addresses.
kubectl port-forward pod/mypod :5000Forward from a random local portLeaving the local side empty lets kubectl choose a free port.

Debugging and access checks 12

CommandWhat it does
kubectl debug my-pod -it --image=busybox:1.28Debug a running podStarts a busybox debugging container inside my-pod and attaches to it at once.
kubectl debug node/my-node -it --image=busybox:1.28Debug a nodeThe debug container runs in the host namespaces, with the node's filesystem mounted at /host.
kubectl debug mypod -it --image=busybox --copy-to=my-debuggerDebug a copy of a podWorks on a copy of mypod named my-debugger, to which the debug container is added.
kubectl events --types=WarningList warning eventsFilters the event list down to entries of type Warning.
kubectl events --for pod/web-pod-13je7 --watchWatch events of one resourceShows recent events of that pod, then keeps printing new ones as they occur.
kubectl top podShow pod metricsCovers every pod of the default namespace.
kubectl top pod POD_NAME --containersShow metrics per containerBreaks the usage of one pod down by its containers.
kubectl top pod POD_NAME --sort-by=cpuSort pod metricsThe sort field is either cpu or memory.
kubectl wait --for=condition=Ready pod/busybox1Wait until a pod is readyBlocks until the pod reports the Ready condition or the timeout, 30 seconds by default, passes.
kubectl auth can-i create pods --all-namespacesCheck a permissionAnswers whether your user may create pods in any namespace.
kubectl auth can-i --list --namespace=fooList allowed actionsPrints everything your user may do in namespace foo.
kubectl auth whoamiShow who you are logged in asReturns the subject attributes the API server sees for your credentials.

Nodes and cluster 13

CommandWhat it does
kubectl cordon my-nodeCordon a nodeMarks my-node unschedulable, so no new pods are placed on it.
kubectl drain my-nodeDrain a nodeMarks my-node unschedulable and evicts its pods ahead of maintenance.
--ignore-daemonsetsSkip DaemonSet pods while drainingOption of kubectl drain for nodes that run pods managed by a DaemonSet.
--delete-emptydir-dataDrain despite emptyDir dataOption of kubectl drain; the local emptyDir data of evicted pods is lost.
kubectl uncordon my-nodeUncordon a nodeMakes my-node schedulable again after a cordon or drain.
kubectl taint nodes foo dedicated=special-user:NoScheduleTaint a nodeAn existing taint with the same key and effect gets the new value.
kubectl taint nodes foo dedicated:NoSchedule-Remove a taintThe trailing dash deletes the taint with that key and effect from node foo.
kubectl get nodes -o='custom-columns=NodeName:.metadata.name,TaintKey:.spec.taints[*].key,TaintValue:.spec.taints[*].value,TaintEffect:.spec.taints[*].effect'List taints per nodeCustom columns print the key, value and effect of each node's taints.
kubectl top nodeShow node metrics
kubectl top node my-nodeShow metrics of one node
kubectl cluster-infoShow cluster endpointsPrints the address of the control plane and of the cluster services.
kubectl cluster-info dumpDump cluster stateWithout options the whole dump goes to stdout.
kubectl cluster-info dump --output-directory=/path/to/cluster-stateDump cluster state to filesCreates a directory tree with the dump under the given path.

Deleting resources 9

CommandWhat it does
kubectl delete -f ./pod.jsonDelete what a file definesThe type and name of the object are read from pod.json.
kubectl delete pod unwanted --nowDelete a pod immediately--now is the same as a grace period of one second.
kubectl delete pod,service baz fooDelete by type and nameRemoves the pods and the services called baz and foo.
kubectl delete pods,services -l name=myLabelDelete by labelOnly objects that carry the label name=myLabel are removed.
kubectl -n my-ns delete pod,svc --allDelete all in a namespaceRemoves every pod and service of namespace my-ns.
kubectl delete pods --allDelete all podsActs on the namespace in use; add --interactive to be asked first.
kubectl delete pod foo --forceForce delete a podIntended for pods stuck on a node that is down; kubectl does not wait for their processes to end.
--grace-periodSet the termination grace periodSeconds a resource gets to shut down; 0 is allowed only together with --force.
--cascadeChoose the cascading strategyTakes background, orphan or foreground and decides what happens to dependents such as pods.

Resource types 11

CommandWhat it does
kubectl api-resourcesList resource typesShows each supported type with its short names, API group and whether it is namespaced.
kubectl api-resources --namespaced=trueList namespaced types
kubectl api-resources --namespaced=falseList cluster-scoped typesThese are the types that do not live inside a namespace.
kubectl api-resources -o nameList type names onlySimple output with nothing but the resource name.
kubectl api-resources -o wideList types with more columnsExpanded output with more information on each type.
kubectl api-resources --verbs=list,getList types by supported verbsKeeps only types that allow both the list and the get request.
kubectl api-resources --api-group=extensionsList types of one API group
kubectl api-versionsList API versionsPrints what the server supports as group/version pairs.
kubectl explain podsShow documentation of a typeDescribes the resource and the fields a pod manifest may contain.
kubectl explain pods.spec.containersShow documentation of a fieldFields are addressed with dots, starting at the resource type.
kubectl explain pods --recursiveShow all fields of a typePrints the whole field tree; --max-depth caps how deep it goes.

Output formats and verbosity 12

-o is the short form of --output and works on every command that supports output formats.

CommandWhat it does
-o=jsonOutput as JSONPrints the API object in JSON instead of the default table.
-o=yamlOutput as YAML
-o=kyamlOutput as KYAMLKYAML is a Kubernetes dialect of YAML that ordinary YAML parsers can read.
-o=nameOutput names onlyNothing besides the resource name is printed.
kubectl get pods -A -o=custom-columns='DATA:spec.containers[*].image'List images with custom columnsPrints one column, DATA, holding the images of every pod in the cluster.
kubectl get pods --selector=app=cassandra -o jsonpath='{.items[*].metadata.labels.version}'Extract a field with JSONPathReturns only the version label of the pods that match app=cassandra.
kubectl get configmap myconfig -o jsonpath='{.data.ca\.crt}'Read a key that contains dotsA backslash before the dot keeps JSONPath from splitting the key ca.crt.
kubectl get secret my-secret -o go-template='{{range $k,$v := .data}}{{"### "}}{{$k}}{{"\n"}}{{$v|base64decode}}{{"\n\n"}}{{end}}'Print a decoded secretThe Go template decodes each value itself, so no external tool is needed.
--no-headersHide the header rowOption of kubectl get for the default table and for custom columns.
--v=6Log requested resourcesVerbosity is set with -v or --v followed by a log level number.
--v=8Log HTTP request contentsAt this level long request bodies are still truncated.
--v=9Log full request contentsHighest level in the table: bodies are printed without truncation.

Notes

Looking

kubectl get pods and kubectl get services list the basic objects of the namespace in use; kubectl get pods -o wide adds details such as the node name, and kubectl get pods --all-namespaces looks across the whole cluster. When a pod is not behaving, kubectl describe pods my-pod prints a detailed report that includes related events. kubectl logs my-pod shows the container's output and kubectl logs -f my-pod follows it; add -c with a container name for multi-container pods and --previous for the instance that ran before.

Changing

kubectl apply -f ./my-manifest.yaml creates or updates whatever a manifest describes; the Kubernetes documentation recommends it for managing applications in production, and it also accepts a directory or a URL. kubectl diff -f ./my-manifest.yaml shows beforehand what an apply would change. kubectl scale --replicas=3 rs/foo changes a replica count, and kubectl rollout restart deployment/frontend replaces the pods of a deployment through a rolling restart. kubectl exec --stdin --tty my-pod -- /bin/sh opens a shell inside a container, and kubectl port-forward my-pod 5000:6000 listens on a local port and forwards it to a port of the pod.

Where am I

kubectl config get-contexts lists the contexts of the kubeconfig and kubectl config current-context names the one in use; kubectl config use-context my-cluster-name switches. Check it before a delete or a drain, because every command goes to the active context. kubectl config set-context --current --namespace=ggckad-s2 saves a namespace in that context so later commands need no -n; for a single command, --namespace and --context do the same without changing the kubeconfig.

Questions

How do I list all pods in Kubernetes?

Use kubectl get pods for the namespace in use, or kubectl get pods --all-namespaces for every namespace; -A is the short form of that flag.

How do I get a shell inside a running pod?

Use kubectl exec --stdin --tty my-pod -- /bin/sh with the name of your own pod; the short flags are -i and -t. When the pod has several containers, name one with -c, as in kubectl exec mypod -c ruby-container -i -t -- bash -il.

How do I scale a deployment?

Use kubectl scale with --replicas and the resource as type/name, for example kubectl scale --current-replicas=2 --replicas=3 deployment/mysql, which scales the mysql deployment to 3 only if it currently has 2 replicas. Leave --current-replicas out to scale unconditionally, as in kubectl scale --replicas=3 rs/foo.

How do I follow pod logs in real time with kubectl?

Run kubectl logs -f my-pod, with the name of your own pod at the end. The -f flag (--follow) streams the log, printing new lines as they are written, until you stop the command with Ctrl and C. Without it kubectl prints the current log and exits.

When the pod has more than one container, name the one you want: kubectl logs -f my-pod -c my-container. Add --tail=20 to start from the last 20 lines, -n for a pod in another namespace, and --previous to read the log of the container instance that ran before a restart.

How do I port-forward to a pod with kubectl?

Run kubectl port-forward my-pod 5000:6000. The first number is the local port and the second is the port in the pod, so connections to localhost:5000 reach port 6000 in the pod. A single number uses the same port on both sides.

The command does not return: forwarding lasts only while it runs, so open a second terminal for other work. It listens on localhost unless --address is given. kubectl port-forward svc/my-service 5000 picks a pod through a Service instead; when that pod terminates the session ends and the command has to be run again.

Sources and checks

Every row on this page was matched to a line in the documentation above on . A binding that could not be found there is not listed.

Found a wrong or missing key? Tell us and it gets checked against the source. How we verify describes the process and its limits.