You are on page 1of 12

Blog URL: https://cheatsheet.dennyzhang.

com/cheatsheet-kubernetes-A4 Updated: June 7, 2020

1 Kubectl Kubernetes CheatSheet Cloud


• PDF Link: cheatsheet-kubernetes-A4.pdf, Category: Cloud
• Blog URL: https://cheatsheet.dennyzhang.com/cheatsheet-kubernetes-A4
• Related posts: Kubectl CheatSheet, Kubernetes Yaml, #denny-cheatsheets

File me Issues or star this repo.

1.1 Common Commands

Name Command
Run curl test temporarily kubectl run --generator=run-pod/v1 --rm mytest --image=yauritux/busybox-cu
Run wget test temporarily kubectl run --generator=run-pod/v1 --rm mytest --image=busybox -it wget
Run nginx deployment with 2 replicas kubectl run my-nginx --image=nginx --replicas=2 --port=80
Run nginx pod and expose it kubectl run my-nginx --restart=Never --image=nginx --port=80 --expose
Run nginx deployment and expose it kubectl run my-nginx --image=nginx --port=80 --expose
List authenticated contexts kubectl config get-contexts, ~/.kube/config
Set namespace preference kubectl config set-context <context_name> --namespace=<ns_name>
List pods with nodes info kubectl get pod -o wide
List everything kubectl get all --all-namespaces
Get all services kubectl get service --all-namespaces
Get all deployments kubectl get deployments --all-namespaces
Show nodes with labels kubectl get nodes --show-labels
Get resources with json output kubectl get pods --all-namespaces -o json
Validate yaml file with dry run kubectl create --dry-run --validate -f pod-dummy.yaml
Start a temporary pod for testing kubectl run --rm -i -t --image=alpine test-$RANDOM -- sh
kubectl run shell command kubectl exec -it mytest -- ls -l /etc/hosts
Get system conf via configmap kubectl -n kube-system get cm kubeadm-config -o yaml
Get deployment yaml kubectl -n denny-websites get deployment mysql -o yaml
Explain resource kubectl explain pods, kubectl explain svc
Watch pods kubectl get pods -n wordpress --watch
Query healthcheck endpoint curl -L http://127.0.0.1:10250/healthz
Open a bash terminal in a pod kubectl exec -it storage sh
Check pod environment variables kubectl exec redis-master-ft9ex env
Enable kubectl shell autocompletion echo "source <(kubectl completion bash)" »~/.bashrc, and reload
Use minikube dockerd in your laptop eval $(minikube docker-env), No need to push docker hub any more
Kubectl apply a folder of yaml files kubectl apply -R -f .
Get services sorted by name kubectl get services –sort-by=.metadata.name
Get pods sorted by restart count kubectl get pods –sort-by=’.status.containerStatuses[0].restartCount’
List pods and images kubectl get pods -o=’custom-columns=PODS:.metadata.name,Images:.spec.containers[*]
List all container images list-all-images.sh
kubeconfig skip tls verification skip-tls-verify.md
Ubuntu install kubectl "deb https://apt.kubernetes.io/ kubernetes-xenial main"
Reference GitHub: kubernetes releases
Reference minikube cheatsheet, docker cheatsheet, OpenShift CheatSheet

1.2 Check Performance


Name Command
Get node resource usage kubectl top node
Get pod resource usage kubectl top pod
Get resource usage for a given pod kubectl top <podname> --containers
List resource utilization for all containers kubectl top pod --all-namespaces --containers=true

GitHub: https://github.com/dennyzhang/cheatsheet-kubernetes-A4 1 of 5
Blog URL: https://cheatsheet.dennyzhang.com/cheatsheet-kubernetes-A4 Updated: June 7, 2020

1.3 Resources Deletion


Name Command
Delete pod kubectl delete pod/<pod-name> -n <my-namespace>
Delete pod by force kubectl delete pod/<pod-name> --grace-period=0 --force
Delete pods by labels kubectl delete pod -l env=test
Delete deployments by labels kubectl delete deployment -l app=wordpress
Delete all resources filtered by labels kubectl delete pods,services -l name=myLabel
Delete resources under a namespace kubectl -n my-ns delete po,svc --all
Delete persist volumes by labels kubectl delete pvc -l app=wordpress
Delete state fulset only (not pods) kubectl delete sts/<stateful_set_name> --cascade=false

