Kubectl cheat sheet for Kubernetes administrators and CKA exam preparation

You can download this article in PDF format via the link below to support us.
Download the guide in PDF formatturn off

This is a self-righteous cheat sheet designed to be used as a reference point for daily Kubernetes operations and management using the following commands on the command line interface kubectl. If you are preparing for the CKA or CKAD exam, the cheat sheet contains some commands to help you complete the exam tasks quickly. For exam preparation, it is not entirely dependent on this document, but a lot of practice to traverse the course content.

If you have a time-saving kubectl command that we missed in this article, please don’t delete it in the comment section. We are happy to update the documentation at any time.

Before introducing the task-specific commands used in management and application deployment in a Kubernetes or OpenShift cluster, we will start with useful general commands.

Useful general commands

The following are some of the most useful general commands when using 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

Apple system:

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 the installation by checking the 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 to complete

By default, Bash is not enabled after installing the kubectl command. Use the following command to enable it.

Heavy hit:

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

zsh:

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

3. List and switch context

The context is a set of access parameters. Each context contains a Kubernetes cluster, a user and a namespace.

List content:

kubectl config get-contexts

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

$ kubectl config use-context <context-name>

Set a context entry in kubeconfig:

kubectl config set-context <context-name>

If you want to change the namespace preference, use:

kubectl config set-context <context-name> --namespace=<ns-name>

View the current context:

 kubectl config current-context

4. Verify the syntax of the manifest yaml file

If you have created the deployment yaml file and want to verify the syntax, use the following command:

 kubectl create --dry-run --validate -f <file>.yaml

example:

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

If there is a syntax error, you will get from the output:

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

5. Drain nodes when deleting local data

You can clear the node, or you can clear the local data used by the running container. To this end, the command syntax is:

kubectl drain <node-name> --ignore-daemonsets=true --delete-local-data=true

To force emptying, you can add --force Mark, although this is not recommended.

6. Apply yaml files and folders

You can use the apply parameter to apply the configuration to the resource by file name or stdin. The command syntax is:

kubectl apply -f <file-name>.yaml
# Or for json:
kubectl apply -f <file-name>.json

For folders with multiple yaml fils, use:

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

Use absolute path:

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

7. Create time-saving aliases

You can also create some aliases to make the command line use 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 died on exit

You can quickly create a temporary Pod with a shell session for testing. Once you exit, the Pod will be destroyed.

kubectl run --rm -it --image=<image> <podname> -- 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
<HTML><HEAD><meta http-equiv="content-type" content="text/html;charset=utf-8">
<TITLE>301 Moved</TITLE></HEAD><BODY>
<H1>301 Moved</H1>
The document has moved
<A HREF="http://www.google.com/">here</A>.
</BODY></HTML>

/ # 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

Use the following command to create the namespace:

kubectl create namespace <namespace-name>

Either

kubectl create ns <namespace-name>

To switch to the namespace for all operations, use:

$ kubectl config get-contexts
$ kubectl config set-context <context-name> --namespace=<namespace-name>

example:

$ 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 commands in Pod without tty

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

cat <<EOF | kubectl apply -f -
apiVersion: v1
kind: Pod
metadata:
  name: ubuntu
  labels:
    app: ubuntu
spec:
  containers:
  - name: ubuntu
    image: ubuntu:latest
    command: ["/bin/sleep", "3650d"]
    imagePullPolicy: IfNotPresent
  restartPolicy: Always
EOF

Confirm that the Pod is running:

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

Start a Shell session to the Pod:

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

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

Run commands directly in the container without a 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 <Pod-ip>
$ 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 the pods.

$ kubectl delete pod ubuntu
pod "ubuntu" deleted

11. Check the environment variables in the Pod

To list all environment variables in the Pod, use the following command:

$ kubectl exec <pod> -- 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. Obtain resource usage instructions

The command syntax is:

$ kubectl explain <resource>

example:

kubectl explain pods
kubectl explain deploy
kubectl explain service

Explain the field.

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, use.

kubectl get <resource> --sort-by=.metadata.name

example.

$ 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   <none>        53/UDP,53/TCP   2d11h
default       kubernetes   ClusterIP   172.20.0.1    <none>        443/TCP         2d11h

14. Generate 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 will print the corresponding API objects without creating them:

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

There are memory and CPU limitations:

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

It has both CPU and memory requirements 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

Then, you can create a Pod by applying the file.

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

Confirm that the Pod is running:

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

Delete the pod.

$ kubectl delete pod nginx
pod "nginx" deleted

15. Generate and deploy YAML files

Similar build commands apply to deployment resource types.Only we fail –Restart=never.

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

Write file

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

You can modify the file and apply resource creation.

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

Check the deployment.

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

List the Pods that match 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

Delete the deployment.

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

16.Publish the Pod or deployment on the service

Use kubectl exposure command to expose deployment or Pods on ClusterIP or NodePort.

$ kubectl expose -h

See the 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   <none>        80/TCP    17s

Types of service support: 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   <none>        80:30292/TCP   3s

This other example creates a service for the container RedisAnd its port named “redis” is 6379

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

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

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

17. Expand the Pod in deployment

You can expand the number of Pods in your deployment without editing any files.

$ 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 the node to make it unschedulable

Determine the node to take action:

$ kubectl get nodes

Next, tell Kubernetes to run out of nodes:

$ kubectl drain <node-name>

You may need to ignore the daemon set and delete the local container data.

$ kubectl drain  <node-name> --delete-local-data --ignore-daemonsets

Tell Kubernetes to stop scheduling new pods on this node:

$ kubectl cordon <node-name>

To resume scheduling on the node, use the command:

$ kubectl uncordon <node-name>

19. Create multiple containers in one container

First generate the Pod manifest file.We will create the name Tripod ubuntu picture.

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

Edit the file, and then 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 added two containers – Nginx with Redis. To apply the configuration, run the following command:

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

Confirm that 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 accounts, roles and role definitions

Create a service called a presentation.

$ kubectl create sa demo
serviceaccount/demo created

Create a role named Demo Allow users to perform “get”, “watch” and “list” operations on pod, 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 Demo Roles.

$ 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

verification:

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

Get the latest logs about named Pods:

$ 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

Track the log stream in real time.

$ kubectl logs newrelic-infra-r4bpg -f

Get the latest logs from all Pods in the 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 regular expressions 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 file:

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

22. Get top pods

Get the top resource utilization container.

$ kubectl top pod

Get the top Pod with high CPU usage:

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

Use label filtering.

$ 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

Only get the Pod with the highest CPU usage, and then write the output to a 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. Deployment and rollback deployment

Deploy the 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 the 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

Roll back to the previous deployment:

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

Launch a specific version

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

24. Mark nodes and assign containers to nodes

How to add tags to nodes.

$ kubectl label nodes <node-name> <label-key>=<label-value>

example:

kubectl label nodes k8snode01 disktype=ssd

Then you can assign Pods to nodes.

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

You can download this article in PDF format via the link below to support us.
Download the guide in PDF formatturn off

Sidebar