Cyberithub

22 Best Kubectl Command Examples

In this article, I will take you through 22 Best Kubectl Commands Examples. As you probably know, kubectl command is relatively used to manage Kubernetes. It is essentially a primary gateway to access any kubernetes cluster. Since it is a primary command line access tool hence It is very important for you to know this well.

22 Best Kubectl Command Examples 1

Kubectl Command Examples

Also Read: Create a Service to Expose your Apps on Kubernetes

1. List all the pods

You need to use kubectl get pods command to list all the available pods as shown in the below example. This command output will also provide few more information like current status of the pod, number of restart happened and the age of the pod.

[root@localhost ~]# kubectl get pods
         NAME                READY STATUS RESTARTS AGE
test-pod-0-64958d679f-qxzbs   1/1  Running   0     3d21h
test-pod-1-86b655bbff-789nd   1/1  Running   0     3d21h
test-pod-2-6f6c8f9fdd-xm44w   1/1  Running   0     3d21h
test-pod-3-0                  1/1  Running   0     3d21h
test-pod-4-d7c457fc7-775gx    1/1  Running   0     3d21h
test-pod-5-6d77f97f45-kkl8n   1/1  Running   0     3d21h
test-pod-6-66ff6db548-4lh58   2/2  Running   0     3d21h
test-pod-7-p6b5q              1/1  Running   0     3d21h
test-pod-8-b577cf8b6-kw8s4    1/1  Running   0     3d21h

2. List all kube dns pods

You need to -n kube-system to list out all the pods for kube-system namespace as shown in below example. This command output will also provide the same information as we have observed in above command.

[root@localhost ~]# kubectl get pods -n kube-system
NAME                                   READY STATUS RESTARTS AGE
test-pod-0-5644d7b6d9-58ddc            1/1   Running   0     3d21h
kube-dns-5644d7b6d9-f7gxb              1/1   Running   0     3d21h
kube-apiserver-172.31.33.220           1/1   Running   0     3d21h
kube-controller-manager-172.31.33.220  1/1   Running   0     3d21h
kube-proxy-lcj2g                       1/1   Running   0     3d21h
kube-scheduler-172.31.33.220           1/1   Running   0     3d21h
kube-net-bbg7w                         2/2   Running   1     3d21h

3. List all persistent volumes

You need to use --sort-by=.spec.capacity.storage option to list out all the persistent volumes by their storage capacity as given in below example. From the output, you can see that pods are visible in increasing order of their storage capacity.

[root@localhost ~]# kubectl get pv --sort-by=.spec.capacity.storage
NAME                           CAPACITY ACCESS MODES RECLAIM POLICY STATUS CLAIM STORAGECLASS REASON   AGE
test-pod-0-logs-vol-0            2Gi     RWO   Retain Bound example/logs-test-pod-0 local-storage   3d21h
test-pod-1-logs-vol-0            2Gi     RWO   Retain Bound example/logs-test-pod-1-0 local-storage 3d21h
test-pod-2-logs-vol-0            2Gi     RWO   Retain Bound example/logs-test-pod-2-0 local-storage 3d21h
test-pod-3-logs-vol-0            2Gi     RWO   Retain Bound example/logs-test-pod-3-0 local-storage 3d21h
test-pod-4-vol                   7Gi     RWO   Retain Bound example/test-pod-4-k8s-0 local-storage 3d21h
test-pod-5-vol-0                 10Gi    RWO   Retain Bound example/data-test-pod-5-0 local-storage 3d21h
test-pod-6-0-logs-vol-0          10Gi    RWO   Retain Bound example/logs-test-pod-6-0 local-storage 3d21h
test-pod-7-vol-0                 10Gi    RWO   Retain Bound example/data-test-pod-7-0 local-storage 3d21h
test-pod-8-vol-0                 10Gi    RWO   Retain Bound example/data-test-pod-8-0 local-storage 3d21h
test-pod-9-vol-0                 10Gi    RWO   Retain Bound example/data-test-pod-9-0 local-storage 3d21h

4. Check all the services

If you want to see all the services, then you need to use kubectl get services command as shown in below example. Here you can get the useful information like Cluster IP, External IP, Port details and age of the pod. This output will help you identifying which are the services currently running and which are currently down.

[root@localhost ~]# kubectl get services
   NAME       TYPE    CLUSTER-IP   EXTERNAL-IP    PORT(S)                  AGE
