Essential 9 kubectl Commands for Operations

Essential 9 kubectl Commands for Operations

The newly released kubectl cheat sheet can help everyone understand useful commands related to the Kubernetes command-line utility.

Author: Jessica Cherry / Translation:Bach Proofread:Wenzi under the Starry Skybot (Caiyun)

Source: K8sMeetup Community / Original link

kubectl is a command-line management tool for Kubernetes, used for application deployment and daily management on Kubernetes. This article lists 9 common kubectl commands and summarizes some usage tips, hoping to help system administrators simplify management tasks.

Essential 9 kubectl Commands for Operations
Using Kubectl to Query, Create, Edit, and Delete Resources
For developers just starting to use command-line tools, the safest method is to ask questions (read operations) rather than issuing commands (write operations), so starting with the get command is a good choice.
Kubectl get
The get command can retrieve a list of available resources in the current cluster, including:
  • Namespace
  • Pod
  • Node
  • Deployment
  • Service
  • ReplicaSet
Each get command can provide detailed information about available resources in the cluster. For example, the get nodes command provides the status and version of Kubernetes.
$ kubectl get nodesNAME       STATUS   ROLES    AGE   VERSIONminikube   Ready    master   9d    v1.18.0
Most of these commands also have shorthand versions. For example, to get namespaces, you can use kubectl get namespaces or kubectl get ns commands:
$ kubectl get nsNAME              STATUS   AGEcharts            Active   8ddefault           Active   9dkube-node-lease   Active   9dkube-public       Active   9dkube-system       Active   9d
Each get command can use the –namespace or -n parameter to specify the corresponding namespace. This is very useful for viewing Pods in the kube-system namespace, as these Pods are services required for Kubernetes itself to run.
$ kubectl get pods -n kube-systemNAME                               READY   STATUS    RESTARTS   AGEcoredns-66bff467f8-mjptx           1/1     Running   2          9dcoredns-66bff467f8-t2xcz           1/1     Running   2          9detcd-minikube                      1/1     Running   1          9dkube-apiserver-minikube            1/1     Running   1          9dkube-controller-manager-minikube   1/1     Running   2          9dkube-proxy-rpc9d                   1/1     Running   1          9dkube-scheduler-minikube            1/1     Running   2          9dstorage-provisioner                1/1     Running   1          9d
Kubectl create
After querying resources, the next step is to create resources. We can use kubectl to create any type of resource in the cluster, including:
  • Service
  • Cronjob
  • Deployment
  • Job
  • Namespace (ns)
Some resources require setting configuration files, namespaces, and resource names for creation. For example, creating a namespace requires an additional parameter to specify the namespace.
$ kubectl create ns hello-therenamespace/hello-there created
In Linux, you can use cron to create scheduled tasks. Similarly, here we use cronjob to return “hello” every five seconds.
$ kubectl create cronjob my-cron --image=busybox --schedule="*/5 * * * *" -- echo hellocronjob.batch/my-namespaced-cron created
We can also use the shorthand version of cronjob, which is cj.
$ kubectl create cj my-existing-cron --image=busybox --schedule="*/15 * * * *" -- echo hellocronjob.batch/my-existing-cron created
Kubectl edit
After creating resources, what if we need to modify them? This is when we need the kubectl edit command.
We can use this command to edit any resource in the cluster. It will open the default text editor. If we want to edit an existing cron job, we can execute:
$ kubectl edit cronjob/my-existing-cron
The configuration we want to edit is as follows:
# Please edit the object below. Lines beginning with a '#' will be ignored,# and an empty file will abort the edit. If an error occurs while saving this file will be# reopened with the relevant failures.#apiVersion: batch/v1beta1kind: CronJobmetadata:  creationTimestamp: "2020-04-19T16:06:06Z"  managedFields:  - apiVersion: batch/v1beta1    fieldsType: FieldsV1    fieldsV1:      f:spec:        f:concurrencyPolicy: {}        f:failedJobsHistoryLimit: {}        f:jobTemplate:          f:metadata:            f:name: {}          f:spec:            f:template:              f:spec:                f:containers:                  k:{"name":"my-new-cron"}:                    .: {}                    f:command: {}                    f:image: {}                    f:imagePullPolicy: {}
The original scheduling interval was set to 15 seconds:

Essential 9 kubectl Commands for Operations

We changed it to every 25 seconds:

Essential 9 kubectl Commands for Operations

After writing is complete, we can see that the modification has taken effect.
$ kubectl edit cronjob/my-existing-croncronjob.batch/my-existing-cron edited
Additionally, we can use the KUBE_EDITOR command to use other editors.
$ KUBE_EDITOR="nano" kubectl edit cronjob/my-existing-cron
Kubectl delete
After learning the above commands, we will proceed to the delete operation. The recently edited cronjob is one of two cronjobs, and now we delete the entire resource.
$ kubectl delete cronjob my-existing-croncronjob.batch "my-existing-cron" deleted
It should be noted that if you are unsure whether the resource has associated information, it is best not to delete it. Because once deleted, it cannot be recovered, and you can only recreate it.
Kubectl apply
As mentioned earlier, some commands require configuration files, and the apply command can adjust configuration files applied to resources within the cluster. Although it can also be done through the command line standard in (STNIN), the apply command is better because it lets you know how to use the cluster and what configuration files to apply. As an example, the following will apply the Helm role-based access control (RBAC) configuration for service accounts.
$ kubectl apply -f commands.yamlserviceaccount/tiller createdclusterrolebinding.rbac.authorization.k8s.io/tiller created

