This is an opinionated cheat sheet created to serve as a reference point for daily Kubernetes operations and administration done on the command line interface with kubectl. If you are preparing for CKA or CKAD exams, the cheat sheet contains commands that will hep you to quickly complete exam tasks. For exam preparation don’t rely entirely on this document but rather go through the course content with lots of practice.

If you have that time saver kubectl command that we’ve missed out in this post don’t hesitate to drop it in the comments section. We’ll be happy to update the document any time.

We’ll start with the helpful generic commands before covering task specific commands used in Administration and Applications deployment in Kubernetes or an OpenShift Cluster.

Helpful commands for general use

Below are some of the most helpful general use commands when working with Kubernetes.

# Display Kubernetes API Server URL
$ kubectl cluster-info

# Dump all cluster information
$ kubectl cluster-info dump

# List all nodes in the cluster
$ kubectl get nodes

# Check health of cluster components
$ kubectl get componentstatuses
$ kubectl get cs

# List all API resources
$ kubectl api-resources

# List API versions
$ kubectl api-versions

1. Install kubectl

This is how to install kubectl on Linux and macOS:

Linux

curl -LO "https://storage.googleapis.com/kubernetes-release/release/$(curl -s https://storage.googleapis.com/kubernetes-release/release/stable.txt)/bin/linux/amd64/kubectl"
chmod  x ./kubectl
sudo mv ./kubectl /usr/local/bin/kubectl

macOS:

curl -LO "https://storage.googleapis.com/kubernetes-release/release/$(curl -s https://storage.googleapis.com/kubernetes-release/release/stable.txt)/bin/darwin/amd64/kubectl"
chmod  x ./kubectl
sudo mv ./kubectl /usr/local/bin/kubectl

Confirm installation by checking version:

$ kubectl version --client
Client Version: version.Info{Major:"1", Minor:"19", GitVersion:"v1.19.3", GitCommit:"1e11e4a2108024935ecfcb2912226cedeafd99df", GitTreeState:"clean", BuildDate:"2020-10-14T12:50:19Z", GoVersion:"go1.15.2", Compiler:"gc", Platform:"darwin/amd64"}

2. Enable Bash Completion

By default Bash completion is not enabled after installation of kubectl command. Enable it with the commands below.

Bash:

echo 'source <(kubectl completion bash)' >>~/.bashrc
source ~/.bashrc

zsh:

echo 'source <(kubectl completion zsh) >> ~/.zshrc
source ~/.zshrc

3. List and Switch context

A context is a group of access parameters. Each context contains a Kubernetes cluster, a user, and a namespace.

Listing contexts:

kubectl config get-contexts

Switch between clusters by setting the current-context in a kubeconfig file:

$ kubectl config use-context 

Set a context entry in kubeconfig:

kubectl config set-context 

If you want to change namespace preference use:

kubectl config set-context  --namespace=

See current context:

 kubectl config current-context

4. Validate manifest yaml file syntax

If you’ve created a deployment yaml file and would like to validate the syntax, use the command:

 kubectl create --dry-run --validate -f .yaml

Example:

$ kubectl create --dry-run=client --validate -f hello-world.yml
pod/hello-world created (dry run)

If there is a syntax errors you’ll get from output:

error: error parsing hello-world.yml: error converting YAML to JSON: yaml: line 12: did not find expected '-' indicator

5. Drain a node while removing local data

A node can be drained and the local data used by running containers cleared as well. For this the command syntax is:

kubectl drain  --ignore-daemonsets=true --delete-local-data=true

To force drain you can add the --force flag though this is not recommended.

6. Apply yaml files and folders

You can use apply argument to apply a configuration to a resource by filename or stdin. The command syntax is:

kubectl apply -f .yaml
# Or for json:
kubectl apply -f .json

For folder with a number of yaml fils, use:

kubectl apply -R -f . # If files are in current working directory

With absolute path:

kubectl apply -R -f /path/to/yaml/files

7. Create time saving aliases

You can also create some aliases that make your command line usage much faster.

$ vim ~/.bashrc
# kubectl alias
alias k='kubectl'

# Create resources
alias kcf='kubectl create -f'
alias kaf='kubectl apply -f'

# List resources
alias kgp='kubectl get pods'
alias kgpa='kubectl get pods --all-namespaces'
alias kgd='kubectl get deployments'
alias kgs='kubectl get service'
alias kgh='kubectl get hpa'