1.4 Log & Conf Files


Name Comment
Config folder /etc/kubernetes/
Certificate files /etc/kubernetes/pki/
Credentials to API server /etc/kubernetes/kubelet.conf
Superuser credentials /etc/kubernetes/admin.conf
kubectl config file ~/.kube/config
Kubernets working dir /var/lib/kubelet/
Docker working dir /var/lib/docker/, /var/log/containers/
Etcd working dir /var/lib/etcd/
Network cni /etc/cni/net.d/
Log files /var/log/pods/
log in worker node /var/log/kubelet.log, /var/log/kube-proxy.log
log in master node kube-apiserver.log, kube-scheduler.log, kube-controller-manager.log
Env /etc/systemd/system/kubelet.service.d/10-kubeadm.conf
Env export KUBECONFIG=/etc/kubernetes/admin.conf

1.5 Pod

Name Command
List all pods kubectl get pods
List pods for all namespace kubectl get pods -all-namespaces
List all critical pods kubectl get -n kube-system pods -a
List pods with more info kubectl get pod -o wide, kubectl get pod/<pod-name> -o yaml
Get pod info kubectl describe pod/srv-mysql-server
List all pods with labels kubectl get pods --show-labels
List all unhealthy pods kubectl get pods –field-selector=status.phase!=Running –all-namespaces
List running pods kubectl get pods –field-selector=status.phase=Running
Get Pod initContainer status kubectl get pod --template ’{{.status.initContainerStatuses}}’ <pod-name>
kubectl run command kubectl exec -it -n "$ns" "$podname" – sh -c "echo $msg »/dev/err.log"
Watch pods kubectl get pods -n wordpress --watch
Get pod by selector kubectl get pods –selector="app=syslog" -o jsonpath=’{.items[*].metadata.name}’
List pods and images kubectl get pods -o=’custom-columns=PODS:.metadata.name,Images:.spec.containers[*].image’
List pods and containers -o=’custom-columns=PODS:.metadata.name,CONTAINERS:.spec.containers[*].name’
Reference Link: kubernetes yaml templates

1.6 Label & Annontation


Name Command
Filter pods by label kubectl get pods -l owner=denny
Manually add label to a pod kubectl label pods dummy-input owner=denny
Remove label kubectl label pods dummy-input owner-
Manually add annonation to a pod kubectl annotate pods dummy-input my-url=https://dennyzhang.com

GitHub: https://github.com/dennyzhang/cheatsheet-kubernetes-A4 2 of 5
Blog URL: https://cheatsheet.dennyzhang.com/cheatsheet-kubernetes-A4 Updated: June 7, 2020

1.7 Deployment & Scale


Name Command
Scale out kubectl scale --replicas=3 deployment/nginx-app
online rolling upgrade kubectl rollout app-v1 app-v2 --image=img:v2
Roll backup kubectl rollout app-v1 app-v2 --rollback
List rollout kubectl get rs
Check update status kubectl rollout status deployment/nginx-app
Check update history kubectl rollout history deployment/nginx-app
Pause/Resume kubectl rollout pause deployment/nginx-deployment, resume
Rollback to previous version kubectl rollout undo deployment/nginx-deployment
Reference Link: kubernetes yaml templates, Link: Pausing and Resuming a Deployment

1.8 Quota & Limits & Resource


Name Command
List Resource Quota kubectl get resourcequota
List Limit Range kubectl get limitrange
Customize resource definition kubectl set resources deployment nginx -c=nginx --limits=cpu=200m
Customize resource definition kubectl set resources deployment nginx -c=nginx --limits=memory=512Mi
Reference Link: kubernetes yaml templates

1.9 Service

