[Cloud native | Learning Kubernetes from scratch] 25. In-depth understanding of kubectl

insert image description here

1. Introduction to kubectl

kubectl is a command-line tool for operating k8s cluster, installed on the master node of k8s, using kubectl it will look for a file named config in the $HOME/.kube directory, you can set the Kubeconfig environment variable or set a specific kubeconfig, kubectl can also operate k8s clusters using specific kubeconfig files.

By interacting with the apiserver, kubectl can add, delete, modify, and check various resources in the k8s cluster. The following will introduce kubectl syntax, command line operations, and introduce common examples. Command details, parameters, and subcommands can be viewed in the kubectl reference documentation.

1.kubectl syntax

The kubectl syntax format is as follows, which can be executed on the master node of the k8s cluster: kubectl [command] [TYPE] [NAME] [flags]

2. Explanation of the above syntax

command: Specifies the operation to be performed on one or more resources, such as create, get, describe, delete, etc.

type: Specifies the resource type, which can be pod, deployment, statefulset, service, etc. Resource types are not case-sensitive and can be specified in singular, plural, or abbreviated forms. For example, the following command outputs the same result:

kubectl get pod pod1

kubectl get pods pod1

kubectl get po pod1

NAME: Specifies the name of the resource. Names are case sensitive. If the name is omitted, details for all resources are displayed: kubectl get pods.

flags: Specifies optional parameters. For example, you can use -o to see which machine a pod is on

Note: Arguments specified from the command line override default values ​​and any corresponding environment variables.

3. Perform operations on multiple resources

Each resource can be specified by type, name, one or more files:

  1. Specify resources by type and name

To group all resources of the same type:

TYPE1 name1 name2 name<#>。

Example: kubectl get pod example-pod1 example-pod2

Specify multiple resource types separately:

TYPE1/name1 TYPE1/name2 TYPE2/name3 TYPE<#>/name<#>。

例:kubectl get pod/example-pod1 pod/example-pod2 deployment/example-rc1

[root@k8smaster ~]# kubectl get pods/tomcat-deploy-6b65dd5799-88676 deployment/tomcat-deploy
NAME                                 READY   STATUS    RESTARTS   AGE
pod/tomcat-deploy-6b65dd5799-88676   1/1     Running   5          2d21h

NAME                            READY   UP-TO-DATE   AVAILABLE   AGE
deployment.apps/tomcat-deploy   0/2     2            0           2d21h

4.kubectl –-help

You can view the help commands of kubectl

Second, kubectl operation command demonstration

Reference: http://docs.kubernetes.org.cn/477.html

The following explains the commands and syntax related to kubectl operations:

annotate

  1. Description: Add or update comments for one or more resources.

Annotations are composed of key/value. The purpose of Annotations is to store auxiliary data, especially the data operated by tools and system extensions. If –overwrite is true, existing annotations can be overwritten. Otherwise, attempting to overwrite annotations will result in an error. If set If --resource-version is specified, the update will use this resource version, otherwise it will use the original resource version.

  1. grammar:

kubectl annotate (-f FILENAME | TYPE NAME | TYPE/NAME) KEY_1=VAL_1 … KEY_N=VAL_N [–overwrite] [–all] [–resource-version=version] [flags]

  1. Example:

Update the "kubectl-pod" pod and set the value of the annotation "description" to "my kubectl-pod". If the same annotation is set multiple times, only the last set value will be used.

kubectl annotate pods kubectl-pod description=‘my kubectl-pod’

Update the pod "kubectl-pod", set the value of annotation "description" to "my tomcat", overwriting the existing value

kubectl annotate --overwrite pods kubectl-pod description=‘my tomcat’

[root@k8smaster ~]# kubectl annotate pods tomcat-deploy-6b65dd5799-88676 description='my kubectl-pod'
pod/tomcat-deploy-6b65dd5799-88676 annotated
[root@k8smaster ~]# kubectl describe pods tomcat-deploy-6b65dd5799-88676
Name:         tomcat-deploy-6b65dd5799-88676
Namespace:    default
Priority:     0
Node:         k8snode1/192.168.11.136
Start Time:   Thu, 11 Aug 2022 02:17:38 -0700
Labels:       app=tomcat
              pod-template-hash=6b65dd5799
              release=canary
