Skip to content

Instantly share code, notes, and snippets.

@naviat
Last active December 8, 2020 21:42
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save naviat/446d1be0a5a03bad1d7113d1abf082c7 to your computer and use it in GitHub Desktop.
Save naviat/446d1be0a5a03bad1d7113d1abf082c7 to your computer and use it in GitHub Desktop.
Kubectl cheatsheet list

Kubectl Kubernetes CheatSheet

Common Commands

NameCommand
Run curl test temporarilykubectl run --rm mytest --image=yauritux/busybox-curl -it
Run wget test temporarilykubectl run --rm mytest --image=busybox -it
Run nginx deployment with 2 replicaskubectl run my-nginx --image=nginx --replicas=2 --port=80
Run nginx pod and expose itkubectl run my-nginx --restart=Never --image=nginx --port=80 --expose
Run nginx deployment and expose itkubectl run my-nginx --image=nginx --port=80 --expose
Set namespace preferencekubectl config set-context <context_name> --namespace=<ns_name>
List pods with nodes infokubectl get pod -o wide
List everythingkubectl get all --all-namespaces
Get all serviceskubectl get service --all-namespaces
Show nodes with labelskubectl get nodes --show-labels
Validate yaml file with dry runkubectl create --dry-run --validate -f pod-dummy.yaml
Start a temporary pod for testingkubectl run --rm -i -t --image=alpine test-$RANDOM -- sh
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
Get deployment yamlkubectl -n denny-websites get deployment mysql -o yaml
Explain resourcekubectl explain pods, kubectl explain svc
Watch podskubectl get pods -n wordpress --watch
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
Kubectl apply a folder of yaml fileskubectl apply -R -f .
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’
List all container imageslist-all-images.sh
kubeconfig skip tls verificationskip-tls-verify.md

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>
Delete pod by forcekubectl delete pod/<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

Log & Conf 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
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 nodekube-apiserver.log, kube-scheduler.log, kube-controller-manager.log
Env/etc/systemd/system/kubelet.service.d/10-kubeadm.conf
Envexport KUBECONFIG=/etc/kubernetes/admin.conf

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
List running podskubectl get pods –field-selector=status.phase=Running
Get Pod initContainer statuskubectl get pod --template '{{.status.initContainerStatuses}}' <pod-name>
kubectl run commandkubectl exec -it -n “$ns” “$podname” – sh -c “echo $msg >>/dev/err.log”
Watch podskubectl get pods -n wordpress --watch
Get pod by selectorkubectl get pods –selector=”app=syslog” -o jsonpath=’{.items[*].metadata.name}’
List pods and imageskubectl 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’

Label & Annontation

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://haidv.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
Customize resource definitionkubectl set resources deployment nginx -c=nginx --limits=memory=512Mi
ReferenceLink: kubernetes yaml templates

Service

NameCommand
List all serviceskubectl get services
List service endpointskubectl get endpoints
Get service detailkubectl get service nginx-service -o yaml
Get service cluster ipkubectl get service nginx-service -o go-template=’{{.spec.clusterIP}}’
Get service cluster portkubectl get service nginx-service -o go-template=’{{(index .spec.ports 0).port}}’
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=ns1

Secrets

NameCommand
List secretskubectl get secrets --all-namespaces
Generate secretecho -n 'mypasswd'=, then redirect to =base64 -decode
Create secret from cfg filekubectl create secret generic db-user-pass –from-file=./username.txt

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
ReferenceLink: kubernetes yaml templates

Volumes & Volume Claims

NameCommand
List storage classkubectl get storageclass
Check the mounted volumeskubectl exec storage ls /data
Check persist volumekubectl describe pv/pv0001
Copy local file to podkubectl cp /tmp/my <some-namespace>/<some-pod>:/tmp/server
Copy pod file to localkubectl cp <some-namespace>/<some-pod>:/tmp/server /tmp/my

Events & Metrics

NameCommand
View all eventskubectl get events --all-namespaces
List Events sorted by timestampkubectl get events –sort-by=.metadata.creationTimestamp

Node Maintenance

NameCommand
Mark node as unschedulablekubectl cordon $NDOE_NAME
Mark node as schedulablekubectl uncordon $NDOE_NAME
Drain node in preparation for maintenancekubectl drain $NODE_NAME

Namespace & Security

NameCommand
List authenticated contextskubectl config get-contexts, ~/.kube/config
Set namespace preferencekubectl config set-context <context_name> --namespace=<ns_name>
Load context from config filekubectl get cs --kubeconfig kube_config.yml
Switch contextkubectl config use-context <cluster-name>
Delete the specified contextkubectl config delete-context <cluster-name>
List all namespaces definedkubectl get namespaces
List certificateskubectl get csr

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

Patch

NameSummary
Patch service to loadbalancer=kubectl patch svc $svc_name -p ‘{“spec”: {“type”: “LoadBalancer”}}’=

Extenstions

NameSummary
List api groupkubectl api-versions
List all CRDkubectl get crd
List storageclasskubectl get storageclass
List all supported resourceskubectl api-resources

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.

Addons: pods and services that implement cluster features

NameSummary
DNSserves DNS records for Kubernetes services
Web UIa general purpose, web-based UI for Kubernetes clusters
Container Resource Monitoringcollect, store and serve container metrics
Cluster-level Loggingsave container logs to a central log store with search/browsing interface

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 ComponentsLink: Kubernetes Components
#!/usr/bin/env bash
kubectl get pods --all-namespaces -o jsonpath="{..image}" |\
tr -s '[[:space:]]' '\n' |\
sort |\
uniq -c
apiVersion: v1
clusters:
- cluster:
    server: https://192.168.0.100:8443
    insecure-skip-tls-verify: true
  name: minikube
contexts:
- context:
    cluster: minikube
    user: minikube
  name: minikube
current-context: minikube
kind: Config
preferences: {}
users:
- name: minikube
  user:
    client-certificate: C:\Users\wes.robinson\.minikube\client.crt
    client-key: C:\Users\wes.robinson\.minikube\client.key

hashicorp/terraform-provider-kubernetes#189

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment