[Cloud native] k8s cluster command line tool kubectl basic operation command practice detailed explanation

1. Preparation

The command-line tool for the cluster control plane (master node) provided by Kubernetes to communicate with the Kubernetes APIServer - kubectl. kubectl default configuration file directory $HOME/.kube/config. The configuration file of kubectl can be specified through the --kubeconfig parameter.

If you have already done the following operations, you can skip them.

1.1、Replication Controller

(1) Create myhello-rc.yaml and write the following content:

vim myhello-rc.yaml

content:

apiVersion: v1
kind: ReplicationController # 副本控制器 RC
metadata:
  namespace: default
  name: myhello-rc # RC名称,全局唯一
  labels:
    name: myhello-rc
spec:
  replicas: 5 # Pod副本期待数量
  selector:
    name: myhello-rc-pod
  template: # pod的定义模板
    metadata:
      labels:
        name: myhello-rc-pod
    spec:
      containers: # Pod 内容的定义部分
      - name: myhello #容器的名称
        image: nongtengfei/hello:1.0.0 #容器对应的 Docker Image
        imagePullPolicy: IfNotPresent
        ports:
        - containerPort: 80
        env: # 注入到容器的环境变量
        - name: env1
          value: "k8s-env1"
        - name: env2
          value: "k8s-env2"

Usually, pods are not configured separately, and pods are deployed through a certain type of replica controller resources. Reason: If pods are configured separately, all pods on the current node need to be drained when the cluster is upgraded, which will cause problems, because the pod does not have any replica controllers to control it, and the cluster has no expectations for him. When the node is drained, Pods will not be scheduled and respawned.

(2) Create a service for RC.

vim myhello-svc.yaml

content:

apiVersion: v1
kind: Service
metadata:
  name: myhello-svc
  labels:
    name: myhello-svc
spec:
  type: NodePort # 对外提供端口
  ports:
  - port: 80
    protocol: TCP
    targetPort: 80
    name: http
    nodePort: 30000
  selector:
    name: myhello-rc-pod

(3) Application configuration.

kubectl apply -f myhello-svc.yaml -f myhello-rc.yaml

1.2、Deployment

(1) Create myapp-deployment.yaml and write the following content:

vim myapp-deployment.yaml

content:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: myapp-deployment
  labels:
    name: myapp-deploy
spec:
  replicas: 5
  selector:
    matchLabels:
      name: myapp-deploy-pod
  template:
    metadata:
      labels:
        name: myapp-deploy-pod
    spec:
     #nodeSelector:
       #nodetype: worker
      containers: # Pod 内容的定义部分
      - name: myhello #容器的名称
        image: nongtengfei/hello:1.0.0 #容器对应的 Docker Image
        imagePullPolicy: IfNotPresent
        ports:
        - containerPort: 80
        env: # 注入到容器的环境变量
        - name: env1
          value: "k8s-env1"
        - name: env2
          value: "k8s-env2"
        resources:
          requests:
            cpu: 100m
      - name: myredis #容器的名称
        image: redis #容器对应的 Docker Image
        imagePullPolicy: IfNotPresent
        ports:
        - containerPort: 6379
        env: # 注入到容器的环境变量
        - name: env1
          value: "k8s-env1"
        - name: env2
          value: "k8s-env2"
        resources:
          requests:
            cpu: 100m

(2) Create a service for the deployment.

vim myapp-svc.yaml

content:

apiVersion: v1
kind: Service
metadata:
  name: myapp-svc
  labels:
    name: myapp-svc
spec:
  type: NodePort # 对外提供端口
  ports:
  - port: 80
    protocol: TCP
    targetPort: 80
    name: http
    nodePort: 30001
  selector:
    name: myapp-deploy-pod

(3) Application configuration.

kubectl apply -f myapp-svc.yaml -f myapp-deployment.yaml

1.3、DaemonSet

(1) Create myapp-deployment.yaml and write the following content:

vim myapp-ds.yaml

content:

apiVersion: apps/v1
kind: DaemonSet
metadata:
  name: myapp-ds
  namespace: default
  labels:
    app: myapp-ds
