Kubernetes Cheat Sheet for day to day DevOps operations?
Note - This Kubernetes Cheat sheet is really long and detailed. I would highly recommend to use CTRL+F from the browser to search for the specific command.
Table Of Content
- Pods
- Deployments
- Port Forwarding
- Service
- Nodes
- Namespace
- Service Accounts
- Documentation
- Describing Resources
- Editing Resources
- Deleting Resources
- All get commands
- Abbreviations / Short forms of resource types
- Verbose Kubectl
- Cluster
- Kubectl Context
- Alias
- Kubectl imperative(create) vs declarative(apply)
1. Pods
List all pods in namespace
kubectl get pods
1kubectl get pod
or
1kubectl get pod
or
1kubectl get po
View a pod in watch mode
1kubectl get pod <pod> --watch
View all pods in watch mode
1kubectl get pods -A --watch
List sroted pods
1kubectl get pods --sort-by='.status.containerStatuses[0].restartCount'
List pods using a different output
1kubectl get pods -o <json|yaml|wide|custom-columns=...|custom-columns-
2file=...|go-template=...|go-template-file=...|jsonpath=...|jsonpath-file=...>
Examples:
- JSON output
1kubectl get pods -o json
or
1kubectl get pods -ojson
- Wide output:
1kubectl get pods -o wide
- Custom columns:
1kubectl get pods -o custom-columns='DATA:spec.containers[*].image'
or
1kubectl get pods -o custom-columns='DATA:spec.containers[*].volumeMounts'
or
1kubectl get pods -o custom-columns='DATA:metadata.*'
Formatting output
To output details to your terminal window in a specific format, add the -o (or --output ) flag to a supported kubectl command (source: Kubernetes docs)
Output format | Description |
---|---|
-o=custom-columns = spec | Print a table using a comma separated list of custom columns |
-o=custom-columns-file= filename | Print a table using the custom columns template in the filename file |
-o=json | Output a JSON formatted API object |
-o=jsonpath=template | Print the fields defined in a jsonpath expression |
-o=jsonpath-file= filename | Print the fields defined by the jsonpath expression in the |
-o=name | Print only the resource name and nothing else |
-o=wide | Output in the plain-text format with any additional information, and for pods, the node name is included |
-o=yaml | Output a YAML formatted API object |
List all pods in a namespace
1kubectl get pods -n <namespace>
or
1kubectl -n <namespace> get pods
or
1kubectl --namespace <namespace> get pods
List all pods in all namespaces
1kubectl get pods --all-namespaces
or
1kubectl get pods -A
Create from an image
1kubectl run <pod> --generator=run-pod/v1 --image=<image>
In the following cheatsheet, we will be using images such as nginx or busybox.
Example:
1kubectl run nginx --generator=run-pod/v1 --image=nginx
1kubectl run busybox --generator=run-pod/v1 --image=busybox
Run pod in an interactive shell mode
1kubectl run -i --tty nginx --image=nginx -- sh
Run a command after creating a pod
1kubectl run busybox --image=busybox -- sleep 100000
Executing a command in a running pod
1kubectl exec <pod> -- <command>
Or pass stdin to the container in TTY mode:
1kubectl exec -it <pod> -- <command>
Example:
1kubectl exec -it nginx -- ls -lrth /app/
Create a pod: dry run mode (without really creating it)
1kubectl run <pod> --generator=run-pod/v1 --image=nginx --dry-run
Patch a pod
1kubectl patch pod <pod> -p '<patch>'
Example:
1kubectl patch pod <pod> -p '{"spec":{"containers":[{"name":"kubernetes-serve-
2hostname","image":"new image"}]}}'
Another example:
1kubectl patch pod valid-pod --type='json' -p='[{"op": "replace", "path":
2"/spec/containers/0/image", "value":"new image"}]'
Create from a YAML file
1kubectl create -f pod.yaml
Export YAML from the dry run mode
1kubectl run nginx --generator=run-pod/v1 --image=nginx --dry-run -o yaml
Create from STDIN
1cat <<EOF | kubectl create -f -
2apiVersion: v1
3kind: Pod
4metadata:
5 name: nginx-pod
6spec:
7 containers:
8 - name: nginx
9 image: nginx:latest
10EOF
Create multiple resources from STDIN
1cat <<EOF | kubectl create -f -
2apiVersion: v1
3kind: Pod
4metadata:
5 name: nginx-pod
6spec:
7 containers:
8 - name: nginx
9 image: nginx:latest
10---
11apiVersion: v1
12kind: Pod
13metadata:
14 name: busybox
15spec:
16 containers:
17 - name: busybox
18 image: busybox
19 args:
20 - sleep
21 - "100"
Create in a namespace
1kubectl run nginx --generator=run-pod/v1 --image=nginx -n <namespace>
Create in a namespace from a file
1kubectl create -f pod.yaml -n <namespace>
Delete pods
1kubectl delete pod/<pod>
or
1kubectl delete pod <pod>
If you create the pod from a file, you can also use:
1kubectl delete -f pod.yaml
To force deletion:
1kubectl delete pod <pod> --grace-period=0 --force
Get pod logs
1kubectl logs <pod>
or
Sometimes a pod contains more than 1 container. You need to filter the output to get logs for a specific container(s)
1kubectl logs <pod> -c <container>
To follow the logs output (tail -f):
1kubectl logs -f <pod>
If you need to output the logs for all pods with a label
1kubectl logs -l <label_name>=<label_value>
Example:
1kubectl logs -l env=prod
You can also view logs in a multi container case with labels:
1kubectl logs -l <label_name>=<label_value> -c <container>
Or view all cotainers logs with a given label:
1kubectl logs -f -l <label_name>=<label_value> --all-containers
List all container id of init container of all pods
1kubectl get pods --all-namespaces -o jsonpath='{range
2.items[*].status.initContainerStatuses[*]}{.containerID}{"\n"}{end}' | cut -d/ -
3f3
Show metrics for a given pod
1kubectl top pod <pod>
Show metrics for a given pod and all its containers
1kubectl top pod <pod> --containers
2. Deployments
Create a deployment
1kubectl run <deployment> --image=<image>
or
1kubectl create deployment <deployment> --image=<image>
Create a deployment with a predefined replica number
1kubectl run <deployment> --image=<image> --replicas=<number>
Create a deployment with a predefined replica number and opening a port
1kubectl run <deployment> --image=<image> --replicas=<replicas> --port=<port>
Example:
1kubectl run nginx --image=nginx --replicas=2 --port=80
Note: The default generator for kubectl run is --generator=deployment/apps.v1 .
Note: --generator=deployment/apps.v1 is deprecated and will be removed in future versions. Use kubectl run --generator=run-pod/v1 or kubectl create instead.
Create a deployment with a predefined replica number,opening a port and exposing it
1kubectl run nginx --image=nginx --replicas=2 --port=80 --expose
Get a deployment
1kubectl get deploy <deployment>
Watch a deployment
1kubectl get deployment <deployment> --watch
or
1kubectl get deployment <deployment> -w
Or using a shorter version:
1kubectl get deploy <deployment> -w
Or even the longer one:
1kubectl get deployments.apps <deployment> --watch
List all deployments
Same as listing pods, you have multiple options from namespace to output formatters:
1kubectl get deploy -n <namespace>
2
3kubectl get deploy --all-namespaces
4kubectl get deploy -A
5
6kubectl get deploy -oyaml
7kubectl get deploy -owide
Update the image
Rolling update "nginx" containers of "nginx" deployment, updating the image:
1kubectl set image deployment/nginx nginx=nginx:1.9.1
Rolling update "api" containers of "backend" deployment, updating the image:
1kubectl set image deployment/backend api=image:v2
Scale a deployment
1kubectl scale --replicas=5 deployment/<deployment>
Note: You can use a shorter version:
1kubectl scale --replicas=5 deploy/<deployment>
Dry run and YAML output
1kubectl run nginx --image=nginx --replicas=2 --port=80 --dry-run -o yaml
Create a deployment from a file
1kubectl apply -f deployment.yaml
Edit a deployment
1kubectl edit deployment/<deployment>
Rollback deployment
After editing your deployment, you had an error, a solution can be rolling back to the old deployment status:
1kubectl rollout undo deployment <deployment>
Get rollout history
You can check the rollout history:
1kubectl rollout history deployment <deployment>
1kubectl rollout history deployment <deployment>
Example:
1kubectl rollout history deployment nginx
gives you:
1REVISION CHANGE-CAUSE
22 kubectl set image deployment/nginx nginx=nginx:1.9.1 --record=true
33 <none>
Roll back to a previous revision
Using the information from the rollout history, we can get back our deployment to a given revision:
1kubectl rollout undo deployment <deployment> --to-revision=<revision>
Example:
1kubectl rollout undo deployment nginx --to-revision=2
Execute deployment rollout operations
1kubectl rollout status deployment <deployment>
2kubectl rollout pause deployment <deployment>
3kubectl rollout resume deployment <deployment>
3. Port Forwarding
Choosing localhost port
1kubectl port-forward deployment <deployment> <locahost-port>:<deployment-port>
2kubectl port-forward pod <pod> <locahost-port>:<pod-port>
Example: Forward to localhost 8090 from pod 6379:
1kubectl port-forward redis 8090:6379
Listening on the same port
1kubectl port-forward pod <pod> <port>
Example: Listen on ports 8000 and 9000 on localhost, forwarded from the same ports in the pod (8000 and 9000)
1kubectl port-forward pod nginx 8000 9000
Listen on a random port locally
1kubectl port-forward pod <pod> :<pod-port>
Example:
1kubectl port-forward pod nginx :80
Listen on port on localhost + another IP
1kubectl port-forward --address localhost,<IP.IP.IP.IP> pod <pod> <locahost-
2port>:<pod-port>
Example:
1kubectl port-forward --address localhost,10.10.10.1 pod redis 8090:6379
Listen on a forwarded port on all addresses
1kubectl port-forward --address 0.0.0.0 pod <pod> <hosts-port>:<pod-port>
4.Services
Create a service
1kubectl create service <clusterip|externalname|loadbalancer|nodeport> <service>
2[flags] [options]>
Examples:
1kubectl create service clusterip myclusterip --tcp=5678:8080
2kubectl create service loadbalancer myloadbalancer --tcp=80
You can use svc instead of service
Delete service(s)
1kubectl delete service myclusterip
2kubectl delete service myloadbalancer
3
4kubectl delete svc myclusterip
5kubectl delete svc myloadbalancer
or
1kubectl delete service myclusterip myloadbalancer
Describe a service
1kubectl describe service <service>
5.Nodes
Get node
1kubectl get nodes
Get a specific node
1kubectl get nodes <node>
Show node metrics
1kubectl top node <node>
Get external IPs of cluster nodes
1kubectl get nodes -o jsonpath='{.items[*].status.addresses[?
2(@.type=="ExternalIP")].address}'
Describe commands with verbose output
1kubectl describe nodes <node>
Check which nodes are ready
1JSONPATH='{range .items[*]}{@.metadata.name}:{range @.status.conditions[*]}
2{@.type}={@.status};{end}{end}' && kubectl get nodes -o jsonpath="$JSONPATH" |
3grep "Ready=True"
Mark a node as unschedulable
1kubectl cordon <node>
Drain a node for maintenance
1kubectl drain <node>
Mark a node as schedulable
1kubectl uncordon <node>
6.Namespaces
List namespaces
1kubectl get namespaces
or
1kubectl get ns
List or describe a namespace
1kubectl get namespace <namespace>
2kubectl describe namespace <namespace>
Create namespace
1kubectl create namespace <namespace>
or
1kubectl create -f namespace.yaml
or
1cat <<EOF | kubectl create -f -
2apiVersion: v1
3kind: Namespace
4metadata:
5 name: mynamespace
6EOF
Delete namespace
1kubectl delete namespace <namespace>
or
1kubectl delete -f namespace.yaml
7. Service accounts
List service accounts
1kubectl get serviceaccounts
or
1kubectl get sa
Get a service account
1kubectl get serviceaccount <serviceaccount>
or
1kubectl get serviceaccounts <serviceaccount>
or
1kubectl get sa <serviceaccount>
or
1kubectl get sa/<serviceaccount>
Create a service account
1kubectl create serviceaccount <serviceaccount>
Delete a service account
1kubectl delete serviceaccount <serviceaccount>
or
1kubectl delete -f myserviceaccount.yaml
Describe a service account
1kubectl describe serviceaccount <serviceaccount>
Events
List events
1kubectl get events -A
List sorted events
1kubectl get events --sort-by=<JSONPath>
Example: Sorted by timestamp
1kubectl get events --sort-by=.metadata.creationTimestamp
List formatted events
1kubectl get events -o <json|yaml|wide|custom-columns=...|custom-columns-
2file=...|go-template=...|go-template-file=...|jsonpath=...|jsonpath-file=...>
Example:
1kubectl get events -owide
8.Documentation
Get the documentation for pod manifests
1kubectl explain pod
Get the documentation for service manifests
1kubectl explain service
9.Describing resources
1 kubectl describe <resource> <reosurce_name>
Example:
1kubectl describe pod busybox
or
1kubectl describe nodes minikube
Other possible resources you can use with describe :
1apiservices.apiregistration.k8s.io
2certificatesigningrequests.certificates.k8s.io
3clusterrolebindings.rbac.authorization.k8s.io
4clusterroles.rbac.authorization.k8s.io
5componentstatuses
6configmaps
7controllerrevisions.apps
8cronjobs.batch
9csidrivers.storage.k8s.io
10csinodes.storage.k8s.io
11customresourcedefinitions.apiextensions.k8s.io
12daemonsets.apps
13daemonsets.extensions
14deployments.apps
15deployments.extensions
16endpoints
17events
18events.events.k8s.io
19horizontalpodautoscalers.autoscaling
20ingresses.extensions
21ingresses.networking.k8s.io
22jobs.batch
23leases.coordination.k8s.io
24limitranges
25mutatingwebhookconfigurations.admissionregistration.k8s.io
26namespaces
27networkpolicies.extensions
28networkpolicies.networking.k8s.io
29nodes
30persistentvolumeclaims
31persistentvolumes
32poddisruptionbudgets.policy
33pods
34podsecuritypolicies.extensions
35podsecuritypolicies.policy
36podtemplates
37priorityclasses.scheduling.k8s.io
38replicasets.apps
39replicasets.extensions
40replicationcontrollers
41resourcequotas
42rolebindings.rbac.authorization.k8s.io
43roles.rbac.authorization.k8s.io
44runtimeclasses.node.k8s.io
45secrets
46serviceaccounts
47services
48statefulsets.apps
49storageclasses.storage.k8s.io
50validatingwebhookconfigurations.admissionregistration.k8s.io
51volumeattachments.storage.k8s.io
10.Editing resources
Edit a service
1kubectl edit service <service>
Edit a service with your favorite text editor
1KUBE_EDITOR="vim" edit service <service>
Note: Change service by any editable resource type like pods.
11.Deleting Resources
Delete a resource using the type and name specified in
1kubectl delete -f <file>
Delete pods and services with same names
1kubectl delete pod,service <name1> <name2>
Delete pods and services with a custom label
1kubectl delete pods,services -l <label-name>=<label-value>
Delete all pods and services in a namespace
1kubectl -n <namespace> delete pods,services --all
Delete all resources in a namespace
1kubectl delte <namespace>
12.All get commands
1kubectl get all
2kubectl get pods
3kubectl get replicasets
4kubectl get services
5kubectl get nodes
6kubectl get namespaces
7kubectl get configmaps
8kubectl get endpoints
13.Abbreviations / Short forms of resource types
Resource type | Abbreviations |
---|---|
componentstatuses | cs |
configmaps | cm |
daemonsets | ds |
deployments | deploy |
endpoints | ep |
event | ev |
horizontalpodautoscalers | hpa |
ingresses | ing |
limitranges | limits |
namespaces | ns |
nodes | no |
persistentvolumeclaims | pvc |
persistentvolumes | pv |
pods | po |
podsecuritypolicies | psp |
replicasets | rs |
replicationcontrollers | rc |
resourcequotas | quota |
serviceaccount | sa |
services | svc |
14.Verbose Kubectl
1kubectl run nginx --image=nginx --v=5
Verbosity | Description |
---|---|
--v=0 | Generally useful for this to always be visible to a cluster operator. |
--v=1 | A reasonable default log level if you don't want verbosity. |
--v=2 | Useful steady state information about the service and important log messages that may correlate to significant changes in the system. This is the recommended default log level for most systems. |
--v=3 | Extended information about changes. |
--v=4 | Debug level verbosity. |
--v=6 | Display requested resources. |
--v=7 | Display HTTP request headers. |
--v=8 | Display HTTP request contents. |
--v=9 | Display HTTP request contents without truncation of contents. |
(Table source: K8s docs)
15.Cluster
Display addresses of the master and services
1kubectl cluster-info
Dump cluster state to STDOUT
1kubectl cluster-info dump
Dump cluster state to a file
1kubectl cluster-info dump --output-directory=</file/path>
Compares the current cluster state against the state that the cluster would be in if the manifest was applied
1kubectl diff -f ./my-manifest.yaml
List all images running in a cluster
1kubectl get pods -A -o=custom-columns='DATA:spec.containers[*].image'
16.Kubectl context
Show merged kubeconfig settings
1kubectl config view
Use multiple kubeconfig
1KUBECONFIG=~/.kube/config1:~/.kube/config2:~/.kube/config3
Get a list of users
1kubectl config view -o jsonpath='{.users[*].name}'
Display the first user
1kubectl config view -o jsonpath='{.users[].name}'
Get the password for the "admin" user
1kubectl config view -o jsonpath='{.users[?(@.name == "admin")].user.password}'
Display the current context
1kubectl config current-context
Display list of contexts
1kubectl config get-contexts
Set the default context to
1kubectl config use-context <cluster>
Sets a user entry in kubeconfig
1kubectl config set-credentials <username> [options]
Sets a user with a client key
1kubectl config set-credentials <user> --client-key=~/.kube/admin.key
Sets a user with basic auth
1kubectl config set-credentials --username=<username> --password=<password>
Sets a user with client certificate
1kubectl config set-credentials <user> --client-certificate=<path/to/cert> --
2embed-certs=true
Set a context utilizing a specific config file
1kubectl config --kubeconfig=<config/path> use-context <cluster>
Set a context utilizing a specific username and namespace.
1kubectl config set-context gce --user=cluster-admin --namespace=foo \
2 && kubectl config use-context gce
17.Alias
Create an alias on *nix
1alias k=kubectl
Create an alias on Windows
1Set-Alias -Name k -Value kubectl
18.Kubectl imperative (create) vs declarative (apply)
Create
You tell your cluster what you want to create, replace or delete, not how you want you it to look like.
1kubectl create -f <filename|url>
2kubectl delete deployment <deployment-name>
3kubectl delete deployment <deployment-filename>
4kubectl delete deployment <deployment-url>
Apply
You tell your cluster how you want it to look like. The creation, deletion and modification of objects is done via a single command. The declarative approach is a statement of the desired end result.
1kubectl apply -f <filename|url>
2kubectl delete -f <deployment-filename>
3kubectl apply -f <deployment-filename>
If the deployment is deleted in
Posts in this Series
- Kubernetes Cheat Sheet for day to day DevOps operations?
- Delete Kubernetes POD stuck in terminating state?
- How to Delete PV(Persistent Volume) and PVC(Persistent Volume Claim) stuck in terminating state?
- Share kubernetes secrets between namespaces?
- How to use Kubernetes secrets?
- How to delete all kubernetes PODS?
- kubernetes pods getting recreated?
- Implementing Kubernetes liveness, Readiness and Startup probes with Spring Boot Microservice Application?
- kubectl export yaml OR How to generate YAML for deployed kubernetes resources
- Kubernetes Updates
- CI/CD Kubernetes | Setting up CI/CD Jenkins pipeline for kubernetes
- Kubernetes cluster setup with Jenkins
- How to use Persistent Volume and Persistent Claims | Kubernetes
- How to fix ProvisioningFailed persistentvolume controller no volume plugin matched
- Fixing – Cannot bind to requested volume: storageClasseName does not match
- Fixing – pod has unbound immediate persistentvolumeclaims or cannot bind to requested volume incompatible accessmode
- How to fix kubernetes dashboard forbidden 403 error – message services https kubernetes-dashboard is forbidden User
- How to fix Kubernetes – error execution phase preflight [preflight]
- Deploy Spring Boot microservices on kubernetes?
- How to fix – ansible_memtotal_mb minimal_master_memory_mb
- How to use kubespray – 12 Steps for Installing a Production Ready Kubernetes Cluster
- How to setup kubernetes on CentOS 8 and CentOS 7
- How to fix – How to fix - ERROR Swap running with swap on is not supported. Please disable swap
- 14 Steps to Install kubernetes on Ubuntu 20.04(bento/ubuntu-20.04), 18.04(hashicorp/bionic64)
- Kubernetes Dashboard | Kubernetes Admin GUI | Kubernetes Desktop Client
- Install Kubernetes with Minikube