Annotations:  cni.projectcalico.org/podIP: 10.244.249.28/32
              cni.projectcalico.org/podIPs: 10.244.249.28/32
              description: my kubectl-pod

api-versions

  1. grammar:

kubectl api-versions [flags]

  1. Description: List available api versions

  2. The meaning of various apiVersion:

alpha: internal beta version, contains many bugs, there may be bugs in use, if this version is abandoned, customers will not be notified
eta: public beta version, this version can be used normally after a lot of testing, some details may change, But this version stable will not be abandoned
: Stable version: This version is very stable and can be used with confidence. Subsequent versions will always include this stable version, named like v1

  1. The results displayed by kubectl api-versions are as follows

admissionregistration.k8s.io/v1 #Admission control related api

v1 # Stable version of Kubernetes API, contains many core objects: pod, service, etc.

apps/v1 #Contains some common application layer api combinations, such as: Deployments, Statefulset, Daemonset, etc.

[root@k8smaster ~]# kubectl api-versions
admissionregistration.k8s.io/v1
admissionregistration.k8s.io/v1beta1
apiextensions.k8s.io/v1
apiextensions.k8s.io/v1beta1

apply

  1. grammar:

kubectl apply -f FILENAME [flags]

Make changes to the resource's application configuration from a file. Declarative update configuration files.

autoscale

Autoscales a set of pods managed by a replica controller.

  1. grammar:

kubectl autoscale (-f FILENAME | TYPE NAME | TYPE/NAME) [–min=MINPODS] --max=MAXPODS [–cpu-percent=CPU] [flags]

cluster-info

  1. grammar:

kubectl cluster-info [flags] Displays endpoint information about masters and services in the cluster.

[root@k8smaster ~]# kubectl cluster-info
Kubernetes control plane is running at https://192.168.11.129:6443
KubeDNS is running at https://192.168.11.129:6443/api/v1/namespaces/kube-system/services/kube-dns:dns/proxy
Metrics-server is running at https://192.168.11.129:6443/api/v1/namespaces/kube-system/services/https:metrics-server:/proxy

config

  1. grammar:

kubectl config SUBCOMMAND [flags] Modify kubeconfig file

create, generally not used, use apply instead of this

  1. grammar:

kubectl create -f FILENAME [flags] Create one or more resources from a file or standard input.

delete

  1. grammar:

kubectl delete (-f FILENAME | TYPE [NAME | /NAME | -l label | --all]) [flags] Delete a resource from file, standard input, or the specified label selector, name, resource selector, or resource.

[root@k8smaster ~]# kubectl delete deployment tomcat-deploy
deployment.apps "tomcat-deploy" deleted

describe

  1. grammar:

kubectl describe (-f FILENAME | TYPE [NAME_PREFIX | /NAME | -l label]) [flags] Display detailed status of one or more resources.

[root@k8smaster ~]# kubectl describe pods tomcat-deploy-6b65dd5799-88676
[root@k8smaster ~]# kubectl describe pod/tomcat-deploy-6b65dd5799-88676

edit

  1. grammar:

kubectl edit (-f FILENAME | TYPE NAME | TYPE/NAME) [flags] Use the default editor to edit and update the definition of one or more resources on the server, changing dynamically.

exec

  1. grammar:

kubectl exec POD-name [-c CONTAINER-name] [-i] [-t] [flags] [-- COMMAND [args…]] Execute a command for the containers in the pod.

The following command is the command to log in to the container in the pod, -c is the name of the container, if there is only one, you don't need to write it.

kubectl exec calico-node-cblk2 -n kube-system -i -t – /bin/sh

explain

  1. grammar:

kubectl explain [–recursive=false] [flags] Get documentation for various resources. For example, pod, node, service, etc. are equivalent to help commands, which can tell us how
to create resources

expose

  1. grammar:

kubectl expose (-f FILENAME | TYPE NAME | TYPE/NAME) [–port=port] [–protocol=TCP|UDP] [–target-port=number-or-name] [–name=name] [–externalip= external-ip-of-service] [–type=type] [flags] Expose the replica controller, service or pod as a new Kubernetes service.

