kubectl commands cheat sheet
Version and kubeconfig file
-
kubectl version --clientShows only the kubectl version, without contacting the cluster. Without --client, the version of the cluster's API server is shown too.
-
export KUBECONFIG=/etc/kubernetes/admin.confOn a cluster set up with kubeadm, as the root user: points kubectl to the cluster's admin file. The file grants full administrator permissions, so never share it.
-
kubectl --kubeconfig /etc/rancher/k3s/k3s.yaml get nodesRuns a command with a specific kubeconfig file, for example the k3s admin file. The --kubeconfig option uses only the file you specify, without merging it with other files.
-
export KUBECONFIG=$HOME/.kube/config:$HOME/.kube/dev-configSets several kubeconfig files together, separated by colons. kubectl merges them, and the first file that sets a value determines it.
-
kubectl config view --minifyShows only the settings of the current context: the cluster, the user, and the namespace. Certificate and key data is hidden.
-
kubectl config view --rawCaution: shows the settings including the full certificate, key, and password data. Never copy the output to a shared place.
Contexts
-
kubectl config get-contextsLists all the contexts in the kubeconfig file. Each context combines a cluster, a user, and a namespace, and the active context is marked with an asterisk.
-
kubectl config current-contextShows the name of the active context. When you work with several clusters, run it before a command that changes resources.
-
kubectl config use-context my-clusterSwitches to the my-cluster context, and all the following commands go to its cluster.
Cluster, nodes, and resource types
-
kubectl cluster-infoShows the address of the cluster's API server and of the system services. When the command succeeds, the connection to the cluster works.
-
kubectl get nodes -o wideLists the nodes in the cluster with the status of each node, the internal and external addresses, the operating system, and the kubelet version.
-
kubectl describe node node1Shows full details about the node1 node: its conditions, the available resources, the Pods running on it, and the latest events.
-
kubectl get node --selector='!node-role.kubernetes.io/control-plane'Lists only the worker nodes, without the control plane nodes.
-
kubectl api-resourcesLists all the resource types the cluster knows, with the short name of each type, for example svc for services, and whether the type belongs to a namespace.
-
kubectl explain pods.spec.containersShows the documentation of a field in the configuration file, with the description and type of each field. Convenient for writing YAML files without searching online.
-
kubectl explain deployment --recursiveShows all the fields of the resource, including nested fields, as a tree.
Namespaces
-
kubectl get namespacesLists the namespaces in the cluster. A new cluster has default, kube-system, kube-public, and kube-node-lease.
-
kubectl create namespace shopCreates a namespace named shop. The name can contain only lowercase letters, digits, and hyphens, and it shouldn't start with kube-, which is used by the system.
-
kubectl get pods -n shopRuns the command in the namespace named shop. Without -n, the command runs in the namespace of the current context, usually default.
-
kubectl get pods -ALists the Pods in all namespaces, with a column for the namespace name. The long form of the option is --all-namespaces.
-
kubectl config set-context --current --namespace=shopSets shop as the default namespace of the current context, so you don't need to specify -n in every command.
-
kubectl config view --minify | grep namespace:Shows the namespace set in the current context. When there is no output, commands run in default.
-
kubectl delete namespace shopCaution: deletes the namespace together with all the resources in it, including Deployments, Services, Secrets, and the data that depends on them. The deletion runs in the background, and meanwhile the namespace shows the Terminating status.
Viewing resources
-
kubectl get pods -o wideLists the Pods with additional details, such as the IP address of each Pod and the node it runs on.
-
kubectl get deployments,servicesLists several resource types in one command, as a comma-separated list.
-
kubectl get ingress -ALists the Ingress resources in all namespaces, with their hosts and addresses.
-
kubectl get deployment web -o yamlShows the full configuration of the Deployment named web in YAML format, including the status field. The -o json option shows it in JSON format.
-
kubectl get pods -wLists the Pods and keeps watching for changes, for example while a new version is being deployed. Pressing Ctrl+C stops watching.
-
kubectl describe pod my-podShows full details about the Pod: the state of each container, the reason for the last termination, the environment variables, the volumes, and the latest events. This is the first command to run for a Pod that doesn't start.
Logs, shell access, and copying files
-
kubectl logs -f --tail=50 my-podShows the last 50 lines of the Pod's log and keeps showing new lines in real time.
-
kubectl logs --since=1h my-podShows only the log lines from the last hour. You can also specify minutes or seconds, for example 30m or 10s.
-
kubectl logs my-pod --previousShows the log of the previous instance of the container, before it restarted. Useful when a container crashes and starts again, and the current log doesn't show the error.
-
kubectl logs my-pod -c my-containerShows the log of a specific container, in a Pod that has several containers.
-
kubectl logs deploy/webShows the log of one of the Pods of the Deployment named web, without having to look up the full name of the Pod.
-
kubectl logs -l app=web --all-containersShows the logs of all the Pods with the app=web label and of all their containers. With a label selector, the last 10 lines of each Pod are shown by default.
-
kubectl exec -it my-pod -- shOpens a shell in the running container of the Pod. Everything after -- is passed to the container, and when the image includes bash, you can run it instead of sh.
-
kubectl exec deploy/web -- envRuns a command in the first container of one of the Pods of the Deployment, here to show the environment variables.
-
kubectl port-forward svc/web 8080:80Forwards port 8080 on the computer running kubectl to port 80 of the Service named web, for testing without exposing it to the internet. By default, the forwarding listens only on localhost, and the --address 0.0.0.0 option opens it on all the computer's addresses and exposes the service to the network.
-
kubectl cp ./config.json my-pod:/tmp/config.jsonCopies a file from the server to the Pod's container. The command requires the tar tool to be present in the container image.
-
kubectl cp shop/my-pod:/tmp/app.log ./app.logCopies a file from a Pod in the namespace named shop to the current folder on the server.
Applying and deleting configuration files
-
kubectl apply -f deployment.yamlCreates the resources in the file, or updates them when they already exist. This is the common way to manage a cluster from YAML files.
-
kubectl apply -f ./k8s/Applies all the configuration files in the k8s folder.
-
kubectl apply -k ./overlays/prodApplies the configuration produced by the kustomization.yaml file in the folder, for example base settings with changes for the production server.
-
kubectl diff -f deployment.yamlShows the differences between the current state of the cluster and the state after applying the file, without changing anything. Exit code 0 means there are no differences, and 1 means differences were found.
-
kubectl apply -f deployment.yaml --dry-run=serverSends the file to the API server for validation, without saving the changes. This way, configuration errors are found before you apply it.
-
kubectl delete -f deployment.yamlCaution: deletes all the resources defined in the file. When the file includes a PersistentVolumeClaim, its data may be deleted, depending on the storage policy.
-
kubectl delete pod my-podDeletes a Pod. When the Pod belongs to a Deployment, a new Pod is created in its place, so this is also a common way to restart a stuck Pod.
Deployments, updates, and rollbacks
-
kubectl create deployment web --image=nginx --replicas=2 --port=80Creates a Deployment named web with two Pods from the nginx image, which expose port 80 of the container.
-
kubectl create deployment web --image=nginx --dry-run=client -o yaml > web.yamlGenerates a Deployment YAML file without sending it to the cluster. Convenient as a starting point for a configuration file that you edit and then apply with kubectl apply.
-
kubectl scale deployment/web --replicas=3Changes the number of Pods of the Deployment to three. When the Deployment is managed from a YAML file, also update the replicas field in the file, so the next apply doesn't restore the previous value.
-
kubectl set image deployment/web nginx=nginx:1.27Updates the image of the container named nginx in the Deployment and starts a gradual replacement of the Pods. The name before the = sign is the container name, not the image name.
-
kubectl rollout status deployment/webFollows the Deployment update until it finishes, and shows how many Pods have already been updated. The --timeout option limits the waiting time, for example in a deployment script.
-
kubectl rollout history deployment/webLists the revisions of the Deployment. The --revision=2 option shows the configuration of a specific revision.
-
kubectl rollout undo deployment/webRolls the Deployment back to the previous revision, for example after an update that caused a problem.
-
kubectl rollout undo deployment/web --to-revision=2Rolls the Deployment back to a specific revision from the history.
-
kubectl rollout restart deployment/webRestarts all the Pods of the Deployment gradually, without taking the service down. Useful after a change to a ConfigMap or a Secret that the application reads only at startup.
-
kubectl expose deployment web --port=80 --target-port=8080Creates a Service of type ClusterIP, which receives traffic on port 80 and forwards it to port 8080 in the containers of the Deployment.
-
kubectl expose deployment web --type=NodePort --port=80Creates a Service of type NodePort, which is reachable from outside the cluster through a fixed port on every node. The port number appears in the output of kubectl get svc web.
ConfigMaps and Secrets
-
kubectl create configmap app-config --from-literal=APP_ENV=production --from-literal=LOG_LEVEL=infoCreates a ConfigMap with two values. You can repeat --from-literal for each additional value.
-
kubectl create configmap nginx-conf --from-file=nginx.confCreates a ConfigMap from a file. The file name is used as the key, and the file content as the value.
-
kubectl create configmap app-env --from-env-file=app.envCreates a ConfigMap from a file in which each line is in key=value format.
-
kubectl create secret generic db-secret --from-file=password=./db-password.txtCreates a Secret with the password key, whose value is taken from the file. This way, the password isn't saved in the shell's command history, as happens with --from-literal.
-
kubectl get secret db-secret -o jsonpath='{.data.password}' | base64 -dShows the value of the password key from the Secret. The values in a Secret are stored in base64 encoding, which is not encryption, so anyone who can read the Secret can decode it.
Troubleshooting and permissions
-
kubectl get events --sort-by=.metadata.creationTimestampLists the events in the namespace in time order, so the latest events appear at the end. Errors such as a failed image pull or insufficient resources show up here.
-
kubectl events --types=WarningLists only events of type Warning, without the normal events.
-
kubectl top nodeShows the CPU and memory usage of each node. The command requires metrics-server to be installed in the cluster, and the data appears a few minutes after installation.
-
kubectl top pod --sort-by=memoryShows the resource usage of the Pods, sorted by memory. Use --sort-by=cpu to sort by CPU, and add --containers to show each container separately.
-
kubectl debug my-pod -it --image=busybox --target=my-containerAdds a temporary debugging container with the busybox image to the Pod and opens a shell in it, with access to the processes of the my-container container. Useful when the application image has no shell or debugging tools.
-
kubectl debug node/node1 -it --image=busyboxCaution: opens a shell in a container running on the node1 node, with the node's file system in the /host folder. This is broad access to the node, so delete the Pod that was created when you finish.
-
kubectl auth can-i create deployments -n shopChecks whether the current user has permission to create Deployments in the namespace named shop, and returns yes or no.
-
kubectl auth can-i --listLists all the actions the current user is allowed to perform in the current namespace.
Labels and annotations
-
kubectl get pods --show-labelsLists the Pods with all their labels in the last column.
-
kubectl get pods -l app=webLists only Pods with the app=web label. You can combine several conditions with commas, for example app=web,tier=frontend.
-
kubectl get pods -l 'env in (prod,staging)'Lists Pods whose env label has the value prod or staging.
-
kubectl label pod my-pod tier=frontendAdds a label to the Pod. To change the value of an existing label, add --overwrite.
-
kubectl label pod my-pod tier-Removes the tier label from the Pod. The - sign after the label name means removal.
-
kubectl annotate deployment web owner=team-aAdds an annotation to the Deployment. Annotations hold additional information about the resource, and unlike labels, they aren't used to select resources.
Node maintenance
-
kubectl cordon node1Marks the node1 node as unavailable for new Pods. The Pods already running on it keep working.
-
kubectl drain node1 --ignore-daemonsets --delete-emptydir-dataCaution: marks the node as unavailable and evicts its Pods before maintenance, except DaemonSet Pods, which stay on it. The data in the emptyDir folders of the evicted Pods is deleted. When the node has Pods that aren't managed by a Deployment or another controller, the command stops, and with --force they are deleted and not recreated. On a single-node cluster, the services stop working until the maintenance is over.
-
kubectl uncordon node1Returns the node to service after maintenance, so new Pods can run on it again.
No matching commands.
Where the kubeconfig file is located
Unless set otherwise, kubectl reads the $HOME/.kube/config file. When the KUBECONFIG variable is set, kubectl merges the files in the list, and the first file that sets a value determines it. The --kubeconfig option overrides both and uses only the file you specify.
On a cluster set up with kubeadm, the admin file is created at /etc/kubernetes/admin.conf, and a user other than root copies it to their own folder:
mkdir -p $HOME/.kube
sudo cp -i /etc/kubernetes/admin.conf $HOME/.kube/config
sudo chown $(id -u):$(id -g) $HOME/.kube/configOn k3s, the file is located at /etc/rancher/k3s/k3s.yaml, and the kubectl installed with k3s reads it by default. A cluster administrator's kubeconfig file grants full permissions to the whole cluster, so keep it with restricted file permissions and never share it.
Secrets and base64
The values in a Secret are stored in base64 encoding, and encoding is not encryption: anyone who can read the Secret can decode it with the base64 -d command. According to the Kubernetes documentation, Secrets are stored unencrypted by default in the cluster's data store (etcd), so it is recommended to enable encryption at rest for that data and to restrict access to Secrets with RBAC permissions.
A Linux VPS comes with full root access over SSH and dedicated CPU cores and memory, so you can install the tools you work with on the server, for example a small k3s cluster, and manage it with kubectl commands.
kubectl commands FAQ
What is the difference between kubectl apply and kubectl create?
The kubectl create command creates a new resource and returns an error when a resource with the same name already exists. The kubectl apply command creates the resources in the file when they are missing, and updates them to match the file when they exist. That is why a cluster is usually managed from YAML files with kubectl apply, and the kubectl diff command shows in advance what will change.
How do I roll a Deployment back to the previous version?
Run kubectl rollout undo deployment/web, and the previous revision of the Deployment is restored through a gradual replacement of the Pods. The kubectl rollout history deployment/web command lists the revisions, and to return to a specific revision, add --to-revision with the revision number. The kubectl rollout status deployment/web command shows when the replacement is complete.
How do I work with several clusters from the same server?
Each cluster is defined in the kubeconfig file as a context, which combines the cluster address, the user, and the namespace. The kubectl config get-contexts command lists the contexts, and the kubectl config use-context command switches between clusters. When the settings are kept in several files, set them together in the KUBECONFIG variable, separated by colons. Before a command that changes resources, the kubectl config current-context command shows which cluster it will go to.
What does kubectl top need to show data?
The kubectl top command shows data from the cluster's Metrics API, so you need to install metrics-server or another component that provides this data in the cluster. After installation, the data for a new Pod usually appears after a few minutes. The kubectl top node command shows the usage of the nodes, and the kubectl top pod command shows the usage of the Pods.
How do I see the log of a container that restarted after a crash?
The kubectl logs my-pod --previous command shows the log of the previous instance of the container, which usually contains the error that caused the crash. In a Pod with several containers, add -c with the container name. The kubectl describe pod my-pod command shows the reason for the last termination and the number of restarts, and the Pod's events appear at the end of its output.