spec:
  selector:
    matchLabels:
      app: myapp-ds
  template:
    metadata:
      labels:
        app: myapp-ds
    spec:
      tolerations:
      - key: node-role.kubernetes.io/control-plane
        operator: Exists
        effect: NoSchedule
      containers: # Pod 内容的定义部分
      - name: myhello #容器的名称
        image: nongtengfei/hello:1.0.0 #容器对应的 Docker Image
        imagePullPolicy: IfNotPresent
        ports:
        - containerPort: 80
        env: # 注入到容器的环境变量
        - name: env1
          value: "k8s-env1"
        - name: env2
          value: "k8s-env2"

(2) Create a service for DaemonSet.

vim myapp-ds-svc.yaml

content:

apiVersion: v1
kind: Service
metadata:
  name: myapp-ds-svc
  labels:
    name: myapp-ds-svc
spec:
  type: NodePort # 对外提供端口
  ports:
  - port: 8080
    protocol: TCP
    targetPort: 80
    name: http
    nodePort: 30002
  selector:
    app: myapp-ds

(3) Application configuration:

kubectl apply -f myapp-ds-svc.yaml -f myapp-ds.yaml

1.4. View the created svc and pod

$ kubectl get svc
NAME           TYPE        CLUSTER-IP      EXTERNAL-IP   PORT(S)          AGE
kubernetes     ClusterIP   10.96.0.1       <none>        443/TCP          45h
myapp-ds-svc   NodePort    10.96.41.180    <none>        8080:30002/TCP   4m3s
myapp-svc      NodePort    10.98.20.127    <none>        80:30001/TCP     6m32s
myhello-svc    NodePort    10.106.252.61   <none>        80:30000/TCP     14m

$ kubectl get pod
NAME                                READY   STATUS    RESTARTS   AGE
myapp-deployment-5659dbddd8-l6m87   0/2     Pending   0          6m41s
myapp-deployment-5659dbddd8-lxxls   0/2     Pending   0          6m41s
myapp-deployment-5659dbddd8-pqqlx   0/2     Pending   0          6m41s
myapp-deployment-5659dbddd8-xb8xp   0/2     Pending   0          6m41s
myapp-deployment-5659dbddd8-zjgsx   0/2     Pending   0          6m41s
myapp-ds-2zqf9                      1/1     Running   0          2m43s
myhello-rc-2tjmr                    0/1     Pending   0          12m
myhello-rc-44ksd                    0/1     Pending   0          12m
myhello-rc-86g79                    0/1     Pending   0          12m
myhello-rc-df225                    0/1     Pending   0          12m
myhello-rc-lfbzb                    0/1     Pending   0          12m

Only one node is established here, and there is only one pod.

1.5, kubectl command auto-completion settings

# 安装自动补全插件
sudo apt-get install -y bash-completion
# 添加.bashrc文件内容
echo "source <(kubectl completion bash)" >> ~/.bashrc
# 加载最新的.bashrc
source ~/.bashrc

Two, kubectl syntax

kubectl [command] [TYPE] [NAME] [flags]

(1) command: Specifies the operation to be performed on one or more resources, such as: create, get, describe, delete, etc.
(2) TYPE: Specifies the resource type. Resource types are case-insensitive and can be specified singular, plural, or abbreviated. For example: the following commands output the same result:

kubectl get pod pod1
kubectl get pods pod1
kubectl get po pod1

(3) NAME: Specify the resource name. Names are case sensitive. If name is omitted, this displays details for all resources. For example:

kubectl get pods

(4) When performing operations on multiple resources, you can specify each resource by type and name, or specify one or more files:

  • Specify resources by type and name:

a) Group all resources of the same type, TYPE1 name1 name2 name<#>.

kubectl get pod pod1 pod2 pod3

b) Specify multiple resource types: TYPE1/name1 TYPE2/name2 TYPE3/name3 TYPE<#>/name<#>.

kubectl get pod/pod1 pod/pod2 rc/rc1 svc/svc1
  • Specify resources with one or more files: -f file1 -f file2 -f file<#>
