Kubectl Cheat Sheet

Configuration and Context Management

Show Specifed Kubeconfig Settings

Bash
kubectl config view

Use Multiple Kubeconfig Files

Bash
KUBECONFIG=~/.kube/config:~/.kube/kubconfig2
kubectl config view

Get User Password

Bash
kubectl config view -o jsonpath='{.users[?(@.name == "user")].user.password}'

Display Contexts and Switch

Bash
kubectl config get-contexts
kubectl config current-context
kubectl config use-context {my-cluster-name}

Set Cluster Entry and Proxy URL

Bash
kubectl config set-cluster my-cluster-name
kubectl config set-cluster my-cluster-name --proxy-url=my-proxy-url

Add a New User and Set Namespace

Bash
kubectl config set-credentials kubeuser/foo.kubernetes.com --username=kubeuser --password=kubepassword
kubectl config set-context --current --namespace=testnamespace

Context and Namespace Short Aliases

Bash
alias kx='f() { [ "$1" ] && kubectl config use-context $1 || kubectl config current-context ; } ; f'
alias kn='f() { [ "$1" ] && kubectl config set-context --current --namespace $1 || kubectl config view --minify | grep namespace | cut -d" " -f6 ; } ; f'

Applying and Managing Resources

Apply Manifests

Bash
kubectl apply -f ./my-manifest.yaml            # create resource(s)
kubectl apply -f ./my1.yaml -f ./my2.yaml      # create from multiple files
kubectl apply -f ./dir                         # create resource(s) in all manifest files in dir
kubectl apply -f https://git.io/vPieo          # create resource(s) from url
kubectl create deployment nginx --image=nginx  # start a single instance of nginx

Create Job and CronJob

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

Explain and Create Multiple YAML Objects

Bash
kubectl explain pods
kubectl apply -f - <<EOF
apiVersion: v1
kind: Pod
metadata:
  name: busybox-sleep
# ... (continues)
EOF

Create Secret with Several Keys

Bash
kubectl apply -f - <<EOF
apiVersion: v1
kind: Secret
metadata:
  name: mysecret
type: Opaque
data:
  password: $(echo -n "p@sswd" | base64 -w0)
  username: $(echo -n "jhon" | base64 -w0)
EOF

View and Find Resources

Bash
kubectl get services                          # List all services in the namespace
kubectl get pods --all-namespaces             # List all pods in all namespaces
kubectl get pods -o wide                      # List all pods in the current namespace, with more details
kubectl get deployment my-dep                 # List a particular deployment
kubectl get pods                              # List all pods in the namespace
kubectl get pod my-pod -o yaml                # Get a pod's YAML

Update Resources and Rollback

Bash
kubectl set image deployment/frontend www=image:v2               # Rolling update "www" containers of "frontend" deployment, updating the image
kubectl rollout history deployment/frontend                      # Check the history of deployments including the revision
kubectl rollout undo deployment/frontend                         # Rollback to the previous deployment
kubectl rollout undo deployment/frontend --to-revision=2         # Rollback to a specific revision
kubectl rollout status -w deployment/frontend                    # Watch rolling update status of "frontend" deployment until completion
kubectl rollout restart deployment/frontend                      # Rolling restart of the "frontend" deployment

Patching Resources and Editing

Bash
kubectl patch node k8s-node-1 -p '{"spec":{"unschedulable":true}}'      # Partially update a node
kubectl patch pod valid-pod -p '{"spec":{"containers":[{"name":"kubernetes-serve-hostname","image":"new image"}]}}'                                      # Update a container's image; spec.containers[*].name is required because it's a merge key
  
kubectl edit svc/docker-registry                                        # Edit the service named docker-registry
KUBE_EDITOR="nano" kubectl edit svc/docker-registry                     # Use an alternative editor

Scaling Resources

Bash
kubectl scale --replicas=3 deployment/test                                 # Scale a deployment named 'test' to 3
kubectl scale --replicas=3 -f test.yaml                            # Scale a resource specified in "test.yaml" to 3
kubectl scale --current-replicas=2 --replicas=3 deployment/mysql  # If the deployment named mysql's current size is 2, scale mysql to 3
kubectl scale --replicas=5 deployment/foo deployment/bar deployment/baz                   # Scale multiple replication controller

Deleting Resources

Bash
kubectl delete -f ./pod.json                                      # Delete a pod using the type and name specified in pod.json
kubectl delete pod unwanted --now                                 # Delete a pod with no grace period
kubectl delete pod,service baz foo                                # Delete pods and services with same names "baz" and "foo"
kubectl delete pods,services -l name=myLabel                      # Delete pods and services with label name=myLabel
kubectl -n my-ns delete pod,svc --all                             # Delete all pods and services in namespace my-ns,
# 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