Name Command
List all services kubectl get services
List service endpoints kubectl get endpoints
Get service detail kubectl get service nginx-service -o yaml
Get service cluster ip kubectl get service nginx-service -o go-template=’{{.spec.clusterIP}}’
Get service cluster port kubectl get service nginx-service -o go-template=’{{(index .spec.ports 0).port}}’
Expose deployment as lb service kubectl expose deployment/my-app --type=LoadBalancer --name=my-service
Expose service as lb service kubectl expose service/wordpress-1-svc --type=LoadBalancer --name=ns1
Reference Link: kubernetes yaml templates

1.10 Secrets
Name Command
List secrets kubectl get secrets --all-namespaces
Generate secret echo -n ’mypasswd’, then redirect to base64 --decode
Get secret kubectl get secret denny-cluster-kubeconfig
Get a specific field of a secret kubectl get secret denny-cluster-kubeconfig -o jsonpath="{.data.value}"
Create secret from cfg file kubectl create secret generic db-user-pass –from-file=./username.txt
Reference Link: kubernetes yaml templates, Link: Secrets

1.11 StatefulSet
Name Command
List statefulset kubectl get sts
Delete statefulset only (not pods) kubectl delete sts/<stateful_set_name> --cascade=false
Scale statefulset kubectl scale sts/<stateful_set_name> --replicas=5
Reference Link: kubernetes yaml templates

GitHub: https://github.com/dennyzhang/cheatsheet-kubernetes-A4 3 of 5
Blog URL: https://cheatsheet.dennyzhang.com/cheatsheet-kubernetes-A4 Updated: June 7, 2020

1.12 Volumes & Volume Claims


Name Command
List storage class kubectl get storageclass
Check the mounted volumes kubectl exec storage ls /data
Check persist volume kubectl describe pv/pv0001
Copy local file to pod kubectl cp /tmp/my <some-namespace>/<some-pod>:/tmp/server
Copy pod file to local kubectl cp <some-namespace>/<some-pod>:/tmp/server /tmp/my
Reference Link: kubernetes yaml templates

1.13 Events & Metrics


Name Command
View all events kubectl get events --all-namespaces
List Events sorted by timestamp kubectl get events –sort-by=.metadata.creationTimestamp

1.14 Node Maintenance


Name Command
Mark node as unschedulable kubectl cordon $NODE_NAME
Mark node as schedulable kubectl uncordon $NODE_NAME
Drain node in preparation for maintenance kubectl drain $NODE_NAME

1.15 Namespace & Security

Name Command
List authenticated contexts kubectl config get-contexts, ~/.kube/config
Set namespace preference kubectl config set-context <context_name> --namespace=<ns_name>
Switch context kubectl config use-context <cluster-name>
Load context from config file kubectl get cs --kubeconfig kube_config.yml
Delete the specified context kubectl config delete-context <cluster-name>
List all namespaces defined kubectl get namespaces
List certificates kubectl get csr
Check user privilege kubectl –as=system:serviceaccount:ns-denny:test-privileged-sa -n ns-denny auth can-i use pods/lis
Check user privilege kubectl auth can-i use pods/list
Reference Link: kubernetes yaml templates

1.16 Network
Name Command
Temporarily add a port-forwarding kubectl port-forward redis-134 6379:6379
Add port-forwaring for deployment kubectl port-forward deployment/redis-master 6379:6379
Add port-forwaring for replicaset kubectl port-forward rs/redis-master 6379:6379
Add port-forwaring for service kubectl port-forward svc/redis-master 6379:6379
Get network policy kubectl get NetworkPolicy

1.17 Patch
Name Summary
Patch service to loadbalancer kubectl patch svc $svcname -p ’{"spec": {"type": "LoadBalancer"}}’

1.18 Extenstions
Name Summary
Enumerates the resource types available kubectl api-resources
List api group kubectl api-versions
List all CRD kubectl get crd
List storageclass kubectl get storageclass

GitHub: https://github.com/dennyzhang/cheatsheet-kubernetes-A4 4 of 5
Blog URL: https://cheatsheet.dennyzhang.com/cheatsheet-kubernetes-A4 Updated: June 7, 2020

1.19 Components & Services


