Kubernetes cluster management tool kubectl

summary

kubectl is the command-line tool of Kubernetes cluster. kubectl can manage the cluster itself and install and deploy container applications on the cluster

Command format

The command format is as follows

kubectl [command] [type] [name] [flags]

parameter

  • command: Specifies the operations to be performed on the resource, such as create, get, describe, and delete
  • Type: Specifies the resource type. The resource type is case sensitive. Developers can use singular, plural and abbreviated forms

Common commands

kubectl help for more information

Help information can be obtained through the help command

# Command to get kubectl
kubectl --help

# Get the introduction and use of a command
kubectl get --help

1, Command classification

Basic command

Common basic commands

commandintroduce
createCreate resources by file name or standard input
exposeExpose a resource as a new Service
runRunning a specific image in a cluster
setSet specific functions on the object
getDisplays one or more resources
explainDocument references
editEdit an asset using the default editor
deleteDelete resources by file name, standard input, resource name or label

Deployment command

commandintroduce
rolloutManage publishing of resources
rolling-updateRolling updates for a given replication controller
scaleExpand or shrink the number of pods, Deployment, ReplicaSet, RC or Job
autoscaleCreate or automatically shrink a Pod and select one

Cluster management command

commandintroduce
certificateModify certificate resource
cluster-infoDisplay cluster information
topDisplay resources (CPU/M)
cordonMarked node is not schedulable
uncordonMarked nodes can be scheduled
drainExpel applications on nodes and prepare for offline maintenance
taintModify node taint tag

Fault and commissioning commands

commandintroduce
describeDisplays the details of a specific resource or resource group
logsPrint a container log in a Pod. If the Pod has only one container, the container name is optional
attachAttach to a running container
execExecute command to container
port-forwardForward one or more
proxyRun a proxy to Kubernetes API Server
cpCopy files or directories into containers
authCheck authorization

Other commands

commandintroduce
applyApply configuration to resources by file name or standard input
patchUse the patch to modify and update the fields of resources
replaceReplace a resource with a file name or standard input
convertConverting profiles between different API versions
labelUpdate labels on resources
annotateUpdate comments on resources
completionIt is used to realize automatic completion of kubectl tool
api-versionsPrint supported API versions
configModify kubeconfig file (used to access API, such as configuring authentication information)
helpAll command help
pluginRun a command line plug-in
versionPrint client and service version information

Currently used commands

1.1 kubectl get list resources

Kubectl get is the most commonly used command in k8s. Remember that k8s abstracts everything into resources, and kubectl get is used to view these resources. The most common resource is pod.

What is pod?
The concept of pod is actually very similar to the container in docker. He is the smallest working unit in k8s. You can think of pod as a small robot, and k8s Abstract large resource pool is their factory.

What is the relationship between pod and docker container?
pod encapsulates one or more docker containers into a unified whole for management and external services.

Not only our own services should be packaged as pods, but even k8s we run on a pile of pods. Next, let's take a look at k8s's pod:

kubectl get pod -n kube-system

-The n parameter specifies which namespace of the pod to view. k8s all pods are placed under the Kube system namespace.

Each line is a resource. The resource we see here is pod. The number of pods you see may be inconsistent with mine, because this list includes k8s the pods running on all nodes. The more nodes you add, the more pods you will display. Let's look at it one by one:

  • NAME: the first column is the NAME of the pod, k8s which can be randomly assigned a five digit suffix.
  • READY: the second column is the number of docker containers READY in the pod. As mentioned above, pod encapsulates one or more docker containers. Here, 1 / 1 means 1 container READY / 1 container in total.
  • STATUS: the third column is the current STATUS of pod. Here are some common statuses:
Status namemeaning
RunningIn operation
ErrorException, unable to provide service
PendingThe service cannot be provided temporarily due to preparation
TerminalingEnding, about to be removed
UnknownUnknown state, mostly due to node downtime
PullImageBackOffImage pull failed
  • RESTART: k8s can automatically RESTART the pod. This line indicates how many times the pod has been restarted.
  • AGE: how long did pod exist.

