Skip to content

Kubectl Kubernetes CheatSheet

Common Commands

NameCommand
List everythingkubectl get all --all-namespaces
List pods with nodes infokubectl get pod -o wide
Validate yaml file with dry runkubectl apply --dry-run --validate -f pod-dummy.yaml
Diff deployed resource with local yaml filekubectl alpha diff -f <yaml file/dir>
Start a temporary pod for testingkubectl run --rm -i -t --image=alpine test-$RANDOM -- sh
Run wget test temporarilykubectl run --rm mytest --image=busybox -it
Run curl test temporarilykubectl run --rm mytest --image=yauritux/busybox-curl -it
kubectl run shell commandkubectl exec -it mytest -- ls -l /etc/hosts
Get system conf via configmapkubectl -n kube-system get cm kubeadm-config -o yaml
kubectl run instance with replicaskubectl run my-nginx --image=nginx --replicas=2 --port=80
Explain resourcekubectl explain pods=, kubectl explain svc
Get all serviceskubectl get service --all-namespaces
Query healthcheck endpointcurl -L http://127.0.0.1:10250/healthz
Open a bash terminal in a podkubectl exec -it storage sh
Check pod environment variableskubectl exec redis-master-ft9ex env
Enable kubectl shell autocompletionecho "source <(kubectl completion bash)" >>~/.bashrc, and reload
Use minikube dockerd in your laptopeval $(minikube docker-env), No need to push docker hub any more
Get services sorted by namekubectl get services --sort-by=.metadata.name
Get pods sorted by restart countkubectl get pods --sort-by='.status.containerStatuses[0].restartCount'
Get logs from init containerkubectl logs <pod-name> -c <init-container-2
Drain a nodeskubectl drain <node_name> --delete-local-data --ignore-daemonsets

Check Performance

NameCommand
Get node resource usagekubectl top node
Get pod resource usagekubectl top pod
Get resource usage for a given podkubectl top <podname> --containers
List resource utilization for all containerskubectl top pod --all-namespaces --containers=true

Resources Deletion

NameCommand
Delete podkubectl delete pod/<pod-name> -n <my-namespace>
Force deletekubectl delete pod NAME --grace-period=0 --force
Delete pods by labelskubectl delete pod -l env=test
Delete deployments by labelskubectl delete deployment -l app=wordpress
Delete all resources filtered by labelskubectl delete pods,services -l name=myLabel
Delete resources under a namespacekubectl -n my-ns delete po,svc --all
Delete persist volumes by labelskubectl delete pvc -l app=wordpress
Delete statefulset only (not pods)kubectl delete sts/<stateful_set_name> --cascade=false

Pod

NameCommand
List all podskubectl get pods
List pods for all namespacekubectl get pods -all-namespaces
List all critical podskubectl get -n kube-system pods -a
List pods with more infokubectl get pod -o wide=, kubectl get pod/<pod-name> -o yaml
Get pod infokubectl describe pod/srv-mysql-server
List all pods with labelskubectl get pods --show-labels
kubectl run commandkubectl exec -it -n "$ns" "$podname" -- sh -c "echo $msg >>/dev/err.log"

Pod Advanced

NameCommand
Get pod by selectorkubectl get pods -n $namespace --selector="app=syslog" -o jsonpath='{.items[*].metadata.name}')
List pods and containerskubectl get pods -o='custom-columns=PODS:.metadata.name,CONTAINERS:.spec.containers[*].name'
List pods, containers and imageskubectl get pods -o='custom-columns=PODS:.metadata.name,CONTAINERS:.spec.containers[*].name,Images:.spec.containers[*].image'

Label & Annotations

NameCommand
Filter pods by labelkubectl get pods -l owner=denny
Manually add label to a podkubectl label pods dummy-input owner=denny
Remove labelkubectl label pods dummy-input owner-
Manually add annonation to a podkubectl annotate pods dummy-input my-url=https://www.dennyzhang.com

Deployment & Scale