1.19.1 Services on Master Nodes
Name Summary
kube-apiserver API gateway. Exposes the Kubernetes API from master nodes
etcd reliable data store for all k8s cluster data
kube-scheduler schedule pods to run on selected nodes
kube-controller-manager Reconcile the states. node/replication/endpoints/token controller and service account, etc
cloud-controller-manager

1.19.2 Services on Worker Nodes

Name Summary
kubelet A node agent makes sure that containers are running in a pod
kube-proxy Manage network connectivity to the containers. e.g, iptable, ipvs
Container Runtime Kubernetes supported runtimes: dockerd, cri-o, runc and any OCI runtime-spec implementation.

1.19.3 Addons: pods and services that implement cluster features


Name Summary
DNS serves DNS records for Kubernetes services
Web UI a general purpose, web-based UI for Kubernetes clusters
Container Resource Monitoring collect, store and serve container metrics
Cluster-level Logging save container logs to a central log store with search/browsing interface

1.19.4 Tools
Name Summary
kubectl the command line util to talk to k8s cluster
kubeadm the command to bootstrap the cluster
kubefed the command line to control a Kubernetes Cluster Federation
Kubernetes Components Link: Kubernetes Components

1.20 More Resources


License: Code is licensed under MIT License.
https://kubernetes.io/docs/reference/kubectl/cheatsheet/
https://codefresh.io/kubernetes-guides/kubernetes-cheat-sheet/

GitHub: https://github.com/dennyzhang/cheatsheet-kubernetes-A4 5 of 5
kubectl Commands Cheat Sheet
Listing Resources Displaying the State of Resources Printing Container Logs

kubectl get namespaces Generate a plain-text list of kubectl describe nodes See details about a kubectl logs [pod-name] Print logs from a pod
all namespaces [node-name] particular node
kubectl logs -f [pod-name] Stream logs from a pod
kubectl get pods Generate a plain-text list of kubectl describe pods See details about a
all pods [pod-name] particular pod
Resource Types - Short Names
kubectl get pods -o wide Generate a detailed Kubectl describe –f pod.json See details about a pod
plain-text list of all pods whose name and type are
listed in pod.json Short name Full name
kubectl get pods Generate a list of all pods
--field-selector=spec. running on a particular kubectl describe pods See details about all pods csr certificatesigningrequests
nodeName=[server-name] node server [replication-controller-name] managed by a specific
replication controller
cs componentstatuses
kubectl get List a specific replication
replicationcontroller controller in plain text kubectl describe pods See details about all pods
[replication-controller- cm configmaps
name]
ds daemonsets
Deleting Resources
kubectl get Generate a plain-text list of
replicationcontroller, all replication controllers deploy deployments
services and services kubectl delete -f pod.yaml Remove a pod using the
name and type listed in
ep endpoints
kubectl get deamonset Generate a plain-text list of pod.yaml:
all daemon sets
kubectl delete pods,services Remove all the pods and ev events
-l [label-key]=[label-value] services with a specific
label: hpa horizontalpodautoscalers
Creating a Resource
kubectl delete pods --all Remove all pods. The ing ingresses
kubectl create namespace Create a new namespace command will include
[namespace-name] uninitialized pods as well
limits limitranges

kubectl create –f [filename] Create a resource from a


JSON or YAML file ns namespaces
Executing a Command
no nodes
kubectl exec [pod-name] -- Receive output from a
Applying & Updating a Resource [command] command run on the first pvc persistentvolumeclaims
container in a pod:
kubectl apply -f Create a new service with
pv persistentvolumes
[service-name].yaml the definition contained in kubectl exec [pod-name] -c Receive output from a
[service-name].yaml [container-name] -- command run on a specific
po pods
[command] container in a pod
kubectl apply -f Create a new replication
[controller-name].yaml controller with the kubectl exec -ti [pod-name] -- Run /bin/bash from a pdb poddisruptionbudgets
definition contained in /bin/bash specific pod. The output
[controller-name].yaml received comes from the psp podsecuritypolicies
first container
kubectl apply -f Create the objects defined rs replicasets
[directory-name] in any .yaml, .yml, or .json
file in a directory Modifying kubeconfig Files rc replicationcontrollers
kubectl edit svc/ Edit a service
[service-name] kubectl config Display the current context quota resourcequotas
current-context
KUBE_EDITOR=” Edit a service in a sa serviceaccounts
[editor-name]” kubectl edit non-default editor kubectl config set-cluster Set a cluster entry in
svc/[service-name] [cluster-name] --server= kubeconfig svc services
[server-name]