test-pod-0 ClusterIP 10.96.65.83     <none>      4883/TCP                   4d
test-pod-1 ClusterIP 10.99.221.111   <none>      4883/TCP                   4d
test-pod-2 ClusterIP 10.105.137.228  <none>      7083/TCP                   4d
test-pod-3 ClusterIP     None        <none>      9042/TCP                   4d
test-pod-4 ClusterIP 10.102.184.122  <none>      80/TCP                     4d
test-pod-5 ClusterIP 10.103.106.186  <none>      8080/TCP                   4d
test-pod-6 ClusterIP 10.104.196.193  <none>      8443/TCP,6080/TCP          4d
test-pod-7 ClusterIP 10.102.175.62   <none>      80/TCP,443/TCP             4d
test-pod-8 ClusterIP 10.103.54.109   <none>      9000/TCP                   4d
test-pod-9 ClusterIP 10.106.58.196 172.31.33.220 5671/TCP,5672/TCP,4369/TCP 4d

5. List all the pods in current namespaces

If you want to list all the pods in current namespace, then you need to use kubectl get pods -o wide command as shown below. As you can notice we are wide output(-o) format to display the pods status. In this output you can check the IP of the node as well where pods are running.

[root@localhost ~]# kubectl get pods -o wide
            NAME                READY STATUS RESTARTS  AGE      IP           NODE      NOMINATED NODE READINESS GATES
test-pod-0-64958d679f-qxzbs      1/1  Running    0      4d 192.113.12.38  72.31.33.220   <none>  <none>
test-pod-1-86b655bbff-789nd      1/1  Running    0      4d 192.113.12.39  72.31.33.220   <none>  <none>
test-pod-2-6f6c8f9fdd-xm44w      1/1  Running    0      4d 192.113.12.19  72.31.33.220   <none>  <none>
test-pod-3-0                     1/1  Running    0      4d 192.113.12.10  72.31.33.220   <none>  <none>
test-pod-4-d7c457fc7-775gx       1/1  Running    0      4d 192.113.12.28  72.31.33.220   <none>  <none>
test-pod-5-6d77f97f45-kkl8n      1/1  Running    0      4d 192.113.12.26  72.31.33.220   <none>  <none>
test-pod-6-66ff6db548-4lh58      2/2  Running    0      4d 192.113.12.12  72.31.33.220   <none>  <none>

6. Get the Pod YAML

If you want to check any of the pod yaml, then you need to use kubectl get pod <pod_name> -o yaml command as shown below. You can check the pod configuration details from the YAML output.

[root@localhost ~]# kubectl get pod test-pod-0 -o yaml
apiVersion: v1
kind: Pod
metadata:
annotations:
pod.alpha.kubernetes.io/initialized: "true"
creationTimestamp: "2020-03-12T12:19:43Z"
generateName: test-pod
labels:
app: test-pod
controller-revision-hash: test-pod-7d8b79498
statefulset.kubernetes.io/pod-name: test-pod-0
name: test-pod-0
namespace: example
ownerReferences:
- apiVersion: apps/v1
blockOwnerDeletion: true
controller: true
kind: StatefulSet
name: test-pod
uid: 2b89e51c-ad8f-45c4-9597-4c68c8c39a32

7. Describe a Pod

If you want to know about complete description of a pod, then you need to use kubectl describe pod <pod_name> command as shown below. This command will be very much useful when sometimes pod will not come up due to some error. It will tell you about the error that has occurred.

[root@localhost ~]# kubectl describe pod test-pod-0
Name: test-pod-0
Namespace: example
Priority: 0
Node: 172.31.33.220/172.31.33.220
Start Time: Thu, 12 Mar 2020 12:19:44 +0000
Labels: app=test-pod
controller-revision-hash=test-pod-7d8b79498
statefulset.kubernetes.io/pod-name=test-pod-0
Annotations: pod.alpha.kubernetes.io/initialized: true
Status: Running
IP: 192.113.12.10
IPs:
IP: 192.113.12.10
Controlled By: StatefulSet/test-pod
Containers:
config-datastore:
Container ID: docker://e82ed82037e8fd4b52e4ad75fe9d537c857fdd239a46738f5e92c4d4c314114f
Image: aio:rel-5.1.0p1
Image ID: docker://sha256:5f12324b26dc58ec6c363ba21ce53cdd7366e1f4ce35e8eba71e0af6026b768c
Port: 9042/TCP
Host Port: 0/TCP

8. Check all the nodes

If you want to see all the nodes in Kubernetes cluster, then you need to use kubectl get nodes command as shown below. As you can see from below output, this is a single node cluster.

[root@localhost ~]# kubectl get nodes
NAME          STATUS ROLES  AGE VERSION
172.31.33.220 Ready  master 4d  v1.16.1

9. Show all the Pods Labels