Logs and Exec Commands

Bash
# Dump pod logs (stdout)
kubectl logs my-pod

# Dump pod logs, with label name=myLabel (stdout)
kubectl logs -l name=myLabel

# Dump pod logs (stdout) for a previous instantiation of a container
kubectl logs my-pod --previous

# Dump pod container logs (stdout, multi-container case)
kubectl logs my-pod -c my-container

# Dump pod container logs, with label name=myLabel (stdout)
kubectl logs -l name=myLabel -c my-container

# Dump pod container logs (stdout, multi-container case) for a previous instantiation of a container
kubectl logs my-pod -c my-container --previous

# Stream pod logs (stdout)
kubectl logs -f my-pod

# Stream pod container logs (stdout, multi-container case)
kubectl logs -f my-pod -c my-container

# Stream all pods logs with label name=myLabel (stdout)
kubectl logs -f -l name=myLabel --all-containers

# Run pod as interactive shell
kubectl run -i --tty busybox --image=busybox:1.28 -- sh

# Start a single instance of nginx pod in the namespace of mynamespace
kubectl run nginx --image=nginx -n mynamespace

# Generate spec for running pod nginx and write it into a file called pod.yaml
kubectl run nginx --image=nginx --dry-run=client -o yaml > pod.yaml

# Attach to Running Container
kubectl attach my-pod -i

# Listen on port 5000 on the local machine and forward to port 6000 on my-pod
kubectl port-forward my-pod 5000:6000

# Run command in existing pod (1 container case)
kubectl exec my-pod -- ls /

# Interactive shell access to a running pod (1 container case)
kubectl exec --stdin --tty my-pod -- /bin/sh

# Run command in existing pod (multi-container case)
kubectl exec my-pod -c my-container -- ls /

# Show metrics for a given pod and its containers
kubectl top pod POD_NAME --containers

# Show metrics for a given pod and sort it by 'cpu' or 'memory'
kubectl top pod POD_NAME --sort-by=cpu

Copying Files to and from Containers

Bash
kubectl cp /tmp/foo_dir my-pod:/tmp/bar_dir            # Copy /tmp/foo_dir local directory to /tmp/bar_dir in a remote pod in the current namespace
kubectl cp /tmp/foo my-pod:/tmp/bar -c my-container    # Copy /tmp/foo local file to /tmp/bar in a remote pod in a specific container
kubectl cp /tmp/foo my-namespace/my-pod:/tmp/bar       # Copy /tmp/foo local file to /tmp/bar in a remote pod in namespace my-namespace
kubectl cp my-namespace/my-pod:/tmp/foo /tmp/bar       # Copy /tmp/foo from a remote pod to /tmp/bar locally

Interacting with Deployments and Services

Bash
kubectl logs deploy/my-deployment                         # dump Pod logs for a Deployment (single-container case)
kubectl logs deploy/my-deployment -c my-container         # dump Pod logs for a Deployment (multi-container case)

kubectl port-forward svc/my-service 5000                  # listen on local port 5000 and forward to port 5000 on Service backend
kubectl port-forward svc/my-service 5000:my-service-port  # listen on local port 5000 and forward to Service target port with name <my-service-port>

kubectl port-forward deploy/my-deployment 5000:6000       # listen on local port 5000 and forward to port 6000 on a Pod created by <my-deployment>
kubectl exec deploy/my-deployment -- ls                   # run command in first Pod and first container in Deployment (single- or multi-container cases)

Interacting with Nodes and Cluster

Bash
kubectl cordon my-node                                                # Mark my-node as unschedulable
kubectl drain my-node                                                 # Drain my-node in preparation for maintenance
kubectl uncordon my-node                                              # Mark my-node as schedulable
kubectl top node my-node                                              # Show metrics for a given node
kubectl cluster-info                                                  # Display addresses of the master and services
kubectl cluster-info dump                                             # Dump current cluster state to stdout
kubectl cluster-info dump --output-directory=/path/to/cluster-state   # Dump current cluster state to /path/to/cluster-state

# View existing taints on which exist on current nodes.
kubectl get nodes -o='custom-columns=NodeName:.metadata.name,TaintKey:.spec.taints[*].key,TaintValue:.spec.taints[*].value,TaintEffect:.spec.taints[*].effect'

Taints and Resource Types