kubectl get -f myhello-rc.yaml -f myhello-svc.yaml

(5) flags: specify optional parameters. For example: You can use the -o or --output parameter to specify the output format.

kubectl get -f myhello-rc.yaml -f myhello-svc.yaml -o wide
kubectl get -f myhello-rc.yaml -f myhello-svc.yaml --output json

3. Basic operation commands

3.1、api-resources

API resources supported on the print server.
usage:

# 打印支持的API Resource
kubectl api-resources
# 打印更多信息
kubectl api-resources -o wide
# 根据name 排序
kubectl api-resources --sort-by=name
# 仅打印支持命名空间的资源
kubectl api-resources --namespaced=true
# 打印不支持命名空间的资源
kubectl api-resources --namespaced=false
# 根据分组打印该分组的资源,例如:apps、authorization.k8s.io 等
kubectl api-resources --api-group=apps

effect:

  1. Can help write pod definitions, such as apiversion.
  2. Assign roles and permissions.

Example:

$ 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/v2                         true         HorizontalPodAutoscaler
cronjobs                          cj           batch/v1                               true         CronJob
jobs                                           batch/v1                               true         Job
certificatesigningrequests        csr          certificates.k8s.io/v1                 false        CertificateSigningRequest
leases                                         coordination.k8s.io/v1                 true         Lease
endpointslices                                 discovery.k8s.io/v1                    true         EndpointSlice
events                            ev           events.k8s.io/v1                       true         Event
flowschemas                                    flowcontrol.apiserver.k8s.io/v1beta2   false        FlowSchema
prioritylevelconfigurations                    flowcontrol.apiserver.k8s.io/v1beta2   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/v1                              true         PodDisruptionBudget
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
csistoragecapacities                           storage.k8s.io/v1                      true         CSIStorageCapacity
storageclasses                    sc           storage.k8s.io/v1                      false        StorageClass
volumeattachments                              storage.k8s.io/v1                      false        VolumeAttachment
fly@k8s-master1:~/k8sCtlConfig$ 

3.2、api-versions

Print supported API Versions.

kubectl api-versions 

Example:

$ kubectl api-versions 
admissionregistration.k8s.io/v1
apiextensions.k8s.io/v1
apiregistration.k8s.io/v1
apps/v1
authentication.k8s.io/v1
authorization.k8s.io/v1
autoscaling/v1
autoscaling/v2
autoscaling/v2beta2
batch/v1
certificates.k8s.io/v1
coordination.k8s.io/v1
discovery.k8s.io/v1
events.k8s.io/v1
flowcontrol.apiserver.k8s.io/v1beta1
flowcontrol.apiserver.k8s.io/v1beta2
networking.k8s.io/v1
node.k8s.io/v1
policy/v1
rbac.authorization.k8s.io/v1
scheduling.k8s.io/v1
storage.k8s.io/v1
storage.k8s.io/v1beta1
v1

3.3、create

Create resources from a file or standard input. The functions of crete and apply -f are the same, but create can only be created once, while apply can be applied multiple times, and apply can apply new attributes to the line without changing the existing content.
usage:

kubectl create -f FILENAME

Example:

# 基于文件创建资源
kubectl create -f myhello-rc.yaml -f myhello-svc.yaml -f myapp-deployment.yaml -f
myapp-svc.yaml -f myapp-ds.yaml
# 将文件内容以标准输入,传入kubectl create
cat myhello-rc.yaml | kubectl create -f -
# 编辑文件,以编辑结果为输入参数
kubectl create -f myhello-rc.yaml --edit -o json

3.4、expose

Given a replica controller, service, Deployment or Pod, expose it as a new kubernetes Service, the essence of which is to associate the new Service with the Pod behind the original resource through the configuration information of the existing resource object

usage:

kubectl expose (-f FILENAME | TYPE NAME) [--port=port] [--protocol=TCP|UDP|SCTP] [--target-port=number-or-name] [--name=name] [--external-ip=external-ip-of-service] [--type=type]

Example:

# 为副本控制器myhello-rc 创建service,端口为8000,容器端口为80
kubectl expose rc myhello-rc --port=8000 --target-port=80 --name=myhello-svc-8000
# 通过replication controller 定义文件来创建service
kubectl expose -f myhello-rc.yaml --port=8000 --target-port=80 --name=myhellosvc-8000-file
# 根据指定的pod 创建service,并指定service名称
kubectl expose pod <podname> --port=444 --name=myhello-svc-444
# 通过service 创建新的service
kubectl expose service myhello-svc --port=8080 --target-port=80 --name=myhello-svc-8080
# 查看所有service
kubectl get svc
# 查看某个service详情
kubectl describe svc <svcname>

3.5、run

Start a container using the specified image in the cluster.

usage:

kubectl run NAME --image=image [--env="key=value"] [--port=port] [--dry-run=server|client] [--overrides=inline-json] [--command] -- [COMMAND] [args...]

Example:

# 通过镜像运行一个名为 nginx 的pod
kubectl run nginx --image=nginx
# 通过镜像运行一个名为myhello 的pod
kubectl run myhello --image=nongtengfei/hello:1.0.0
# 指定端口号、环境变量、labels
kubectl run redis --image=redis --port=6379 --env="DNS_DOMAIN=cluster" --env="POD_NAMESPACE=default" --labels="app=redis,env=prod"
# 只打印命令执行的结果,而不做实际操作
kubectl run nginx --image=nginx --dry-run=client
# 运行一个busybox容器,并进入交互,同时设置其重启策略为Never
kubectl run -i -t busybox --image=busybox --restart=Never
# 启动nginx pod 采用自定义启动命令和启动参数
# kubectl run nginx --image=nginx --command -- <cmd> <arg1> ... <argN>
kubectl run nginx2 --image=nginx --command -- echo 123456
# 查看默认命名空间下所有pod
kubectl get pod
# 获取单个pod并以yaml格式输出
kubectl get pod <podname> -o yaml
# 输出某个pod内所有容器的日志
kubectl logs pod/<podname> --all-containers=true
# 输出 pod/myhello-rc-dtshm 内 myhello容器的日志
kubectl logs pod/myhello-rc-dtshm -c myhello

3.6、set

Sets functional properties (environment variables, images, etc.) for objects.

usage:

kubectl set SUBCOMMAND

The following is the SUBCOMMAND.

3.6.1、env

Update resource environment variables, support pod (po), replicationcontroller (rc), deployment (deploy), daemon set (ds), status set (sts), cronjob (cj), ReplicateSet (rs) and other resource objects update

usage:

kubectl set env RESOURCE/NAME KEY_1=VAL_1 ... KEY_N=VAL_N

Example:

# 为rc/myhello-rc 添加环境变量 STORAGE_DIR=/local
kubectl set env rc/myhello-rc STORAGE_DIR=/local
# 查看 rc/myhello-rc 环境变量列表
kubectl set env rc/myhello-rc --list
# 列出所有pod的环境变量列表
kubectl set env pods --all --list
# 设置环境变量,并以yaml格式打印出来
kubectl set env rc/myhello-rc STORAGE_DIR=/data1 -o yaml
# 为所有rc设置环境变量为 EVN=prod
kubectl set env rc --all ENV=prod
# 将所有rc上环境变量 ENV移除
kubectl set env rc --all ENV-
# 移除 deployments/myapp-deployment 对象中,容器名为 myhello 的环境变量 env1
kubectl set env deployments/myapp-deployment --containers="myhello" env1-
# 根据文件,移除资源上的环境变量
kubectl set env -f myhello-rc.yaml env1-

Note: Modifying environment variables on rc will not be reflected in Pod in time; while modifying environment variables in deployment will be reflected in Pod in time.

3.6.2、image

Update the existing resource container image, support pod (po), replicationcontroller (rc), deployment (deploy), daemon set (ds), state set (sts), cronjob (cj), ReplicatSet (rs) and other resources

usage:

kubectl set image (-f FILENAME | TYPE NAME) CONTAINER_NAME_1=CONTAINER_IMAGE_1 ... CONTAINER_NAME_N=CONTAINER_IMAGE_N