If you want to see labels of all the pods, then you need to use kubectl get pods --show-labels command as shown below. Here you can check all the pod details along with the associated Label details.

[root@localhost ~]# kubectl get pods --show-labels
          NAME              READY STATUS RESTARTS AGE LABELS
test-pod-0-64958d679f-qxzbs 1/1   Running  0       4d app=test-pod-0,pod-template-hash=64958d679f
test-pod-1-86b655bbff-789nd 1/1   Running  0       4d app=test-pod-1,pod-template-hash=86b655bbff
test-pod-2-6f6c8f9fdd-xm44w 1/1   Running  0       4d app=test-pod-2,pod-template-hash=6f6c8f9fdd
test-pod-3                  1/1   Running  0       4d app=test-pod-3,controller-revision-hash=test-pod-3-7d8b79498,statefulset.kubernetes.io/pod-name=test-pod-3
test-pod-4-d7c457fc7-775gx  1/1   Running  0       4d app=test-pod-4,pod-template-hash=d7c457fc7
test-pod-5-6d77f97f45-kkl8n 1/1   Running  0       4d app=test-pod-5,pod-template-hash=6d77f97f45
test-pod-6-66ff6db548-4lh58 2/2   Running  0       4d app=test-pod-6,pod-template-hash=66ff6db548
test-pod-7-p6b5q            1/1   Running  0       4d app=test-pod-7,controller-revision-hash=64444d5b79,pod-template-generation=1,version=v1.0

10. List all the secrets used by Pods

If you want to see all the secrets used by all the pods, then you need to use below command. This command will be helpful in identifying all the secrets used in all the pods.

[root@localhost ~]# kubectl get pods -o json | jq '.items[].spec.containers[].env[]?.valueFrom.secretKeyRef.name' | grep -v null | sort | uniq
"aws-secrets"
"test-cert"
"hocsecret"
"ingress-crt"
"test-cert"

11. Dump Pod logs

If you want to dump complete logs of a pod, then you need to use below command. Please note that output of this command can be pretty long so it is a good practice to pipe the output to more command and go slowly to render the output.