Bash
# View existing taints on current nodes
kubectl get nodes -o='custom-columns=NodeName:.metadata.name,TaintKey:.spec.taints[*].key,TaintValue:.spec.taints[*].value'

# Add a new taint to a node
kubectl taint nodes node-1 key=value:NoSchedule

# Remove a taint from a node
kubectl taint nodes node-1 key:NoSchedule-

# List all supported resource types with details
kubectl api-resources

# List all namespaced resources
kubectl api-resources --namespaced=true

# List all non-namespaced resources
kubectl api-resources --namespaced=false

# List resources with simple output (only resource names)
kubectl api-resources -o name

# List resources with expanded (wide) output
kubectl api-resources -o wide

# List resources that support "list" and "get" verbs
kubectl api-resources --verbs=list,get

# List resources in the "extensions" API group
kubectl api-resources --api-group=extensions

Advanced Operations

Get Custom Resource Definitions (CRDs)

Bash
kubectl get crd

Display Raw Resource Confi

Bash
kubectl get pod my-pod -o=json

Export Resources to YAML

Bash
kubectl get pod my-pod -o=yaml > pod.yaml

Diff Resources Before and After Applying

Bash
kubectl diff -f ./my-manifest.yaml

View Applied Configuration

Bash
kubectl get pod my-pod -o=jsonpath='{.metadata.annotations.kubectl\.kubernetes\.io/last-applied-configuration}'

Generate Manifests for Existing Resources

Bash
kubectl get pod my-pod -o=json > my-pod.json

Namespace Operations

List Pods in a Namespace

Bash
kubectl get pods --namespace=my-namespace

Set the Default Namespace for a Context

Bash
kubectl config set-context --current --namespace=my-namespace

Use a Different Namespace for a Single Command

Bash
kubectl get pods --namespace=other-namespace

Troubleshooting and Debugging

Get Events for a Resource

Bash
kubectl describe pod my-pod
kubectl get events --sort-by=.metadata.creationTimestamp
kubectl events --types=Warning

Check Pod’s ContainerIDs

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

Output Decoded Secrets

Bash
kubectl get secret my-secret -o go-template='{{range $k,$v := .data}}{{"### "}}{{$k}}{{"\n"}}{{$v|base64decode}}{{"\n\n"}}{{end}}'

List Secrets Used by Pods

Bash
kubectl get pods -o json | jq '.items[].spec.containers[].env[]?.valueFrom.secretKeyRef.name' | grep -v null | sort | uniq

Check Nodes’ Readiness

Bash
JSONPATH='{range .items[*]}{@.metadata.name}:{range @.status.conditions[*]}{@.type}={@.status};{end}{end}' \
 && kubectl get nodes -o jsonpath="$JSONPATH" | grep "Ready=True"

List All Pods in Running Phase

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

Output Formatting

Output in JSON Format

Bash
kubectl get pods -o=json
kubectl describe pod my-pod -o=json

Custom Output Using JSONPath

Bash
kubectl get nodes -o json | jq -c 'paths|join(".")'
kubectl get pods -o json | jq -c 'paths|join(".")'

Output in YAML Format

Bash
kubectl get pods -o=yaml
kubectl describe pod my-pod -o=yaml

Custom Output Columns

Bash
kubectl get pods -o=custom-columns=NAME:.metadata.name,STATUS:.status.phase
kubectl get nodes -o=custom-columns='NODE_NAME:.metadata.name,STATUS:.status.conditions[?(@.type=="Ready")].status'

Debugging and Verbosity

Display API Requests

Bash
kubectl get pods --v=8
kubectl describe pod my-pod --v=9

Display HTTP Request Headers

Bash
kubectl get pods --v=7

Display HTTP Request Contents

Bash
kubectl get pods --v=8

Table Of Commands