kubectl get can list all resources in k8s
This article only introduces how to use kubectl to get the list of pods. But don't bind get and pod together. Pod is just a service in k8s. You can not only get pod, but also get SVC (view service), get RS (view replica controller), get deploy (view deployment), etc. if you want to view a resource and don't know what the command is, kbuectl get < resource name > is right.
If you want to see more information, you can specify the - o wide parameter as follows:

kubectl get pod -n kube-system -o wide

1.2 kubectl describe view details

The kubectl describe command can be used to view the specific information of a resource. It can also view the details of all resources, but the most commonly used is to view the details of the pod. He can also use the - n parameter to specify the namespace where the resource is located.

kubectl describe pod kube-apiserver-iz2zeb4qsoj3p5ymi6ksehz -n kube-system

Output result:

1.3 kubectl logs viewing logs

If you want to view the specific log of a pod, you can view it through kubectl logs < pod name >. Note that this can only view the log of the pod. You can continuously view the log by adding the - f parameter. For example, check the log of a flannel pod in the Kube system namespace, and pay attention to modifying the pod Name:

kubectl logs -f -n kube-system kube-apiserver-iz2zeb4qsoj3p5ymi6ksehz

If you still have a problem, you can use runkuctl to view the status of a service, but you can use runkuctl to find it.

1.4 kubectl create create resource

Everything in k8s can be created by kubectl create command. Whether you want to create a pod or a large rolling upgrade service deployment, the create command can do it. There are two common methods to generate a resource using create, one is to create from yaml configuration file and the other is to create it simply:
Create from yaml profile
If you want k8s as like as two peas in your imagination, you need to describe the resource in detail and fully. K8s provides a way to create a file in yaml format, define an object according to the structure specified by k8s, and then pass the file to k8s with the following methods. It can be generated according to your description:

kubectl create -f <Profile name.yaml>

For example, the simplest pod can be created by using the following configuration file:
kubia-manual.yaml

apiVersion: v1
kind: Pod
metadata:
  name: kubia-manual
spec:
  containers:
  - image: luksa/kubia
    name: kubia
    ports:
    - containerPort: 8080
      protocol: TCP

Then use kubectl create - F kubia manual Yaml to create
Easy creation
k8s provides easy creation methods for some common resources, such as service, namespace, deployment, etc. these methods can be created by kubectl create < resource type > < resource name >. For example, if I want to create a namespace called Hello world, I can directly use the following command:

kubectl create namespace hello-world

1.5 kubectl explain configuration

K8s can generate resources through configuration files. In order to describe the appearance of resources in detail as much as possible, k8s provides a large number of configuration items. The explain command can help us quickly understand the role of a configuration item.
For example, if I want to know what the basic attributes of creating a pod are, I can enter kubectl explain pod:

[root@iZ2zeb4qsoj3p5ymi6ksehZ k8s]# kubectl explain pod
KIND:     Pod
VERSION:  v1

DESCRIPTION:
     Pod is a collection of containers that can run on a host. This resource is
     created by clients and scheduled onto hosts.

FIELDS:
   apiVersion	<string>
     APIVersion defines the versioned schema of this representation of an
     object. Servers should convert recognized schemas to the latest internal
     value, and may reject unrecognized values. More info:
     https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources

   kind	<string>
     Kind is a string value representing the REST resource this object
     represents. Servers may infer this from the endpoint the client submits
     requests to. Cannot be updated. In CamelCase. More info:
     https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds

   metadata	<Object>
     Standard object's metadata. More info:
     https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata

   spec	<Object>
     Specification of the desired behavior of the pod. More info:
     https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status

   status	<Object>
     Most recently observed status of the pod. This data may not be up to date.
     Populated by the system. Read-only. More info:
     https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status

What if you want to know the configuration items of matedata (metadata) field?

kubectl explain pod.matedata

1.8 kubectl delete

The delete command is very simple to use

kubectl delete <Resource type> <Resource name>

If you want to delete all pod s, you can write this:

kubectl delete pod --all 