get

  1. grammar:

kubectl get (-f FILENAME | TYPE [NAME | /NAME | -l label]) [–watch] [–sortby=FIELD] [[-o | --output]=OUTPUT_FORMAT] [flags]
List one or more resource.

label

  1. grammar:

kubectl label (-f FILENAME | TYPE NAME | TYPE/NAME) KEY_1=VAL_1 … KEY_N=VAL_N [–overwrite] [–all] [–resource-version=version] [flags] Add or update labels for one or more resources .

[root@k8smaster ~]# kubectl label pods tomcat-deploy-6b65dd5799-88676 a=b
pod/tomcat-deploy-6b65dd5799-88676 labeled

logs

  1. grammar:

kubectl logs POD [-c CONTAINER] [–follow] [flags] Print the log of the container, -c can specify the container

[root@k8smaster ~]# kubectl logs tomcat-deploy-6b65dd5799-88676

patch

  1. grammar:

kubectl patch (-f FILENAME | TYPE NAME | TYPE/NAME) --patch PATCH [flags] Update one or more fields of the resource

port-forward

1) Syntax:

kubectl port-forward POD [LOCAL_PORT:]REMOTE_PORT […[LOCAL_PORT_N:]REMOTE_PORT_N] [flags] Forward one or more local ports to the Pod.

proxy

  1. grammar:

kubectl proxy [–port=PORT] [–www=static-dir] [–www-prefix=prefix] [–apiprefix=prefix] [flags] Proxy to run the Kubernetes API server.

replace

  1. Syntax: kubectl replace -f FILENAM Replace resource from file or standard input.

run

  1. grammar:

kubectl run NAME --image=image [–env=“key=value”] [–port=port] [–dryrun=server | client | none] [–overrides=inline-json] [flags] Run the specified on the cluster mirror

kubectl run nginx --image=nginx

You can create an nginx application, and the actual creation of pod applications is created by writing a resource manifest file

scale

  1. grammar:

kubectl scale (-f FILENAME | TYPE NAME | TYPE/NAME) --replicas=COUNT [–resource-version=version] [–current-replicas=count] [flags] Update the size of the specified replica controller (change the number of replicas) .

version

  1. grammar:

kubectl version [–client] [flags] show the version of Kubernetes running on the client and server

Resource Type

The following table lists all supported resource types and their abbreviated aliases:

[root@k8smaster ~]# kubectl api-resources
NAME                              SHORTNAMES   APIVERSION                             NAMESPACED   KIND
bindings                                       v1                                     true         Binding
componentstatuses                 cs           v1                                     false        ComponentStatus
configmaps                        cm           v1                                     true         ConfigMap
endpoints                         ep           v1                                     true         Endpoints
events                            ev           v1                                     true         Event
limitranges                       limits       v1                                     true         LimitRange
namespaces                        ns           v1                                     false        Namespace
nodes                             no           v1                                     false        Node
persistentvolumeclaims            pvc          v1                                     true         PersistentVolumeClaim
persistentvolumes                 pv           v1                                     false        PersistentVolume
pods                              po           v1                                     true         Pod
podtemplates                                   v1                                     true         PodTemplate
replicationcontrollers            rc           v1                                     true         ReplicationController
resourcequotas                    quota        v1                                     true         ResourceQuota
secrets                                        v1                                     true         Secret
serviceaccounts                   sa           v1                                     true         ServiceAccount
services                          svc          v1                                     true         Service
mutatingwebhookconfigurations                  admissionregistration.k8s.io/v1        false        MutatingWebhookConfiguration
validatingwebhookconfigurations                admissionregistration.k8s.io/v1        false        ValidatingWebhookConfiguration
customresourcedefinitions         crd,crds     apiextensions.k8s.io/v1                false        CustomResourceDefinition
apiservices                                    apiregistration.k8s.io/v1              false        APIService
controllerrevisions                            apps/v1                                true         ControllerRevision
daemonsets                        ds           apps/v1                                true         DaemonSet
deployments                       deploy       apps/v1                                true         Deployment
replicasets                       rs           apps/v1                                true         ReplicaSet
statefulsets                      sts          apps/v1                                true         StatefulSet
tokenreviews                                   authentication.k8s.io/v1               false        TokenReview
localsubjectaccessreviews                      authorization.k8s.io/v1                true         LocalSubjectAccessReview
selfsubjectaccessreviews                       authorization.k8s.io/v1                false        SelfSubjectAccessReview
selfsubjectrulesreviews                        authorization.k8s.io/v1                false        SelfSubjectRulesReview
subjectaccessreviews                           authorization.k8s.io/v1                false        SubjectAccessReview
horizontalpodautoscalers          hpa          autoscaling/v1                         true         HorizontalPodAutoscaler
cronjobs                          cj           batch/v1beta1                          true         CronJob
jobs                                           batch/v1                               true         Job
certificatesigningrequests        csr          certificates.k8s.io/v1                 false        CertificateSigningRequest
leases                                         coordination.k8s.io/v1                 true         Lease
bgpconfigurations                              crd.projectcalico.org/v1               false        BGPConfiguration
bgppeers                                       crd.projectcalico.org/v1               false        BGPPeer
blockaffinities                                crd.projectcalico.org/v1               false        BlockAffinity
clusterinformations                            crd.projectcalico.org/v1               false        ClusterInformation
felixconfigurations                            crd.projectcalico.org/v1               false        FelixConfiguration
globalnetworkpolicies                          crd.projectcalico.org/v1               false        GlobalNetworkPolicy
globalnetworksets                              crd.projectcalico.org/v1               false        GlobalNetworkSet
hostendpoints                                  crd.projectcalico.org/v1               false        HostEndpoint
ipamblocks                                     crd.projectcalico.org/v1               false        IPAMBlock
ipamconfigs                                    crd.projectcalico.org/v1               false        IPAMConfig
ipamhandles                                    crd.projectcalico.org/v1               false        IPAMHandle
ippools                                        crd.projectcalico.org/v1               false        IPPool
kubecontrollersconfigurations                  crd.projectcalico.org/v1               false        KubeControllersConfiguration
networkpolicies                                crd.projectcalico.org/v1               true         NetworkPolicy
networksets                                    crd.projectcalico.org/v1               true         NetworkSet
endpointslices                                 discovery.k8s.io/v1beta1               true         EndpointSlice
events                            ev           events.k8s.io/v1                       true         Event
ingresses                         ing          extensions/v1beta1                     true         Ingress
flowschemas                                    flowcontrol.apiserver.k8s.io/v1beta1   false        FlowSchema
prioritylevelconfigurations                    flowcontrol.apiserver.k8s.io/v1beta1   false        PriorityLevelConfiguration
ingressclasses                                 networking.k8s.io/v1                   false        IngressClass
ingresses                         ing          networking.k8s.io/v1                   true         Ingress
networkpolicies                   netpol       networking.k8s.io/v1                   true         NetworkPolicy
runtimeclasses                                 node.k8s.io/v1                         false        RuntimeClass
poddisruptionbudgets              pdb          policy/v1beta1                         true         PodDisruptionBudget
podsecuritypolicies               psp          policy/v1beta1                         false        PodSecurityPolicy
clusterrolebindings                            rbac.authorization.k8s.io/v1           false        ClusterRoleBinding
clusterroles                                   rbac.authorization.k8s.io/v1           false        ClusterRole
rolebindings                                   rbac.authorization.k8s.io/v1           true         RoleBinding
roles                                          rbac.authorization.k8s.io/v1           true         Role
priorityclasses                   pc           scheduling.k8s.io/v1                   false        PriorityClass
csidrivers                                     storage.k8s.io/v1                      false        CSIDriver
csinodes                                       storage.k8s.io/v1                      false        CSINode
storageclasses                    sc           storage.k8s.io/v1                      false        StorageClass
volumeattachments                              storage.k8s.io/v1                      false        VolumeAttachment

write at the end

It is not easy to create, if you think the content is helpful to you, please give me a three-link follow to support me! If there are any mistakes, please point them out in the comments and I will change them in time!
The series that is currently being updated: learn k8s from scratch.
Thank you for watching. The article is mixed with personal understanding. If there is any error, please contact me and point it out~

Guess you like

Origin blog.csdn.net/qq_45400861/article/details/127147257