[root@localhost ~]# kubectl logs test-pod-0 | more
Successfully added cron job
+ mem_json='{
"name": "memtuning",
"version": "1.0.0",
"components": [
{
"name": "test-pod-0",
"memconfig": [
{
"range": "7-14",
"value": "64m"
},
{
"range": "15-23",
"value": "512m"
},
{
"range": "24-30",
"value": "1024m"
},
{
"range": "31-59",
"value": "2048m"
},

12. Run a command in existing pod

If you want to run a command inside a pod without actually logging in to the pod, then you need to use below kubectl exec <pod_name> -- <commands> command. Here I am trying to check the size of /u01/test directory of test-pod-0 pod using du -sh command without logging in to the test-pod-0 pod as shown below.

[root@localhost ~]# kubectl exec test-pod-0 -- du -sh /u01/test/
935M /u01/test/

13. Display Continuous Logs

If you want to see streaming logs of a specific pod, then you need to use -f option as shown in below example. This command will be very useful in troubleshooting any of the pod error.

[root@localhost ~]# kubectl logs -f test-pod-0
2020-03-16 12:43:52,582 DEBG 'test' stdout output:
INFO [Service Thread] 2020-03-16 12:43:52,582 StatusLogger.java:101 - system_auth.resource_role_permissons_index 0,0
INFO [Service Thread] 2020-03-16 12:43:52,582 StatusLogger.java:101 - system_auth.role_permissions 0,0

2020-03-16 12:43:52,583 DEBG 'test' stdout output:
INFO [Service Thread] 2020-03-16 12:43:52,582 StatusLogger.java:101 - system_traces.sessions 0,0
INFO [Service Thread] 2020-03-16 12:43:52,582 StatusLogger.java:101 - system_traces.events 0,0

2020-03-16 12:43:59,060 DEBG 'test' stdout output:
WARN [PERIODIC-COMMIT-LOG-SYNCER] 2020-03-16 12:43:59,060 NoSpamLogger.java:94 - Out of 0 commit log syncs over the past 0.00s with average duration of Infinityms, 1 have exceeded the configured commit interval by an average of 21.47ms

14. Get Container metrics

If you want to see metrics of a pod and its containers, then you need to use below command.

[root@localhost ~]# kubectl top pod test-pod-0 --containers
POD          NAME   CPU(cores) MEMORY(bytes)
test-pod-0  test-pod   220m       2241Mi

15. Login to a Pod

If you want to login to a pod, then you need to use below kubectl command to open a bash prompt in test-pod-0 pod.

[root@localhost ~]# kubectl exec -ti test-pod-0 bash
bash-4.1#

-t : Stdin is a TTY

-i : Pass stdin to the container

16. Check Cluster Info

If you want to check Kubernetes cluster summary, then you can use below cluster-info option. This command will tell you about the URL in which Kubernetes master is currently running. It will also tell you about the URL KubeDNS is pointing to as can be seen below.

[root@localhost ~]# kubectl cluster-info
Kubernetes master is running at https://72.39.43.220:6443
KubeDNS is running at https://12.71.43.220:6443/api/v1/namespaces/kube-system/services/kube-dns:dns/proxy

To further debug and diagnose cluster problems, use 'kubectl cluster-info dump'.

17. Dump Cluster Information

If you want to dump all the kubernetes cluster logs, then you need to use below command. Please note that output of this command can be pretty long as this command will provide complete details about all the Cluster pods.

[root@localhost ~]# kubectl cluster-info dump
2020-03-12 12:36:32,649 DEBG 'test-pod-0' stderr output:
at net.appcito.barista.occonsumer.OCConsumerHandler.handleCommand(OCConsumerHandler.java:62)
at net.appcito.messaging.ocutils.OCConsumer.handleDelivery(OCConsumer.java:77)
at net.jodah.lyra.internal.ConsumerDelegate.handleDelivery(ConsumerDelegate.java:53)
at com.rabbitmq.client.impl.ConsumerDispatcher$5.run(ConsumerDispatcher.java:140)
at com.rabbitmq.client.impl.ConsumerWorkService$WorkPoolRunnable.run(ConsumerWorkService.java:85)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)

==== END logs for container test-pod of pod example/test-pod-0-6f6c8f9fdd-xm44w ====
==== START logs for container test-pod of pod example/test-pod-0 ====

18. Show metrics of a node

If you want to see the resources utilization of a cluster node, then you need to use below command. As can be seen from below output, You will be able to check no of cpu core, cpu utilization % and memory utilization % using below command.

[root@localhost ~]# kubectl top node 72.131.183.22
    NAME      CPU(cores) CPU% MEMORY(bytes) MEMORY%
72.131.183.22  3051m      38% 24953Mi        78%

19. Delete a Pod

If you want to delete a single pod then you can simply use delete pod <pod_name> option as shown in below example. Usually this command will be used to restart the pods where deleting the pod will recreate the pod after current pod termination as per the rule applied through YAML.

[root@localhost ~]# kubectl delete pod test-pod-0
pod "test-pod-0" deleted

20. Delete all the pods

If you want to delete all the Kubernetes Cluster pods, then awk will be very handy here for choosing all the first columns and feeding those columns as input to xargs command to delete all the pods at once instead of deleting one by one as shown in below example.

[root@localhost ~]# kubectl get pods | awk '{ print $1};' | xargs kubectl delete pods
pod "test-pod-0-64958d679f-qxzbs" deleted
pod "test-pod-1-86b655bbff-789nd" deleted
pod "test-pod-2-6f6c8f9fdd-xm44w" deleted
pod "test-pod-3" deleted
pod "test-pod-4"-d7c457fc7-775gx" deleted
pod "test-pod-5-6d77f97f45-kkl8n" deleted
pod "test-pod-6-66ff6db548-4lh58" deleted
pod "test-pod-7-p6b5q" deleted
pod "test-pod-8-b577cf8b6-kw8s4" deleted
pod "test-pod-9-5bdf4f6887-dwkpm" deleted
pod "test-pod-10" deleted
pod "test-pod-11" deleted

21. Get all the API Resources

If you want to check all the API Resources, then you need to use below api-resources option.

[root@localhost ~]# kubectl api-resources
NAME SHORTNAMES APIGROUP NAMESPACED KIND
bindings true Binding
componentstatuses cs false ComponentStatus
configmaps cm true ConfigMap
endpoints ep true Endpoints
events ev true Event
limitranges limits true LimitRange

22. Check Other Options with Kubectl Commands

You can also check all the options that can used with any of the kubectl commands by using --help option as shown below. For example, If you want to check all the options that can be used with kubectl get pods example, then you need to use kubectl get pods --help command as shown below.

[root@ip-172-31-33-220 ~]# kubectl get pods --help
Display one or many resources

Prints a table of the most important information about the specified resources. You can filter the list using a label
selector and the --selector flag. If the desired resource type is namespaced you will only see results in your current
namespace unless you pass --all-namespaces.

Uninitialized objects are not shown unless --include-uninitialized is passed.

 

 

Reference: Kubectl Cheat Sheets

Leave a Comment