If you want to delete everything! Then write this:

kubectl delete all --all

1.9 kubectl edit modify configuration

What if we need to change the settings of some services for some reasons during routine maintenance? Each resource is generated through a yaml configuration file. Even the resources created simply are k8s created from a default configuration file.
We can attach the - o yaml file after the get command to view the configuration items of an existing resource. For example, to view the configuration items of pod kubia Manual:

kubectl get pod kubia-manual -o yaml

Then the default editor of system settings will pop up. At this time, we can make any changes, such as changing the name to kubia-manual-v2. First, navigate to metadata Name field, and then modify its value:

apiVersion: v1
kind: Pod
metadata:
  creationTimestamp: "2019-07-07T07:31:11Z"
  name: kubia-manual # > kubia-manual-v2
  namespace: default
  resourceVersion: "790349"
  selfLink: /api/v1/namespaces/default/pods/kubia-manual
  uid: 51eaa1e6-5749-4e79-aec9-12cf2a3e485d
spec:
  ...

After modification, enter: wq save, and then you will find that k8s actually reports an error

A copy of your changes has been stored to "/tmp/kubectl-edit-vj0ts.yaml"
error: At least one of apiVersion, kind and name was changed

This is a k8s restriction. You cannot change the name or type of a running resource. Then let's modify other properties. For example, specify the label of the pull image as latest. Re edit the configuration file and find the spec. containers.image field, and then save after adding: latest. Then k8s the message "save succeeded" will pop up, as follows:

pod/kubia-manual edited

At this time, we can check the details of the pod in kubectl describe pod kubia manual and find that the corresponding fields have been updated:

Name:         kubia-manual
Namespace:    default
Priority:     0
Node:         worker1/192.168.56.21
Start Time:   Sun, 07 Jul 2019 07:31:11 +0000
Labels:       <none>
Annotations:  <none>
Status:       Running
IP:           10.244.1.14
Containers:
  kubia:
    Container ID:   docker://89617ffcc9b1455c514e5129a9b2694c43a2aff9b4c0449d5efc4aea1fe41db6
    # The latest tag has been explicitly applied
    Image:          luksa/kubia:latest
    Image ID:       docker-pullable://luksa/kubia@sha256:3f28e304dc0f63dc30f273a4202096f0fa0d08510bd2ee7e1032ce600616de24
    Port:           8080/TCP

Kubectl edit < resource type > < resource name > can edit the specific configuration items of a resource. In actual use, the edit command is more inclined to manually modify a configuration item to solve the problem. For example, modify the image address to solve the problem that the image cannot be pulled.

1.10 kubectl apply application configuration

Using kubectl edit can edit the configuration easily and quickly, but what if we want to make a wide range of modifications to the resources? You can't open configuration items and modify them manually one by one. At this time, we can use our kubectl apply command. The basic usage is as follows:

kubectl apply -f <New profile name.yaml>

kubeclt apply can be said to be an upgraded version of the edit command. The biggest difference between kubeclt and edit is that apply accepts a yaml configuration file instead of opening an editor to modify it. k8s after receiving the configuration file, it will find the target resource according to the metadata in the metadata. If not, it will be directly created. If found, it will compare the differences between the configuration files in turn, and then apply different configurations.
There are many advantages to doing this. For example, you can apply - F through kubectl https://some-network-site/resourse.yaml The command deploys your resources from a website, so that when its manager updates the configuration file, you only need to execute the command again to apply the updated content, and you don't care what configuration items have been modified.

Restart k8s service

Delete pod directly

The service will be interrupted

kubectl -n <namespace> get pod
kubectl -n <namespace> delete pod <pod name>
kubectl -n <namespace> delete pod --all

rollout

Uninterrupted service

kubectl -n <namespace> rollout status deployments  //View all statuses
kubectl -n <namespace> rollout restart deployments  //Restart all services
kubectl -n <namespace> rollout status deployments/<service-name>  //Restart the specified service

Keywords: Docker Kubernetes Container

Added by jsucupira on Mon, 07 Feb 2022 02:46:35 +0200