CommandDescription
kubectl config viewShow specified Kubeconfig settings
KUBECONFIG=~/.kube/config:~/.kube/kubconfig2 kubectl config viewUse multiple Kubeconfig files
kubectl config view -o jsonpath='{.users[?(@.name == "user")].user.password}'Get user password
kubectl config get-contextsDisplay contexts
kubectl config current-contextDisplay the current context
kubectl config use-context {my-cluster-name}Switch to a specific context
kubectl config set-cluster my-cluster-nameSet cluster entry
kubectl config set-cluster my-cluster-name --proxy-url=my-proxy-urlSet cluster entry and proxy URL
kubectl config set-credentials kubeuser/foo.kubernetes.com --username=kubeuser --password=kubepasswordAdd a new user and set namespace
kubectl config set-context --current --namespace=testnamespaceSet the namespace for the current context
`alias kx=’f() { [ “$1” ] && kubectl config use-context $1
`alias kn=’f() { [ “$1” ] && kubectl config set-context –current –namespace $1
kubectl apply -f ./my-manifest.yamlApply manifests to create resource(s)
kubectl apply -f ./my1.yaml -f ./my2.yamlApply from multiple files
kubectl apply -f ./dirApply resource(s) in all manifest files in a directory
kubectl apply -f https://git.io/vPieoApply resource(s) from URL
kubectl create deployment nginx --image=nginxCreate a deployment with a specified image
kubectl create job hello --image=busybox:1.28 -- echo "Hello World"Create a job
kubectl create cronjob hello --image=busybox:1.28 --schedule="*/1 * * * *" -- echo "Hello World"Create a cron job
kubectl explain podsExplain and create multiple YAML objects
kubectl apply -f - <<EOF...EOFCreate multiple YAML objects from stdin
kubectl apply -f - <<EOF...EOFCreate a secret with several keys
kubectl get servicesView services in the namespace
kubectl get pods --all-namespacesList pods in all namespaces
kubectl get pods -o wideList pods in the current namespace with more details
kubectl get deployment my-depList a particular deployment
kubectl get podsList all pods in the namespace
kubectl get pod my-pod -o yamlGet a pod’s YAML
kubectl set image deployment/frontend www=image:v2Update resources – rolling update
kubectl rollout history deployment/frontendCheck deployment history
kubectl rollout undo deployment/frontendRollback to the previous deployment
kubectl rollout undo deployment/frontend --to-revision=2Rollback to a specific revision
kubectl rollout status -w deployment/frontendWatch rolling update status
kubectl rollout restart deployment/frontendRolling restart of the deployment
kubectl patch node k8s-node-1 -p '{"spec":{"unschedulable":true}}'Patch node to mark as unschedulable
kubectl patch pod valid-pod -p '{"spec":{"containers":[{"name":"kubernetes-serve-hostname","image":"new image"}]}}'Patch pod container’s image
kubectl edit svc/docker-registryEdit the service named docker-registry
KUBE_EDITOR="nano" kubectl edit svc/docker-registryUse an alternative editor
kubectl scale --replicas=3 deployment/testScale a deployment to 3 replicas
kubectl scale --replicas=3 -f test.yamlScale a resource specified in “test.yaml” to 3
kubectl scale --current-replicas=2 --replicas=3 deployment/mysqlScale deployment if current size is 2
kubectl scale --replicas=5 deployment/foo deployment/bar deployment/bazScale multiple replication controllers
kubectl delete -f ./pod.jsonDelete a pod using the type and name specified in pod.json
kubectl delete pod unwanted --nowDelete a pod with no grace period
kubectl delete pod,service baz fooDelete pods and services with specified names
kubectl delete pods,services -l name=myLabelDelete pods and services with label name=myLabel
kubectl -n my-ns delete pod,svc --allDelete all pods and services in namespace my-ns
`kubectl get pods -n mynamespace –no-headers=trueawk ‘/pattern1
kubectl logs my-podDump pod logs (stdout)
kubectl logs -l name=myLabelDump pod logs with label name=myLabel (stdout)
kubectl logs my-pod --previousDump pod logs for a previous instantiation of a container
kubectl logs my-pod -c my-containerDump pod container logs (stdout, multi-container case)
kubectl logs -l name=myLabel -c my-containerDump pod container logs with label name=myLabel (stdout)
kubectl logs my-pod -c my-container --previousDump pod container logs for a previous instantiation of a container
kubectl logs -f my-podStream pod logs (stdout)
kubectl logs -f my-pod -c my-containerStream pod container logs (stdout, multi-container case)
kubectl logs -f -l name=myLabel --all-containersStream all pods logs with label name=myLabel (stdout)
kubectl run -i --tty busybox --image=busybox:1.28 -- shRun pod as interactive shell
kubectl run nginx --image=nginx -n mynamespaceStart a single instance of nginx pod in the specified namespace
kubectl run nginx --image=nginx --dry-run=client -o yaml > pod.yamlGenerate spec for running pod nginx
kubectl attach my-pod -iAttach to running container
kubectl port-forward my-pod 5000:6000Listen on port 5000 on the local machine and forward to port 6000 on my-pod
kubectl exec my-pod -- ls /Run command in existing pod (single-container case)
kubectl exec --stdin --tty my-pod -- /bin/shInteractive shell access to a running pod (single-container case)
kubectl exec my-pod -c my-container -- ls /Run command in existing pod (multi-container case)
kubectl top pod POD_NAME --containersShow metrics for a given pod and its containers
kubectl top pod POD_NAME --sort-by=cpuShow metrics for a given pod and sort by ‘cpu’
kubectl cp /tmp/foo_dir my-pod:/tmp/bar_dirCopy local directory to a remote pod in the current namespace
kubectl cp /tmp/foo my-pod:/tmp/bar -c my-containerCopy local file to a remote pod in a specific container
kubectl cp /tmp/foo my-namespace/my-pod:/tmp/barCopy local file to a remote pod in a specified namespace
kubectl cp my-namespace/my-pod:/tmp/foo /tmp/barCopy from a remote pod to a local directory
kubectl logs deploy/my-deploymentDump Pod logs for a Deployment (single-container case)
kubectl logs deploy/my-deployment -c my-containerDump Pod logs for a Deployment (multi-container case)
kubectl port-forward svc/my-service 5000Listen on local port 5000 and forward to port 5000 on Service backend
kubectl port-forward svc/my-service 5000:my-service-portListen on local port 5000 and forward to Service target port
kubectl port-forward deploy/my-deployment 5000:6000Listen on local port 5000 and forward to port 6000 on a Pod created by <my-deployment>
kubectl exec deploy/my-deployment -- lsRun command in the first Pod and first container in Deployment
kubectl get crdGet Custom Resource Definitions (CRDs)
kubectl get pod my-pod -o=jsonDisplay raw resource configuration
kubectl get pod my-pod -o=yaml > pod.yamlExport resources to YAML
kubectl diff -f ./my-manifest.yamlDiff resources before and after applying
kubectl get pod my-pod -o=jsonpath='{.metadata.annotations.kubectl\.kubernetes\.io/last-applied-configuration}'View applied configuration
kubectl get pod my-pod -o=json > my-pod.jsonGenerate manifests for existing resources
kubectl get pods --namespace=my-namespaceList pods in a specific namespace
kubectl config set-context --current --namespace=my-namespaceSet the default namespace for a context
kubectl get events --sort-by=.metadata.creationTimestampGet events for a resource
`kubectl get pods –all-namespaces -o jsonpath='{range .items[].status.initContainerStatuses[]}{.containerID}{“\n”}{end}’cut -d/ -f3`
`kubectl get secret my-secret -o go-template='{{range $k,$v := .data}}{{“### “}}{{$k}}{{“\n”}}{{$vbase64decode}}{{“\n\n”}}{{end}}’`
`kubectl get pods -o jsonjq ‘.items[].spec.containers[].env[]?.valueFrom.secretKeyRef.name’
kubectl get nodes -o='custom-columns=NodeName:.metadata.name,TaintKey:.spec.taints[*].key,TaintValue:.spec.taints[*].value,TaintEffect:.spec.taints[*].effect'View existing taints on nodes
kubectl taint nodes node-1 key=value:NoScheduleAdd a new taint to a node
kubectl taint nodes node-1 key:NoSchedule-Remove a taint from a node
kubectl api-resourcesList all supported resource types with details
kubectl api-resources --namespaced=trueList all namespaced resources
kubectl api-resources --namespaced=falseList all non-namespaced resources
kubectl api-resources -o nameList resources with simple output (only resource names)
kubectl api-resources -o wideList resources with expanded (wide) output
kubectl api-resources --verbs=list,getList resources that support “list” and “get” verbs
kubectl api-resources --api-group=extensionsList resources in the “extensions” API group
kubectl get pods -o=jsonGet custom resource definitions (CRDs)
kubectl get pod my-pod -o=jsonDisplay raw resource configuration
kubectl get pod my-pod -o=yaml > pod.yamlExport resources to YAML
kubectl diff -f ./my-manifest.yamlDiff resources before and after applying
kubectl get pod my-pod -o=jsonpath='{.metadata.annotations.kubectl\.kubernetes\.io/last-applied-configuration}'View applied configuration
kubectl get pod my-pod -o=json > my-pod.jsonGenerate manifests for existing resources
kubectl get pods --namespace=my-namespaceList pods in a specific namespace
kubectl config set-context --current --namespace=my-namespaceSet the default namespace for a context
kubectl get events --sort-by=.metadata.creationTimestampGet events for a resource
kubectl describe pod my-podDescribe pod details
kubectl get pods --v=8Display API requests
kubectl describe pod my-pod --v=9Display API requests with high verbosity
kubectl get pods --v=7Display HTTP request headers
kubectl get pods --v=8Display HTTP request contents
Kubectl Cheatsheet Table

Leave a Reply