kubectl config unset Unset an entry in


[property-name] kubeconfig
Deployments ReplicaSets
Kubernetes Cheat $ k ubec t l get depl oy $ kubect l get r s

Sheet $ k ubec t l desc r i be depl oy


$ k ubec t l get depl oy - o wi de
$ kubect l descr i be r s
$ kubect l get r s - o wi de
$ k ubec t l get depl oy - o yaml $ kubect l get r s - o yaml
What is Kubernetes?
Services Roles
Kubernetes is a platform for managing containerized
workloads. Kubernetes orchestrates computing, $ k ubec t l get s vc $ kubect l get r ol es - - al l - namespaces
networking and storage to provide a seamless portability
$ k ubec t l desc r i be sv c $ kubect l get r ol es - - al l - namespaces - o yaml
across infrastructure providers.
$ k ubec t l get s vc - o wi de
$ k ubec t l get s vc - o y aml Secrets
Viewing Resource Information $ k ubec t l get s vc - - s how- l abel s
$ kubect l get s ecr et s
$ kubect l get s ecr et s - - al l - names pac es
Nodes DaemonSets $ kubect l get s ecr et s - o y aml
$ k ubec t l get no
$ k ubec t l get ds
$ k ubec t l get no - o wi de ConfigMaps
$ k ubec t l get ds - - al l - names pac es
$ k ubec t l des cr i be no $ kubect l get c m
$ k ubec t l desc r i be ds [ daemonset _name] - n
$ k ubec t l get no - o y aml [ namespace_name] $ kubect l get c m - - al l - namespaces
$ k ubec t l get node - - sel ect or =[ l abel _name] $ k ubec t l get ds [ ds_name] - n [ ns _name] - o $ kubect l get c m - - al l - namespaces - o yaml
$ k ubec t l get nodes - o y aml
j s onpat h=' { . i t ems[ * ] . st at us. addr es ses
Events Ingress
[ ?( @. t y pe==" Ext er nal I P" ) ] . addr ess} '
$ k ubec t l t op node [ node_name] $ kubect l get i ng
$ k ubec t l get event s
$ kubect l get i ng - - al l - names paces
Pods $ k ubec t l get event s - n kube- sy st em
$ k ubec t l get event s - w
$ k ubec t l get po PersistentVolume
$ k ubec t l get po - o wi de Logs $ kubect l get pv
$ k ubec t l des cr i be po
$ k ubec t l l ogs [ pod_name] $ kubect l descr i be pv
$ k ubec t l get po - - show- l abel s
$ k ubec t l get po - l app=ngi nx $ k ubec t l l ogs - - si nc e=1h [ pod_name]
$ k ubec t l l ogs - - t ai l =20 [ pod_name]
PersistentVolumeClaim
$ k ubec t l get po - o y aml
$ k ubec t l get pod [ pod_name] - o yaml $ k ubec t l l ogs - f - c [ cont ai ner _name] $ kubect l get pvc
- - expor t [ pod_name]
$ kubect l descr i be pvc
$ k ubec t l get pod [ pod_name] - o yaml $ k ubec t l l ogs [ pod_name] > pod. l og
- - expor t > nameof f i l e. yaml
Service Accounts
$ k ubec t l get pods - - f i el d- s el ect or
st at us. phase=Runni ng $ k ubec t l get s a
Namespaces $ k ubec t l get s a - o y aml
$ k ubec t l get s er vi ceacc ount s def aul t - o
$ k ubec t l get ns y aml > . / s a. yaml
$ k ubec t l get ns - o y aml
$ k ubec t l des cr i be ns
$ k ubec t l r epl ace s er v i c eacc ount def aul t - f
. / s a. yaml
http://linuxacademy.com
Deployments/Namespaces Creating a Deployment
Kubernetes Cheat $ k ubec t l edi t depl oy [ depl oy _name] $ kubec t l c r eat e - f [ name_of _f i l e]