NameCommand
Scale outkubectl scale --replicas=3 deployment/nginx-app
Online rolling upgradekubectl rollout app-v1 app-v2 --image=img:v2
Roll backupkubectl rollout app-v1 app-v2 --rollback
List rolloutkubectl get rs
Check update statuskubectl rollout status deployment/nginx-app
Check update historykubectl rollout history deployment/nginx-app
Pause/Resumekubectl rollout pause deployment/nginx-deployment=, resume
Rollback to previous versionkubectl rollout undo deployment/nginx-deployment

Quota & Limits & Resource

NameCommand
List Resource Quotakubectl get resourcequota
List Limit Rangekubectl get limitrange
Customize resource definitionkubectl set resources deployment nginx -c=nginx --limits=cpu=200m,memory=512Mi

Service

NameCommand
List all serviceskubectl get services
List service endpointskubectl get endpoints
Get service detailkubectl get service nginx-service -o yaml
Expose deployment as lb servicekubectl expose deployment/my-app --type=LoadBalancer --name=my-service
Expose service as lb servicekubectl expose service/wordpress-1-svc --type=LoadBalancer --name=wordpress-lb

StatefulSet

NameCommand
List statefulsetkubectl get sts
Delete statefulset only (not pods)kubectl delete sts/<stateful_set_name> --cascade=false
Scale statefulsetkubectl scale sts/<stateful_set_name> --replicas=5

Volumes & Volume Claims

NameCommand
Check the mounted volumeskubectl exec storage ls /data
Check persist volumekubectl describe pv/pv0001
List storage classkubectl get storageclass
Copy fileskubectl cp /tmp/foo <namespace1>/<pod1>:/tmp/bar

Security

NameCommand
List certificateskubectl get csr

Extenstions

NameSummary
List api groupkubectl api-versions
List all CRDkubectl get crd

Components & Services

Services on Master Nodes

NameSummary
kube-apiserverexposes the Kubernetes API from master nodes
etcdreliable data store for all k8s cluster data
kube-schedulerschedule pods to run on selected nodes
kube-controller-managernode controller, replication controller, endpoints controller, and service account & token controllers

Services on Worker Nodes

NameSummary
kubeletmakes sure that containers are running in a pod
kube-proxyperform connection forwarding
Container RuntimeKubernetes supported runtimes: Docker, rkt, runc and any OCI runtime-spec implementation.

Tools

NameSummary
kubectlthe command line util to talk to k8s cluster
kubeadmthe command to bootstrap the cluster
kubefedthe command line to control a Kubernetes Cluster Federation
Kubernetes ComponentsKubernetes Components

Other Components

Log files

NameCommand
API Server.log in master node/var/log/kube-apiserver.log
Scheduler.log in master node/var/log/kube-scheduler.log
Controller.log in master node/var/log/kube-controller-manager.log
Kubelet.log in worker node/var/log/kubelet.log
Kube Proxy.log in worker node/var/log/kubelet-proxy.log

Events & Metrics

NameCommand
View all eventskubectl get events --all-namespaces

Namespace & Security

NameCommand
List authenticated contextskubectl config get-contexts
Switch contextkubectl config use-context <cluster-name>
Delete the specified contextkubectl config delete-context <cluster-name>
List all namespaces definedkubectl get namespaces
kubectl config file~/.kube/config

Network

NameCommand
Temporarily add a port-forwardingkubectl port-forward redis-izl09 6379
Add port-forwaring for deploymentkubectl port-forward deployment/redis-master 6379:6379
Add port-forwaring for replicasetkubectl port-forward rs/redis-master 6379:6379
Add port-forwaring for servicekubectl port-forward svc/redis-master 6379:6379
Get network policykubectl get NetworkPolicy

Basic

Key Concepts

NameSummary
CNCFCloud Native Computing Foundation
CRIContainer Runtime Interface
CNIContainer Network Interface
CSIContainer Storage Interface

Kubernetes Critical Files

NameComment
Config folder/etc/kubernetes/
Certificate files/etc/kubernetes/pki/
Credentials to API server/etc/kubernetes/kubelet.conf
Superuser credentials/etc/kubernetes/admin.conf
Kubernets working dir/var/lib/kubelet/
Docker working dir/var/lib/docker/
Etcd working dir/var/lib/etcd/
Network cni/etc/cni/net.d/
Docker container log/var/log/containers/
Log files/var/log/pods/
Envexport KUBECONFIG=/etc/kubernetes/admin.conf
Env/etc/systemd/system/kubelet.service.d/10-kubeadm.conf