We can apply almost any configuration, but it is essential to clarify the configuration to be applied; otherwise, it may lead to unexpected consequences.

Troubleshooting Kubernetes with Kubectl

Kubectl describe

describe command can view detailed information about resources. A common usage is to check the information of a Pod or node to see if there are any anomalies or if resources are exhausted.

The resources that can be viewed with this command include:

  • Nodes

  • Pods

  • Services

  • Deployments

  • Replica sets

  • Cronjobs

For example, we can use the describe command to view detailed information about the cronjob in the cluster mentioned above.
$ kubectl describe cronjob my-cron
Here is some of the information:
Name:                         my-cronNamespace:                    defaultLabels:                       <none>Annotations:                  <none>Schedule:                     */5 * * * *Concurrency Policy:           AllowSuspend:                      FalseSuccessful Job History Limit: 3Failed Job History Limit:     1Starting Deadline Seconds:    <unset>Selector:                     <unset>Parallelism:                  <unset>Completions:                  <unset>Pod Template:  Labels: <none>  Containers:   my-cron:    Image:     busybox    Port:      <none>    Host Port: <none>
Kubectl logs
While the describe command can let you know what is happening inside the Pod’s application, the logs command can provide more detailed information about the Pod in Kubernetes. Understanding this distinction can help developers better troubleshoot issues happening within applications and Kubernetes, as these two are often not the same.
$ kubectl logs cherry-chart-88d49478c-dmcfv -n charts
Here are part of the output results of the above command:
172.17.0.1 - - [19/Apr/2020:16:01:15 +0000] "GET / HTTP/1.1" 200 612 "-" "kube-probe/1.18" "-"172.17.0.1 - - [19/Apr/2020:16:01:20 +0000] "GET / HTTP/1.1" 200 612 "-" "kube-probe/1.18" "-"172.17.0.1 - - [19/Apr/2020:16:01:25 +0000] "GET / HTTP/1.1" 200 612 "-" "kube-probe/1.18" "-"172.17.0.1 - - [19/Apr/2020:16:01:30 +0000] "GET / HTTP/1.1" 200 612 "-" "kube-probe/1.18" "-"172.17.0.1 - - [19/Apr/2020:16:01:35 +0000] "GET / HTTP/1.1" 200 612 "-" "kube-probe/1.18" "-"172.17.0.1 - - [19/Apr/2020:16:01:40 +0000] "GET / HTTP/1.1" 200 612 "-" "kube-probe/1.18" "-"172.17.0.1 - - [19/Apr/2020:16:01:45 +0000] "GET / HTTP/1.1" 200 612 "-" "kube-probe/1.18" "-"172.17.0.1 - - [19/Apr/2020:16:01:50 +0000] "GET / HTTP/1.1" 200 612 "-" "kube-probe/1.18" "-"172.17.0.1 - - [19/Apr/2020:16:01:55 +0000] "GET / HTTP/1.1" 200 612 "-" "kube-probe/1.18" "-"
grep command can filter out irrelevant information or view specific events. For example, the following kube-probe might be irrelevant information, and we can filter it using the grep command.
$ kubectl logs cherry-chart-88d49478c-dmcfv -n charts | grep -vie kube-probe127.0.0.1 - - [10/Apr /2020:23:01:55 +0000] "GET / HTTP/1.1" 200 612 "-" "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:75.0) Gecko/20100101 Firefox/75.0" “-”
In some deployments, there may be a Pod with multiple containers, so we can use -c <container name> in the logs command to find the logs of a specific container.
Kubectl exec
Similar to the docker exec command, the exec command can also directly troubleshoot applications within containers. It is especially useful when the Pod’s logs cannot pinpoint the issue. Also, note that when using the exec command, you must use the shell used inside the Pod as the last parameter of the command.
$ kubectl exec -it cherry-chart-88d49478c-dmcfv -n charts -- /bin/bashroot@cherry-chart-88d49478c-dmcfv:/#
Kubectl cp
Kubectl cp command is similar to the Linux cp command, used for copying files and directories between containers. Additionally, this command can also be used for recovery backups in emergencies such as automation failures.
Here is an example of copying a local file to a container. The command format is:kubectl cp <filename> <namespace/podname:/path/tofile>.
$ kubectl cp commands_copy.txt charts/cherry-chart-88d49478c-dmcfv:commands.txt$ kubectl exec -it cherry-chart-88d49478c-dmcfv -n charts -- /bin/bashroot@cherry-chart-88d49478c-dmcfv:/# lsbin  boot  commands.txt  dev  etc  home  lib  lib64  media  mnt  opt  proc  root  run  sbin  srv  sys  tmp  usr  var
Below is an example of copying a file from inside the container to the local computer. The command format is:kubectl cp <namespace/podname:/path/tofile>.
$ kubectl cp charts/cherry-chart-88d49478c-dmcfv:commands.txt commands_copy.txt$ lscommands_copy.txt
END
Recommended Kubernetes CKA Practical Training Class:

Shenzhen Station: June 19-21

Online Live Class: July 5
Essential 9 kubectl Commands for Operations

Essential 9 kubectl Commands for Operations

Essential 9 kubectl Commands for Operations

Leave a Comment

×