Sheet page 2
$ k ubec t l del et e depl oy [ depl oy _name]
$ k ubec t l ex pos e depl oy [ depl oy _name]
$ kubec t l appl y - f [ name_of _f i l e]
$ kubec t l c r eat e depl oy [ depl oy_name]
- - por t =80 - - t y pe=NodePor t - - i mage=ngi nx
Viewing Resource Information (cont.) $ k ubec t l sc al e depl oy [ depl oy_name]
- - r epl i c as =5 Interactive Pod
StorageClass $ k ubec t l del et e ns $ kubec t l r un [ pod_name] - - i mage=busybox
$ k ubec t l edi t ns [ ns _name] - - r m - i t - - r es t ar t =Never - - sh
$ k ubect l get s c
$ k ubect l get s c - o yaml Services Output YAML to a File

$ k ubec t l edi t sv c [ s v c_name] $ k ubect l cr eat e depl oy [ depl oy _name]


Multiple Resources - - i mage=ngi nx - - dr y- r un - o yaml >
$ k ubec t l del et e sv c [ sv c_name] depl oy . yaml
$ k ubect l get s vc, po $ k ubect l get po [ pod_name] - o yaml - - expor t
$ k ubect l get depl oy , no
DaemonSets
> pod. yaml
$ k ubect l get al l $ k ubec t l edi t ds [ ds _name] - n kube- sy st em
Getting Help
$ k ubect l get al l - - al l - namespaces $ k ubec t l del et e ds [ ds_name]
$ k ubect l - h
Service Accounts $ k ubect l cr eat e - h
Changing Resource Attributes $ k ubec t l edi t sa [ sa_name] $ k ubect l r un - h
$ k ubec t l del et e sa [ s a_name] $ k ubect l expl ai n depl oy . spec
Taint
$ k ubect l t ai nt [ node_name] [ t ai nt _name] Annotate
Requests
$ k ubec t l annot at e po [ pod_name]
Labels [ annot at i on]
API Call
$ k ubec t l l abel [ node_name] di sk t ype=ssd $ k ubec t l annot at e no [ node_name]
$ k ubect l get - - r aw / api s/ met r i cs. k8s. i o/
$ k ubr ec t l l abel [ pod_name] env=pr od

Adding Resources
Cordon/Uncordon Cluster Info
$ k ubec t l c or don [ node_name]
Creating a Pod $ k ubect l conf i g
$ k ubec t l uncor don [ node_name] $ k ubec t l cr eat e - f [ name_of _f i l e] $ k ubect l cl ust er - i nf o
$ k ubec t l appl y - f [ name_of _f i l e] $ k ubect l get component s t at uses
Drain
$ k ubec t l r un [ pod_name] - - i mage=ngi nx
$ k ubect l dr ai n [ node_name] - - r es t ar t =Never
$ k ubec t l r un [ pod_name]
- - gener at or =r un- pod/ v 1 - - i mage=ngi nx
Nodes/Pods
$ k ubec t l r un [ pod_name] - - i mage=ngi nx
$ k ubec t l del et e node [ node_name] - - r es t ar t =Never

$ k ubec t l del et e pod [ pod_name] Creating a Service


$ k ubec t l edi t node [ node_name]
$ k ubec t l edi t pod [ pod_name]
$ k ubec t l cr eat e sv c nodepor t [ sv c _name]
- - t cp=8080: 80
http://linuxacademy.com
mimacom
Kubernetes Cheat Sheet
Kubernetes, is an open-source system for automating deployment, scaling, and management of containerized applications. It is
built for planet scale to run millions of containers, while it’s flexibility allows customization to meet any needs so in fact, Kubernetes
can run anywhere from on-premises to hybrid or public cloud infrastructure.

AUTHENTICATION DELETING RESOURCES


A context connects to a K8s cluster with a specific user. Resources that are deleted are usually gone forever.

kubectl config get-contexts kubectl delete <type> <name>


View all available and configured contexts Delete a specific resource of type identified by its name.
kubectl config current-context kubectl delete -f <manifest.yml>
Show the context that is currently being used Delete all resources mentioned in the manifest file.
kubectl config use-context <context-name>
Switch to another context and use it for subsequent commands
EDITING RESOURCES
kubectl config view
For a quick test you can manually edit resources.
View the merged configuration file
kubectl edit <type> <name>
Edit a specific resource and sync any changes to the cluster.
CREATING RESOURCES KUBE_EDITOR="nano"
Create resources declaratively with a manifest. Set the editor to use to your liking.
kubectl apply -f <manifest.yml>
Create and update resources to match definition in manifest file.
VIEW AND FIND RESOURCES
kubectl apply -k <directory>
Explore the resource objects available.
Apply a folder using Kustomize configuration management.
kubectl create job <name> --image=busybox - kubectl get <type>
- echo 'Hello mimacom!' Get all resources of a type in current namespace, e.g. pods.
Imperatively create a resource, in this case a job. kubectl get <type> -A
kubectl create secret generic <name> --from- Get all resources of a type across all namespaces.
literal=<key>=<value>
kubectl get <type> <name>
Create a secret from the CLI. Do not store secrets in manifest files.
Get condensed info on a specific resource by name.
kubectl describe <type> <name>
EXPLORING RESOURCE TYPES Get verbose info on a specific resource by name.

Every cluster may have different resource types. kubectl get <type> <name> -o yaml
Get a specific resource in its complete YAML representation.
kubectl api-resources
kubectl get <type> --show-labels
Retrieve a list of all available resource types of the cluster.
Get all resource along with the labels defined on each resource.
kubectl explain <type>
kubectl get <type> -l <label>=<value>
Get the documentation for the resource type.
Show only resources that have label set to value.
kubectl explain <type>.<property>
Get documentation for a specific property.

k8s-cheat-sheet.docx/Publication Date Seite 1 von 2


OPERATING APPLICATIONS EXAMPLE MANIFESTS
Rollout and scale your applications. Use these example manifests as quick reference.

kubectl rollout history <type> <name> ---


apiVersion: apps/v1
View the deployment history of a specific deployment
kind: Deployment
kubectl rollout undo <type> <name> metadata:
Rollback to the previous deployment. name: mima-deployment
spec:
kubectl rollout restart <type> <name>
replicas: 3
Rolling restart of a resource. strategy:
kubectl scale --replicas=3 <type> <name> type: RollingUpdate
selector:
Scale a resource to a number of replicas. matchLabels: {'app': 'mima-app'}
template:
metadata:
TROUBLESHOOTING labels: {'app': 'mima-app'}
spec:
When things go south start investigating.
containers:
kubectl get <type> <name> - name: mima-app-container
image: ...
If you identify a faulty resource, start by investigating its details. ports:
kubectl logs <pod> - containerPort: 3000
resources:
Get logs of a specific pod.
limits:
kubectl logs <pod> -f memory: "256M"
Stream and follow the logs in real-time. cpu: "500m"
livenessProbe:
kubectl logs <pod> --previous httpGet:
See the log output of the previous container, if still available. port: 3000
kubectl exec <pod> -- curl localhost:8080 path: '/actuator/info'
A deployment manifest with some important properties set.
Execute a command on a pod.
kubectl exec <pod> -it -- /bin/sh ---
apiVersion: v1
Start an interactive shell on the pod. kind: Service
kubectl port-forward <pod> 8080:6000 metadata:
name: mima-app-service
Port-forwarding from a pod to your local machine.
spec:
kubectl get events type: ClusterIP
View cluster/namespace events. ports:
- port: 3000
kubectl top pods selector: {'app': 'mima-app'}
View CPU and memory usage for all pods. A service exposing the above deployment.

GENERAL OPTIONS
These general options are useful from time to time.

kubectl --namespace <namespace>


Apply the command to a specific namespace. TT
kubectl --v=<0..9>
Increase log output to even see HTTP requests starting at level 7.

k8s-cheat-sheet.docx/Publication Date Seite 2 von 2