Example:

# 将deployment/myapp-deployment 中myhello 容器的镜像更改为 nongtengfei/hello:1.0.1
kubectl set image deployment/myapp-deployment myhello=nongtengfei/hello:1.0.1
# 根据文件修改镜像,--local表示不向apiserver发送请求,仅本地修改并输出yaml格式内容
kubectl set image -f myapp-deployment.yaml myhello=nongtengfei/hello:1.0.1 --local -o yaml
# 修改 deployment/myapp-deployment myhello 容器和myredis容器的镜像
kubectl set image deployment/myapp-deployment myhello=nongtengfei/hello:1.0.1 myredis=redis:alpine
# 修改ds/myapp-ds myhello 容器镜像
kubectl set image ds/myapp-ds myhello=nongtengfei/hello:1.0.2

Note: Modifying the RC image will not be reflected in the Pod in time; while modifying the deployment image will be reflected in the Pod in time.

3.6.3、resources

Specify computing resource requirements (CPU, memory, etc.) for Pod template resource objects Support pod (po), replicationcontroller (rc), deployment (deploy), daemon set (ds), state set (sts), cronjob (cj), ReplicatSet (rs) and other resources.

usage:

kubectl set resources (-f FILENAME | TYPE NAME) ([--limits=LIMITS & --requests=REQUESTS]

Example:

# 设置单个容器的资源
kubectl set resources deployment myapp-deployment -c=myhello --limits=cpu=200m,memory=512Mi
# 设置myapp-deployment部署下所有容器资源
kubectl set resources deployment myapp-deployment --limits=cpu=200m,memory=512Mi --requests=cpu=100m,memory=256Mi
# 移除资源限制,设置为0即不限制
kubectl set resources deployment myapp-deployment --limits=cpu=0,memory=0 --requests=cpu=0,memory=0
# 根据文件设置资源,打印出结果,且不向apiserver发送请求
kubectl set resources -f myapp-deployment.yaml --limits=cpu=200m,memory=512Mi --local -o yaml

3.6.4、selector

Set a selector on a resource. If the resource had a selector before calling "set selector", the new selector will override the old selector.
If --resource version is specified, the update will use this resource version, otherwise the existing resource version will be used. Currently only supports
Service resource objects

usage:

kubectl set selector (-f FILENAME | TYPE NAME) EXPRESSIONS [--resourceversion=version]

Example:

# 将service myhello-svc 的label selector 修改为 env=proc
kubectl set selector svc myapp-svc env=proc
kubectl set selector svc myapp-svc name=myapp-deploy-pod
# 查看service 对象明细
kubectl describe svc myapp-svc

3.7, explain (emphasis)

Show resource documentation description.
usage:

kubectl explain RESOURCE

Role: It can help define resources.

Example:

# 获取资源及其字段的文档
kubectl explain pods
# 获取资源特定字段的文档
kubectl explain pods.spec.containers

3.8、get

Display information about one or more resources.
usage:

kubectl get [(-o|--output=)json|yaml|name|go-template|go-templatefile|template|templatefile|jsonpath|jsonpath-as-json|jsonpath-file|customcolumns|custom-columns-file|wide] (TYPE[.VERSION][.GROUP] [NAME | -l label] | TYPE[.VERSION][.GROUP]/NAME ...) [flags]

Example:

# 获取默认命名空间下所有Pod
kubectl get pods
# 获取更多Pod信息
kubectl get pods -o wide
# 获取副本控制器 myhello-rc
kubectl get replicationcontroller myhello-rc
# 获取处于apps.v1 api组下所有 deployment,并以json格式答应
kubectl get deployments.v1.apps -o json
# 获取单个Pod,以json格式数据
kubectl get -o json pod myhello-rc-278jg
# 根据文件获取对象
kubectl get -f myapp-deployment.yaml -o json
# 返回对象指定的值
kubectl get -o template deployment/myapp-deployment --template={
    
    {
    
    .status.readyReplicas}}
# 自定义返回字段,分别指定了列名为:CONTAINER 和 IMAGE
kubectl get pod -o customcolumns=CONTAINER:.spec.containers[0].name,IMAGE:.spec.containers[0].image
# 获取 所有rc 和 service
kubectl get rc,services
# 获取一个或多个资源
kubectl get rc/myhello-rc service/myhello-svc deployment/myapp-deployment

3.9、edit

Modify a resource on the server.
usage:

kubectl edit (RESOURCE/NAME | -f FILENAME)

Example:

# 修改myhello-svc service
kubectl edit svc/myhello-svc
# 以打开为json文件的方式修改
kubectl edit svc/myhello-svc -o json
# 修改资源配置,并将修改后的内容添加到注解
kubectl edit deployment/myapp-deployment -o yaml --save-config

3.10、delete

Delete resources by filename, stdin, resource and name, or by resource and label selector.
Example:

# 通过定义文件删除资源
kubectl delete -f myhello-rc.yaml
# 指定所有后缀名为yaml的文件,删除这些文件定义的资源
kubectl delete -f '*.yaml'
# 以文件内容为参数,删除资源
cat myhello-rc.yaml | kubectl delete -f -
# 删除名称为 myhello-pod 或 myhello-svc 的pod 和 service
kubectl delete pod,service myhello-pod myhello-svc
# 删除标签为 myhello-pod的pod和service
kubectl delete pods,services -l name=myhello-rc-pod
# 最小延迟删除Pod
kubectl delete pod <podname> --now
# 强制删除 Pod
kubectl delete pod <podname> --force
# 删除所有Pod
kubectl delete pods --all

3.11、label

Update the label of the resource.
usage:

kubectl label [--overwrite] (-f FILENAME | TYPE NAME) KEY_1=VAL_1 ... KEY_N=VAL_N [--resource-version=version]

Example:

# 为pod/nginx添加标签
kubectl label pods nginx status=unhealthy
# 修改已存在的label
kubectl label --overwrite pods nginx status=healthy
# 为当前命名空间下所有pod添加标签
kubectl label pods --all status=unhealthy
# 根据资源定义文件添加标签
kubectl label -f myapp-deployment.yaml status=unhealthy
# 删除当前命名空间下所有Pod的status标签
kubectl label pods --all status-
# 删除指定label
kubectl label pods nginx status-
# 根据资源定义文件删除资源标签
kubectl label -f myapp-deployment.yaml status-
# 为节点添加标签
kubectl label node k8s-master1 nodetype=master
kubectl label node k8s-node1 nodetype=worker
kubectl label node k8s-node2 nodetype=worker
kubectl label nodes k8s-node2 nodetype-
# 为pod指定部署的节点
nodeSelector:
nodetype: worker

3.12、annotate

Updates the annotation associated with the resource.
usage:

kubectl annotate [--overwrite] (-f FILENAME | TYPE NAME) KEY_1=VAL_1 ... KEY_N=VAL_N [--resource-version=version]

Example:

# 为资源类型为 rc 的 myhello-rc 添加注解 description='my hello rc'
kubectl annotate rc myhello-rc description='my hello rc'
# 为文件myhello-rc.yaml所定义的资源 添加注解 description1='my hello rc1'
kubectl annotate -f myhello-rc.yaml description1='my hello rc1'
# 重写 myhello-rc 的description 注解
kubectl annotate --overwrite rc myhello-rc description='this a replication
controller'
# 为当前命名空间下所有pod 添加注解
kubectl annotate pods --all description='myhello running golang program'
# 更新指定resourceVersion 的单一资源对象
kubectl annotate rc myhello-rc description3='my hello rc3' --resourceversion=10564
# 删除注解
kubectl annotate pods --all description

Summarize

Usually, pods are not configured separately, and pods are deployed through a certain type of replica controller resources. Reason: If pods are configured separately, all pods on the current node need to be drained when the cluster is upgraded, which will cause problems, because the pod does not have any replica controllers to control it, and the cluster has no expectations for him. When the node is drained, Pods will not be scheduled and respawned.
insert image description here

Guess you like

Origin blog.csdn.net/Long_xu/article/details/129682647