top of page

Kubernetes Cheat Sheet

Writer's picture: Rex AndrewRex Andrew



This page contains a list of commonly used kubectl commands and flags.




Kubectl apply - Creating objects


# create resource(s)

kubectl apply -f ./my-manifest.yaml
   

# create from multiple files

kubectl apply -f ./my1.yaml -f ./my2.yaml     

# create resource(s) in all manifest files in dir

kubectl apply -f ./dir  

# create resource(s) from url

kubectl apply -f https://git.io/vPieo 

# create a Job which prints "Hello World"

kubectl create job hello --image=busybox:1.28 -- echo "Hello World"

# create a CronJob that prints "Hello World" every minute

kubectl create cronjob hello --image=busybox:1.28   --schedule="*/1 * * * *" -- echo "Hello World"


Viewing the Resources


# Get commands with basic output

kubectl get services                         
kubectl get pods --all-namespaces            
kubectl get pods -o wide                     
kubectl get deployment my-dep                
kubectl get pods                             
kubectl get pod my-pod -o yaml               

# Describe commands with verbose output

kubectl describe nodes my-node
kubectl describe pods my-pod

# List Services Sorted by Name

kubectl get services --sort-by=.metadata.name

# List pods Sorted by Restart Count

kubectl get pods --sort-by='.status.containerStatuses[0].restartCount'

# List PersistentVolumes sorted by capacity

kubectl get pv --sort-by=.spec.capacity.storage

# Get the version label of all pods with label app=cassandra

kubectl get pods --selector=app=cassandra -o \
  jsonpath='{.items[*].metadata.labels.version}'

# Retrieve the value of a key with dots, e.g. 'ca.crt'

kubectl get configmap myconfig \
  -o jsonpath='{.data.ca\.crt}'

# Retrieve a base64 encoded value with dashes instead of underscores.

kubectl get secret my-secret --template='{{index .data "key-name-with-dashes"}}'

# Get all worker nodes (use a selector to exclude results that have a label

# named 'node-role.kubernetes.io/control-plane')

kubectl get node --selector='!node-role.kubernetes.io/control-plane'

# Get all running pods in the namespace

kubectl get pods --field-selector=status.phase=Running

# Get ExternalIPs of all nodes

kubectl get nodes -o jsonpath='{.items[*].status.addresses[?(@.type=="ExternalIP")].address}'

# List all containerIDs of initContainer of all pods

# Helpful when cleaning up stopped containers, while avoiding removal of initContainers.

kubectl get pods --all-namespaces -o jsonpath='{range .items[*].status.initContainerStatuses[*]}{.containerID}{"\n"}{end}' | cut -d/ -f3

# List Events sorted by timestamp

kubectl get events --sort-by=.metadata.creationTimestamp

# List all warning events

kubectl events --types=Warning

# Compares the current state of the cluster against the state that the cluster would be in if the manifest was applied.

kubectl diff -f ./my-manifest.yaml

# Get a deployment's status subresource

kubectl get deployment nginx-deployment --subresource=status


Updating resources


# Rolling update "www" containers of "frontend" deployment, updating the image

kubectl set image deployment/frontend www=image:v2    

# Check the history of deployments including the revision

kubectl rollout history deployment/frontend   

# Rollback to the previous deployment

kubectl rollout undo deployment/frontend      

# Rollback to a specific revision

kubectl rollout undo deployment/frontend --to-revision=2 

# Watch rolling update status of "frontend" deployment until completion

kubectl rollout status -w deployment/frontend       

# Rolling restart of the "frontend" deployment

kubectl rollout restart deployment/frontend                    

# Force replace, delete and then re-create the resource. Will cause a service outage.

kubectl replace --force -f ./pod.json

# Create a service for a replicated nginx, which serves on port 80 and connects to the containers on port 8000

kubectl expose rc nginx --port=80 --target-port=8000


Editing resources


# Edit the deploy file

kubectl edit deploy deploy.yaml                      

Scaling resources

# Scale a replicaset named 'foo' to 3

kubectl scale --replicas=3 rs/foo

# Scale a resource specified in "foo.yaml" to 3

kubectl scale --replicas=3 -f foo.yaml 

# If the deployment named mysql's current size is 2, scale mysql to 3

kubectl scale --current-replicas=2 --replicas=3 deployment/mysql  

# Scale multiple replication controllers

kubectl scale --replicas=5 rc/foo rc/bar rc/baz                 

Deleting resources


# Delete a pod using the type and name specified in pod.json

kubectl delete -f ./pod.json              

# Delete a pod with no grace period

kubectl delete pod unwanted --now      

# Delete pods and services with same names "baz" and "foo"

kubectl delete pod,service baz foo         

# Delete pods and services with label name=myLabel

kubectl delete pods,services -l name=myLabel  

# Delete all pods and services in namespace my-ns,

kubectl -n my-ns delete pod,svc --all                        

# Delete all pods matching the awk pattern1 or pattern2

kubectl get pods  -n mynamespace --no-headers=true | awk '/pattern1|pattern2/{print $1}' | xargs  kubectl delete -n mynamespace pod


Interacting with running Pods



kubectl logs my-pod                               
kubectl logs -l name=myLabel                        
kubectl logs my-pod --previous                     
kubectl logs my-pod -c my-container               
kubectl logs my-pod -c my-container --previous   
kubectl logs -f my-pod                          
kubectl logs -f my-pod -c my-container            
kubectl logs -f -l name=myLabel --all-containers  


# Show metrics for a given pod and its containers

kubectl top pod POD_NAME --containers              
kubectl top pod POD_NAME --sort-by=cpu           

Interacting with Deployments and Services

kubectl logs deploy/my-deployment                        
kubectl logs deploy/my-deployment -c my-container       

# listen on local port 5000 and forward to port 5000 on Service backend

kubectl port-forward svc/my-service 5000           

# listen on local port 5000 and forward to Service target port with name <my-service-port>

kubectl port-forward svc/my-service 5000:my-service-port 

# listen on local port 5000 and forward to port 6000 on a Pod created by <my-deployment>

kubectl port-forward deploy/my-deployment 5000:6000     

# run command in first Pod and first container in Deployment (single- or multi-container cases)

kubectl exec deploy/my-deployment -- ls         

Interacting with Nodes and cluster


# Mark my-node as unschedulable

kubectl cordon my-node  

# Drain my-node in preparation for maintenance

kubectl drain my-node    

# Mark my-node as schedulable

kubectl uncordon my-node         

# Show metrics for a given node

kubectl top node my-node 

# Display addresses of the master and services

kubectl cluster-info              

# Dump current cluster state to stdout

kubectl cluster-info dump   

# Dump current cluster state to /path/to/cluster-state

kubectl cluster-info dump --output-directory=/path/to/cluster-state  


Source : https://kubernetes.io/docs/reference/kubectl/cheatsheet/#updating-resources


Kubernetes Sample Yaml Files

Here the Sample Deployment and Service yaml file to deploy the application start pods in the existing node. deployment.yaml apiVersion:...

Comments


bottom of page