Check status

NameSummary
List everythingkubectl get all --all-namespaces
Get cluster infokubectl cluster-info
Get configurationkubectl config view
Get kubectl versionkubectl version
Get component statuskubectl get componentstatus
Similar to docker ps kubectl get nodes
Similar to docker inspect kubectl describe pod/nginx-app-413181-cn
Similar to docker logs kubectl logs
Similar to docker exec kubectl exec
Get services for current namespacekubectl get svc
Get node statuskubectl describe node/<node_name>

Names of certificates files

Names of certificates files:

  • ca.crt, ca.key (CA certificate)
  • apiserver.crt, apiserver.key (API server certificate)
  • apiserver-kubelet-client.crt, apiserver-kubelet-client.key (client certificate for the apiservers to connect to the kubelets securely)
  • sa.pub, sa.key (a private key for signing ServiceAccount )
  • front-proxy-ca.crt, front-proxy-ca.key (CA for the front proxy)
  • front-proxy-client.crt, front-proxy-client.key (client cert for the front proxy client)

Misc scripts

Tail pod log by label

bash
namespace="mynamespace"
mylabel="app=mylabel"
kubectl get pod -l "$mylabel" -n "$namespace" | tail -n1 \
    | awk -F' ' '{print $1}' | xargs -I{} \
      kubectl logs -n "$namespace" -f {}

Get node hardware resource utilization

bash
kubectl get nodes --no-headers \
     | awk '{print $1}' | xargs -I {} \
     sh -c 'echo {}; kubectl describe node {} | grep Allocated -A 5'

kubectl get nodes --no-headers | awk '{print $1}' | xargs -I {} \
    sh -c 'echo {}; kubectl describe node {} | grep Allocated -A 5 \
     | grep -ve Event -ve Allocated -ve percent -ve -- ; echo'

Apply yaml files recursively

bash
# create
time ls -1 */*.yml | grep -v namespace | xargs -I{} kubectl apply -f {}

# delete
time ls -1r */*.yml | grep -v namespace | xargs -I{} kubectl delete -f {}

Apply the configuration in manifest.yaml and delete all the other configmaps that are not in the file.

bash
kaubectl apply --prune -f manifest.yaml --all --prune-whitelist=core/v1/ConfigMap

List all critical pods

bash
kubectl --namespace kube-system get pods

for pod in $(kubectl --namespace kube-system get pods -o jsonpath="{.items[*].metadata.name}"); do
    node_info=$(kubectl --namespace kube-system describe pod $pod | grep "Node:")
    echo "Pod: $pod, $node_info"
done

Helm: The Kubernetes Package Manager

NameSummary
Helma chart manager.
Chartspackages of pre-configured Kubernetes resources.
Releasea collection of Kubernetes resources deployed to the cluster using Helm.
tillerhelm server manages releases (installations) of your charts.
NameSummary
helm init
helm list
helm list -a
helm repo update
helm install stable/mysql
helm install --name mysql-release stable/mysql
helm inspect stable/mysql
helm status $helm_name
helm delete $helm_name
helm delete --purge $helm_name
~/.helm/cache/archive

Release, list, inspect, delete, rollback, purge

Metric Server

Metrics Server is a cluster-wide aggregator of resource usage data. Metrics Server registered in the main API server through Kubernetes aggregator.

NameSummary
Core metricsnode/container level metrics; CPU, memory, disk and network, etc.
Custom metricsrefers to application metrics, e.g. HTTP request rate.

Today (Kubernetes 1.7), there are several sources of metrics within a Kubernetes cluster

NameSummary
Heapsterk8s add-on
Cadvisora standalone container/node metrics collection and monitoring tool.
Kubernetes APIdoes not track metrics. But can get real time metrics

Today, heapster is the source of the time-series data for the Kubernetes Dashboard. All other Kubernetes components will supply their own metrics in a Prometheus format

In logging domain, we can say syslog is the standard format In metric domain, maybe we can choose prometheus as the standard format.