Cheat Sheet Version: 2021-01-21
Get the latest version on go.mimacom.com/k8s
KUBERNETES Master Kubectl Command List
• Pods and Container Introspection • Objects
• It is responsible for maintaining the desired state for the cluster you

CHEAT SHEET
are working on. COMMANDS FUNCTION All clusterrolebindings clusterroles
• “Master” indicates a set of processes that are used to manage the
Kubectl get pods Lists all current pods crd=custom
cluster.
cm= conf gmaps controllerrevisions resource
• Contains info, API, scheduler, replication controllers, and master.
Kubectl describe pod<name> Describes the pod names definition
KUBERNETES
Kubectl get rc List all replication controllers csr= certificate
Cronjobs cs=component status
• It is an open source platform for automating deployment and signing requests
scaling of containers across clusters of hosts providing Kubectl get rc -- Lists replication controllers in
container centric infrastructure. Deploy=deployments ds= daemon sets ep=end points
namespace=”namespace” namespace
• It is a container orchestrator and can run Linux containers:
• Launch container. ev= events hpa= autoscaling ing= ingress
• Maintain and monitor container site. Shows the replication
Kubectl describe rc <name> Netpol- network
• Performs container-oriented networking controller name jobs limits=limit ranges
policies
Kubectl get cvc Lists the services
No = nodes ns= namespaces pdb= pod
Worker Nodes/Minions Kubectl describe svc<name> Shows the service name po= pods Pod preset Pod templates
• Also called as a minion. It contains the services necessary to run the
Kubectl delete pod<name> Deletes the pod Psp= pod security Pv= persistent pvc= persistent
pods that are managed by the master.
policies volumes volume claims
• Some services include: container runtime, Kubelet, kube-proxy. Kubectl get nodes -w Watch nodes continuously
• Contains: Kubelet, cAdvisor, services, pods and containers. quota= resource rc= replication
• Debugging Role bindings
quotas controllers

FUNCTION COMMAND sa=service


roles rs= replica sets
account
Kubectl
Execute command on service by
exec<service><commands>[- sc= storage classes secrets sts= stateful sets
Key Concepts selecting container.
c< $container>] • Cluster Introspection
Now let’s discuss the key points of this architecture. Kubectl logs -f<name>>[-c< FUNCTION COMMAND
Get logs from service for a container
$container>]
• Pod: These are the group of containers.
Get version information Kubectl version
• Labels: These are used to identify the pods.
• Kubelet: They are container agents, responsible for maintaining Watch -n 2
Watch the kubelet logs Get cluster information Kubectl cluster-info
the set of pods. cat/var/log/kublet.log
• Proxy: They are the Load balancer for pods, helping in
distributing tasks across the pods. Show metrics for node Kubectl top node Get the configuration Kubectl config g view
• ETCD: A Metadata service.
• Cadvisor: For resource usage and performance stats. Show metrics for pods Kubectl top pod Output info about a node Kubectl describe node<node>
• Replication controller: It manages pod replication. Features
• Scheduler: Used for pod scheduling in worker nodes.
• API server: Kubernetes API server. • Automated scheduling- provides an advanced scheduler that helps
launch container on cluster nodes Other Quick Commands
Now let’s understand the role Master and Node play in the • Self healing- reschedule, replace and restart dead containers.
Kubernetes Architecture. • Automated rollouts and rollbacks- supports rollback for systems Launch a pod with a name an image : Kubectl run<name> -- Map external port to internal replication port : Expose rc<name> -
incase of a failure. Enables rollout and rollback for the desired state. image=<image-name> -port=<external>--target-port=<internal>
• Horizontal scaling- can scale up and down the app as per required. Can Create a service in <manifest.yaml> : Kubectl create -f To stop all pod in <n> : Kubectl drain<n>-- delete-local-data--force--
also be automated wrt CPU usage. <manifest.yaml> ignore-daemonset
• Service discovery and load balancing- uses unique ip and dns name to Scale replication counter to count the number of instances Allow master nodes to run pods : Kubectltaintnodes --all-node-
containers. This helps identify them across different containers. : Kubectl scale --replicas=<count> role.kuernetes.io/master-
FURTHERMORE: Kubernetes Training

You might also like