# Delete resources
alias kd='kubectl delete'
alias kdp='kubectl delete pods'
alias kdd='kubectl delete deployments'
alias kgs='kubectl delete service'

8. Start a temporary pod that dies on exit

You can quickly create a temporary pod with shell session for testing purposes that is destroyed once you exit.

kubectl run --rm -it --image=  -- sh

Example:

$ kubectl run --rm -it --image=alpine alpine -- sh
If you don't see a command prompt, try pressing enter.
/ # apk update
fetch http://dl-cdn.alpinelinux.org/alpine/v3.12/main/x86_64/APKINDEX.tar.gz
fetch http://dl-cdn.alpinelinux.org/alpine/v3.12/community/x86_64/APKINDEX.tar.gz
v3.12.1-82-g0e1cfdcae4 [http://dl-cdn.alpinelinux.org/alpine/v3.12/main]
v3.12.1-85-gd70a46ae6d [http://dl-cdn.alpinelinux.org/alpine/v3.12/community]
OK: 12747 distinct packages available

/ # apk add wget curl vim
(1/12) Installing ca-certificates (20191127-r4)
(2/12) Installing nghttp2-libs (1.41.0-r0)
(3/12) Installing libcurl (7.69.1-r2)
(4/12) Installing curl (7.69.1-r2)
(5/12) Installing xxd (8.2.0735-r0)
(6/12) Installing lua5.3-libs (5.3.5-r6)
(7/12) Installing ncurses-terminfo-base (6.2_p20200523-r0)
(8/12) Installing ncurses-libs (6.2_p20200523-r0)
(9/12) Installing vim (8.2.0735-r0)
(10/12) Installing libunistring (0.9.10-r0)
(11/12) Installing libidn2 (2.3.0-r0)
(12/12) Installing wget (1.20.3-r1)
Executing busybox-1.31.1-r19.trigger
Executing ca-certificates-20191127-r4.trigger
OK: 39 MiB in 26 packages

/ # curl google.com

301 Moved

301 Moved

The document has moved here. / # exit Session ended, resume using 'kubectl attach alpine -c alpine -i -t' command when the pod is running pod "alpine" deleted $ kubectl get pods NAME READY STATUS RESTARTS AGE alpine 0/1 Terminating 0 80s

9. Create a namespace

A namespace is created with the command:

kubectl create namespace 

Or

kubectl create ns 

To switch to the namespace for all operations use:

$ kubectl config get-contexts
$ kubectl config set-context  --namespace=

Examples:

$ kubectl create ns dev
namespace/dev created

$ kubectl get ns dev -o yaml
apiVersion: v1
kind: Namespace
metadata:
  creationTimestamp: "2020-12-10T08:19:10Z"
  managedFields:
  - apiVersion: v1
    fieldsType: FieldsV1
    fieldsV1:
      f:status:
        f:phase: {}
    manager: kubectl-create
    operation: Update
    time: "2020-12-10T08:19:10Z"
  name: dev
  resourceVersion: "592755"
  selfLink: /api/v1/namespaces/dev
  uid: 8cd5639a-85db-4c84-927d-344bdec9acba
spec:
  finalizers:
  - kubernetes
status:
  phase: Active

10. Run shell command in a Pod without tty

Let’s create a pod that runs in the background.

cat <

Confirm Pod is running:

$ kubectl get pods ubuntu
NAME     READY   STATUS    RESTARTS   AGE
ubuntu   1/1     Running   0          14s

Starting shell session to the Pod:

$ kubectl exec --stdin --tty ubuntu -- sh
# exit

$ kubectl exec --stdin --tty ubuntu -- /bin/bash
[email protected]:/# exit
exit

Running command directly in the container without tty.

$ kubectl exec -it ubuntu -- ls -l /etc/hosts
-rw-r--r-- 1 root root 205 Dec 10 08:25 /etc/hosts

$ kubectl exec -it ubuntu -- apt update
kubectl exec -ti busybox -- nslookup 
$ kubectl exec -it ubuntu -- cat /etc/os-release
NAME="Ubuntu"
VERSION="20.04.1 LTS (Focal Fossa)"
ID=ubuntu
ID_LIKE=debian
PRETTY_NAME="Ubuntu 20.04.1 LTS"
VERSION_ID="20.04"
HOME_URL="https://www.ubuntu.com/"
SUPPORT_URL="https://help.ubuntu.com/"
BUG_REPORT_URL="https://bugs.launchpad.net/ubuntu/"
PRIVACY_POLICY_URL="https://www.ubuntu.com/legal/terms-and-policies/privacy-policy"
VERSION_CODENAME=focal
UBUNTU_CODENAME=focal

Kill Pod.

$ kubectl delete pod ubuntu
pod "ubuntu" deleted

11. Check environment variables in a Pod

To list all environment variables in a Pod use the command:

$ kubectl exec  -- env

Example

$ kubectl exec ubuntu -- env
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
HOSTNAME=ubuntu
KUBERNETES_PORT_443_TCP_ADDR=172.20.0.1
KUBERNETES_SERVICE_HOST=172.20.0.1
KUBERNETES_SERVICE_PORT=443
KUBERNETES_SERVICE_PORT_HTTPS=443
KUBERNETES_PORT=tcp://172.20.0.1:443
KUBERNETES_PORT_443_TCP=tcp://172.20.0.1:443
KUBERNETES_PORT_443_TCP_PROTO=tcp
KUBERNETES_PORT_443_TCP_PORT=443
HOME=/root

12. Get explanation of resource usage

The command syntax is:

$ kubectl explain 

Examples:

kubectl explain pods
kubectl explain deploy
kubectl explain service

Explain fields.

kubectl explain deploy.spec
kubectl explain deploy.spec.replicas
kubectl explain pod.metadata.namespace

13. Get resources sorted by name

To list resources sorted by name you’ll use.

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

Examples.

$ kubectl get pods --sort-by=.metadata.name
NAME     READY   STATUS    RESTARTS   AGE
ubuntu   1/1     Running   0          10m

$ kubectl get svc --sort-by=.metadata.name --all-namespaces
NAMESPACE     NAME         TYPE        CLUSTER-IP    EXTERNAL-IP   PORT(S)         AGE
kube-system   kube-dns     ClusterIP   172.20.0.10           53/UDP,53/TCP   2d11h
default       kubernetes   ClusterIP   172.20.0.1            443/TCP         2d11h

14. Generate a Pod manifest YAML file

You can use kubectl run to generate a yaml manifest file for Pods deployment.

Command help page.

kubectl run pod --help

The following command prints the corresponding API objects without creating them:

$  kubectl run nginx --image=nginx --restart=Never --dry-run=client -o yaml

With memory and CPU Limits:

kubectl run nginx --image=nginx --restart=Never --limits='cpu=300m,memory=512Mi' --dry-run=client -o yaml

With both CPU and Memory requests and Limits.

kubectl run nginx --image=nginx --restart=Never --requests='cpu=100m,memory=256Mi' --limits='cpu=300m,memory=512Mi' --dry-run=client -o yaml

You can direct the output to a file.

kubectl run nginx --image=nginx --restart=Never --dry-run=client -o yaml >nginx-pod.yaml

You can then create the Pod by applying the file.

$ kubectl apply -f ./nginx-pod.yaml
pod/nginx created

Confirm Pod is running:

$ kubectl get pod nginx
NAME    READY   STATUS    RESTARTS   AGE
nginx   1/1     Running   0          31s

Delete Pod.

$ kubectl delete pod nginx
pod "nginx" deleted

15. Generate a Deployment deployment YAML file

Similar generation commands applies for deployments resource types. Only that we don’t pass –restart=Never.

kubectl create deploy nginx --image=nginx  --replicas=3 --dry-run=client -o yaml

Write to file

kubectl create deploy nginx --image=nginx  --replicas=3 --dry-run=client -o yaml >nginx-deployment.yml

You can the modify the file and apply resource creations.

$ kubectl apply -f nginx-deployment.yml
deployment.apps/nginx created

Check deployment.

$ kubectl get deploy nginx
NAME    READY   UP-TO-DATE   AVAILABLE   AGE
nginx   3/3     3            3           37s

List Pods matching Nginx.

$  kubectl get pods -l app=nginx
NAME                    READY   STATUS    RESTARTS   AGE
nginx-f89759699-6hcng   1/1     Running   0          70s
nginx-f89759699-dvqhf   1/1     Running   0          70s
nginx-f89759699-hgbtq   1/1     Running   0          70s

Remove deployment.

$ kubectl delete deploy nginx
deployment.apps "nginx" deleted

16. Expose Pod or Deployment on a Service

Use kubectl expose command to make a deployment or Pods exposed on ClusterIP or NodePort.

$ kubectl expose -h

See example below.

$ kubectl expose deployment nginx --port=80 --type=ClusterIP
service/nginx exposed

$ kubectl get svc nginx
NAME    TYPE        CLUSTER-IP     EXTERNAL-IP   PORT(S)   AGE
nginx   ClusterIP   172.20.29.63           80/TCP    17s

Supported types for the service: ClusterIP, NodePort, LoadBalancer, or ExternalName.

$ kubectl expose deployment nginx --port=80 --type=NodePort
$ kubectl get svc nginx
NAME    TYPE       CLUSTER-IP     EXTERNAL-IP   PORT(S)        AGE
nginx   NodePort   172.20.32.97           80:30292/TCP   3s

This other example creates a service for a pod redis, which serves on port 6379 with the name “redis”

 $ kubectl expose pod redis --port=6379 --name=redis

You can also manually specify the Port exposed by the container(Application port).

$ kubectl expose pod redis  --type=ClusterIP --port=6379 --target-port=6379

17. Scale up pods in a deployment

You can scale up the number of Pods in a deployment without editing any file.

$ kubectl get deploy
NAME    READY   UP-TO-DATE   AVAILABLE   AGE
nginx   3/3     3            3           7h

$ kubectl scale --replicas=4 deployment nginx
deployment.apps/nginx scaled

$ kubectl get deploy
NAME    READY   UP-TO-DATE   AVAILABLE   AGE
nginx   4/4     4            4           7h3m

$ kubectl get pods -l app=nginx
NAME                    READY   STATUS    RESTARTS   AGE
nginx-f89759699-7x7q7   1/1     Running   0          2m21s
nginx-f89759699-jz9cj   1/1     Running   0          7h3m
nginx-f89759699-nm2nk   1/1     Running   0          7h3m
nginx-f89759699-ppdzr   1/1     Running   0          7h3m

$ kubectl scale --replicas=3 deployment nginx
deployment.apps/nginx scaled

$ kubectl get deploy
NAME    READY   UP-TO-DATE   AVAILABLE   AGE
nginx   3/3     3            3           7h4m

18. Migrate all Pods in a node and make it Unschedulable

Identify node to action on:

$ kubectl get nodes

Next, tell Kubernetes to drain the node:

$ kubectl drain 

You may need to ignore daemonsets and delete local container data.

$ kubectl drain   --delete-local-data --ignore-daemonsets

Tell Kubernetes to stop scheduling new pods onto the node:

$ kubectl cordon 

To resume scheduling on the node use command:

$ kubectl uncordon 

19. Create Multiple containers in a Pod

First generate Pod manifest file. We’ll create pod called mypod with ubuntu image.

kubectl run mypod --image=nginx --restart=Never --dry-run=client -o yaml >mypod.yaml

Edit the file and add other containers to the named Pod.

$ vim mypod.yaml
apiVersion: v1
kind: Pod
metadata:
  creationTimestamp: null
  labels:
    run: mypod
  name: mypod
spec:
  containers:
  - image: nginx
    name: nginx
  - image: redis
    name: redis
  dnsPolicy: ClusterFirst
  restartPolicy: Never
status: {}

We’ve added two containers – nginx and redis. To apply configurations run the command:

$ kubectl apply -f mypod.yaml
pod/mypod created

Confirm the pod has two containers.

$ kubectl get pod mypod
NAME    READY   STATUS    RESTARTS   AGE
mypod   2/2     Running   0          39s

Clean up:

$ kubectl delete -f mypod.yaml
pod "mypod" deleted

20. Create Service Account, Role and Roledinding

Create service called demo.

$ kubectl create sa demo
serviceaccount/demo created

Create a role named demo that allows user to perform “get”, “watch” and “list” on pods,deploy,ds,rs,sts:

$ kubectl create role demo --verb=get,list,watch --resource=pods,deploy,ds,rs,sts
role.rbac.authorization.k8s.io/demo created

# All verbs
$ kubectl create clusterrole demo --verb='*' --resource=pods,deploy,ds,rs,sts

# For cluster role
$ kubectl create clusterrole demo --verb=get,list,watch --resource=pods,deploy,ds,rs,sts
clusterrole.rbac.authorization.k8s.io/demo created

Create a RoleBinding for the demo role.

$ kubectl create rolebinding demo --role=demo --user=demo
rolebinding.rbac.authorization.k8s.io/demo created

# For Cluster role
$ kubectl create rolebinding demo --clusterrole==demo --user=demo

# Clusterrole binding
$ kubectl create clusterrolebinding demo-admin --clusterrole=demo --user=demo

Confirm:

$ kubectl get sa,role,rolebinding
NAME                      SECRETS   AGE
serviceaccount/default    1         2d21h
serviceaccount/demo       1         4m48s
serviceaccount/newrelic   1         3h51m

NAME                                  CREATED AT
role.rbac.authorization.k8s.io/demo   2020-12-10T19:09:01Z

NAME                                         ROLE        AGE
rolebinding.rbac.authorization.k8s.io/demo   Role/demo   21s

Validate:

kubectl auth can-i create deployment --as demo # yes
kubectl auth can-i '*' ds --as demo # yes

Clean up:

kubectl delete sa demo
kubectl delete role demo
kubectl delete clusterrole demo
kubectl delete rolebinding demo

21. Get Logs on Pod(s)

Get recent logs on a named Pod:

$ kubectl get pods
NAME                    READY   STATUS    RESTARTS   AGE
newrelic-infra-hp8dt    1/1     Running   0          3h57m
newrelic-infra-r4bpg    1/1     Running   0          3h57m
nginx-f89759699-jz9cj   1/1     Running   0          8h
nginx-f89759699-nm2nk   1/1     Running   0          8h
nginx-f89759699-ppdzr   1/1     Running   0          8h
ubuntu                  1/1     Running   0          10h

$ kubectl logs newrelic-infra-r4bpg

Follow logs stream in realtime.

$ kubectl logs newrelic-infra-r4bpg -f

Get recent logs from all Pods in a deployment:

$ kubectl get deployments
NAME    READY   UP-TO-DATE   AVAILABLE   AGE
nginx   3/3     3            3           8h

$ kubectl logs deploy/nginx
$ kubectl logs deploy/nginx -f

Use regex to extract logs.

$ kubectl logs newrelic-infra-r4bpg | grep 'connect got id'

time="2020-12-10T15:19:37Z" level=info msg="connect got id" agent-guid=MjU4Mjg0NXxJTkZSQXxOQXw0NDQ3ODMzNDM1Nzk0NDYyMjgx agent-id=4447833435794462281 component=IdentityConnectService

Write output to a file:

$ kubectl logs newrelic-infra-r4bpg | grep 'connect got id' > logs.txt

22. Get top pods

Get top resource utilization pods.

$ kubectl top pod

Get top pods with high cpu utilization:

$ kubectl top pod --sort-by='cpu'

Filter using labels.

$ kubectl top pod -l 'app=nginx' --sort-by='cpu'
NAME                    CPU(cores)   MEMORY(bytes)
nginx-f89759699-jz9cj   0m           2Mi
nginx-f89759699-nm2nk   0m           2Mi
nginx-f89759699-ppdzr   0m           2Mi

Get only one pod with highest CPU usage and write output to file.

$ kubectl top pod -l 'app=nginx' --sort-by='cpu' | awk 'NR==2{print $1}'
$ kubectl top pod -l 'app=nginx' --sort-by='cpu' | awk 'NR==2{print $1}' >top_cpu.txt

23. Roll out and roll back deployment

Deploy Nginx container.

$ kubectl create deploy web --replicas=2 --image=nginx:1.13.2
deployment.apps/web created

$ kubectl get deploy web
NAME   READY   UP-TO-DATE   AVAILABLE   AGE
web    2/2     2            2           16s

Update deployment to use nginx image version 1.14.2

# Syntax: $ kubectl set image CONTAINER_NAME_1=CONTAINER_IMAGE_1 ... CONTAINER_NAME_N=CONTAINER_IMAGE_N
$ kubectl set image deployment web nginx=nginx:1.14.2 --record
deployment.apps/web image updated

Check rollout status

$ kubectl rollout status deployment/web
deployment "web" successfully rolled out

View the rollout history of a deployment:

$ kubectl rollout history deployment/web
deployment.apps/web
REVISION  CHANGE-CAUSE
1         kubectl set image deployment web nginx=nginx:1.14.2 --record=true

Rollback to the previous deployment:

$ kubectl rollout undo deployment web
deployment.apps/web rolled back

Rolling out to particular revision

$ kubectl rollout undo deployment/web --to-revision=3

24. Label Node and Assign Pods to Nodes

How to add labels to a Node.

$ kubectl label nodes  =

Example:

kubectl label nodes k8snode01 disktype=ssd

You can then assign Pods to the Nodes.

spec:
  containers:
  - name: nginx
    image: nginx
    imagePullPolicy: IfNotPresent
  nodeSelector:
    disktype: ssd