current position:Home>Detailed explanation of k8s management tool kubectl

Detailed explanation of k8s management tool kubectl

2022-01-27 08:30:03 Public righteousness

List of articles


One 、 Declarative management

1. Declarative resource management approach

  • kubernetes The only access to cluster resources for cluster management is through corresponding method calls apiserver The interface of
  • kubectl It's official. CLI Command line tools , Used with apiserver communicate , The command entered by the user on the command line , Organize and transform into apiserver Recognizable information , And then realize management k8s An effective way for all kinds of resources
  • kubectl All of your orders
    kubectl --help
    k8s Official Chinese documents :http://docs.kubernetes.org.cn/683.html
  • Increase in resources 、 Delete 、 It's easy to check , But it's not easy to change

2. k8s View relevant information

2.1 View version information

kubectl version

[[email protected] ~]# kubectl version
Client Version: version.Info{
    Major:"1", Minor:"15", GitVersion:"v1.15.1", GitCommit:"4485c6f18cee9a5d3c3b4e523bd27972b1b53892", GitTreeState:"clean", BuildDate:"2019-07-18T09:18:22Z", GoVersion:"go1.12.5", Compiler:"gc", Platform:"linux/amd64"}
Server Version: version.Info{
    Major:"1", Minor:"15", GitVersion:"v1.15.1", GitCommit:"4485c6f18cee9a5d3c3b4e523bd27972b1b53892", GitTreeState:"clean", BuildDate:"2019-07-18T09:09:21Z", GoVersion:"go1.12.5", Compiler:"gc", Platform:"linux/amd64"}

kubectl get nodes

[[email protected] ~]# kubectl get nodes 
NAME     STATUS   ROLES    AGE   VERSION
master   Ready    master   20h   v1.15.1
node01   Ready    <none>   20h   v1.15.1
node02   Ready    <none>   20h   v1.15.1

2.2 View resource object shorthand

kubectl api-resources

[[email protected] ~]# 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
namespaces                        ns                                          false        Namespace
nodes                             no                                          false        Node
persistentvolumeclaims            pvc                                         true         PersistentVolumeClaim
persistentvolumes                 pv                                          false        PersistentVolume
pods                              po                                          true         Pod
podtemplates                                                                  true         PodTemplate
replicationcontrollers            rc                                          true         ReplicationController
resourcequotas                    quota                                       true         ResourceQuota
secrets                                                                       true         Secret
serviceaccounts                   sa                                          true         ServiceAccount
services                          svc                                         true         Service
mutatingwebhookconfigurations                  admissionregistration.k8s.io   false        MutatingWebhookConfiguration
validatingwebhookconfigurations                admissionregistration.k8s.io   false        ValidatingWebhookConfiguration
customresourcedefinitions         crd,crds     apiextensions.k8s.io           false        CustomResourceDefinition
apiservices                                    apiregistration.k8s.io         false        APIService
controllerrevisions                            apps                           true         ControllerRevision
daemonsets                        ds           apps                           true         DaemonSet
deployments                       deploy       apps                           true         Deployment
replicasets                       rs           apps                           true         ReplicaSet
statefulsets                      sts          apps                           true         StatefulSet
tokenreviews                                   authentication.k8s.io          false        TokenReview
localsubjectaccessreviews                      authorization.k8s.io           true         LocalSubjectAccessReview
selfsubjectaccessreviews                       authorization.k8s.io           false        SelfSubjectAccessReview
selfsubjectrulesreviews                        authorization.k8s.io           false        SelfSubjectRulesReview
subjectaccessreviews                           authorization.k8s.io           false        SubjectAccessReview
horizontalpodautoscalers          hpa          autoscaling                    true         HorizontalPodAutoscaler
cronjobs                          cj           batch                          true         CronJob
jobs                                           batch                          true         Job
certificatesigningrequests        csr          certificates.k8s.io            false        CertificateSigningRequest
leases                                         coordination.k8s.io            true         Lease
events                            ev           events.k8s.io                  true         Event
daemonsets                        ds           extensions                     true         DaemonSet
deployments                       deploy       extensions                     true         Deployment
ingresses                         ing          extensions                     true         Ingress
networkpolicies                   netpol       extensions                     true         NetworkPolicy
podsecuritypolicies               psp          extensions                     false        PodSecurityPolicy
replicasets                       rs           extensions                     true         ReplicaSet
ingresses                         ing          networking.k8s.io              true         Ingress
networkpolicies                   netpol       networking.k8s.io              true         NetworkPolicy
runtimeclasses                                 node.k8s.io                    false        RuntimeClass
poddisruptionbudgets              pdb          policy                         true         PodDisruptionBudget
podsecuritypolicies               psp          policy                         false        PodSecurityPolicy
clusterrolebindings                            rbac.authorization.k8s.io      false        ClusterRoleBinding
clusterroles                                   rbac.authorization.k8s.io      false        ClusterRole
rolebindings                                   rbac.authorization.k8s.io      true         RoleBinding
roles                                          rbac.authorization.k8s.io      true         Role
priorityclasses                   pc           scheduling.k8s.io              false        PriorityClass
csidrivers                                     storage.k8s.io                 false        CSIDriver
csinodes                                       storage.k8s.io                 false        CSINode
storageclasses                    sc           storage.k8s.io                 false        StorageClass
volumeattachments                              storage.k8s.io                 false        VolumeAttachment

2.3 View cluster information

kubectl cluster-info

[[email protected] ~]# kubectl cluster-info
Kubernetes master is running at https://192.168.122.10:6443
KubeDNS is running at https://192.168.122.10:6443/api/v1/namespaces/kube-system/services/kube-dns:dns/proxy
 
To further debug and diagnose cluster problems, use 'kubectl cluster-info dump'.

2.4 To configure kubectl Automatic completion

source <(kubectl completion bash)

[[email protected] ~]# source <(kubectl completion bash)

It can be done by TAB Key to complete the command , It is recommended to write it to etc/profile

2.5 Check the log

journalctl -u kubelet -f

[[email protected] ~]# journalctl -u kubelet -f
-- Logs begin at  One  2021-11-01 18:58:09 CST. --
......

2.6 Basic information view

kubectl get [-o wide|json|yaml] [-n namespace]
Get information about resources ,-n Specify the namespace ,-o Specify the output format
resource It can be a specific resource name , Such as "pod nhinx-xxx"; It can also be a resource type , Such as “pod,node,svc,deploy” Multiple resources are separated by commas ; perhaps all( Show only a few core resources , Incomplete )
–all-namespaces or -A: Indicates that all namespaces are displayed
–show-labels: Show all tags
-l app: Only display the label as app Resources for
-l app=nginx: Show only those containing app label , And the value is nginx Resources for

2.6.1 see master Node status

kubectl get componentstatuses
kubectl get cs

[[email protected] ~]# kubectl get componentstatuses
NAME                 STATUS    MESSAGE             ERROR
scheduler            Healthy   ok                  
controller-manager   Healthy   ok                  
etcd-0               Healthy   {"health":"true"}   
[[email protected] ~]# kubectl get cs
NAME                 STATUS    MESSAGE             ERROR
scheduler            Healthy   ok                  
controller-manager   Healthy   ok                  
etcd-0               Healthy   {"health":"true"}   
2.6.2 View namespace

kubectl get namespace
kubectl get ns

[[email protected] ~]# kubectl get namespace
NAME              STATUS   AGE
default           Active   26h
kube-node-lease   Active   26h
kube-public       Active   26h
kube-system       Active   26h
[[email protected] ~]# kubectl get ns
NAME              STATUS   AGE
default           Active   26h
kube-node-lease   Active   26h
kube-public       Active   26h
kube-system       Active   26h

2.7 Namespace operation

2.7.1 see default All resources in the namespace

kubectl get all [-n default]
because deafult Is the default space , When no namespace is specified, the default view is default Namespace

[[email protected] ~]# kubectl get all
NAME                 TYPE        CLUSTER-IP    EXTERNAL-IP   PORT(S)   AGE
service/kubernetes   ClusterIP   10.244.64.1   <none>        443/TCP   4h36m
2.7.2 Create a namespace app

kubectl create ns app

[[email protected] ~]# kubectl create ns app
namespace/app created
[[email protected] ~]# kubectl get ns
NAME                   STATUS   AGE
app                    Active   3s
default                Active   4h37m
ingress-controller     Active   4h34m
kube-node-lease        Active   4h37m
kube-public            Active   4h37m
kube-system            Active   4h37m
kubernetes-dashboard   Active   4h33m
2.7.3 Delete namespace app

kubectl delete ns app

[[email protected] ~]# kubectl delete ns app
namespace "app" deleted
[[email protected] ~]# kubectl get ns
NAME                   STATUS   AGE
default                Active   4h37m
ingress-controller     Active   4h35m
kube-node-lease        Active   4h37m
kube-public            Active   4h37m
kube-system            Active   4h37m
kubernetes-dashboard   Active   4h33m

2.8 deployment/pod operation

2.8.1 In namespace kube-public Create replica controller (deployment) To start up Pod(nginx-test)

kubectl create deployment nginx-test --image=nginx -n kube-public

[[email protected] ~]# kubectl get pod -n kube-public
No resources found in kube-public namespace.
[[email protected] ~]# kubectl create deployment nginx-test --image=nginx -n kube-public 
deployment.apps/nginx-test created
[[email protected] ~]# kubectl get deploy -n kube-public
NAME         READY   UP-TO-DATE   AVAILABLE   AGE
nginx-test   0/1     1            0           23s
[[email protected] ~]# kubectl get deploy -n kube-public
NAME         READY   UP-TO-DATE   AVAILABLE   AGE
nginx-test   1/1     1            1           2m24s
[[email protected] ~]# kubectl get pod -n kube-public
NAME                          READY   STATUS    RESTARTS   AGE
nginx-test-795d659f45-n4nks   1/1     Running   0          2m58s
2.8.2 Describe the details of a resource

kubectl describe deployment nginx-test -n kube-public

[[email protected] ~]# kubectl describe deployment nginx-test -n kube-public 
Name:                   nginx-test
Namespace:              kube-public
CreationTimestamp:      Thu, 16 Dec 2021 20:35:23 +0800
Labels:                 app=nginx-test
Annotations:            deployment.kubernetes.io/revision: 1
Selector:               app=nginx-test
Replicas:               1 desired | 1 updated | 1 total | 1 available | 0 unavailable
StrategyType:           RollingUpdate
MinReadySeconds:        0
RollingUpdateStrategy:  25% max unavailable, 25% max surge
Pod Template:
  Labels:  app=nginx-test
  Containers:
   nginx:
    Image:        nginx
    Port:         <none>
    Host Port:    <none>
    Environment:  <none>
    Mounts:       <none>
  Volumes:        <none>
Conditions:
  Type           Status  Reason
  ----           ------  ------
  Available      True    MinimumReplicasAvailable
  Progressing    True    NewReplicaSetAvailable
OldReplicaSets:  <none>
NewReplicaSet:   nginx-test-795d659f45 (1/1 replicas created)
Events:
  Type    Reason             Age    From                   Message
  ----    ------             ----   ----                   -------
  Normal  ScalingReplicaSet  4m26s  deployment-controller  Scaled up replica set nginx-test-795d659f45 to 1

kubectl describe pod nginx-test -n kube-public

[[email protected] ~]# kubectl describe pod nginx-test -n kube-public
......
2.8.3 View namespace kube-public in pod Information

kubectl get pods -n kube-public

[[email protected] ~]# kubectl get pod -n kube-public 
NAME                          READY   STATUS    RESTARTS   AGE
nginx-test-795d659f45-n4nks   1/1     Running   0          6m4s
2.8.4 Login container

kubectl exec You can log in to the container across hosts ,docker exec You can only log in to the host where the container is located

[[email protected] ~]# kubectl exec -it nginx-test-795d659f45-n4nks bash -n kube-public 
kubectl exec [POD] [COMMAND] is DEPRECATED and will be removed in a future version. Use kubectl exec [POD] -- [COMMAND] instead.
[email protected]:/# ls
bin   dev		   docker-entrypoint.sh  home  lib64  mnt  proc  run   srv  tmp  var
boot  docker-entrypoint.d  etc			 lib   media  opt  root  sbin  sys  usr
2.8.5 Delete ( restart )pod resources

Due to the existence deployment/rc Replica controllers like , Delete pod Will also pull up again

[[email protected] ~]# kubectl get pod -n kube-public 
NAME                          READY   STATUS    RESTARTS   AGE
nginx-test-795d659f45-n4nks   1/1     Running   0          12m
[[email protected] ~]# kubectl delete pod nginx-test-795d659f45-n4nks -n kube-public 
pod "nginx-test-795d659f45-n4nks" deleted
[[email protected] ~]# kubectl get pod -n kube-public 
NAME                          READY   STATUS    RESTARTS   AGE
nginx-test-795d659f45-65pwr   1/1     Running   0          11s
2.8.6 If it cannot be deleted , Always in terminate state , You have to forcibly delete pod

kubectl delete pod [] -n [] --force --grace-period=0
grace-period Indicates transitional survival , Default 30s, In the delete pod Previously allowed pod Slowly terminate the container process on it , So as to exit gracefully ,0 Means immediate termination pod

[[email protected] ~]# kubectl get pod -n kube-public 
NAME                          READY   STATUS    RESTARTS   AGE
nginx-test-795d659f45-r2jwz   1/1     Running   0          13s
[[email protected] ~]# kubectl delete pod nginx-test-795d659f45-r2jwz -n kube-public --force --grace-period=0
warning: Immediate deletion does not wait for confirmation that the running resource has been terminated. The resource may continue to run on the cluster indefinitely.
pod "nginx-test-795d659f45-r2jwz" force deleted
[[email protected] ~]# kubectl get pod -n kube-public 
NAME                          READY   STATUS              RESTARTS   AGE
nginx-test-795d659f45-6h9kj   0/1     ContainerCreating   0          9s
2.8.7 Expansion and contraction capacity
2.8.7.1 Capacity expansion

kubectl scale deployment nginx-test --replicas=3 -n kube-public

[[email protected] ~]# kubectl scale deployment nginx-test --replicas=3 -n kube-public
deployment.apps/nginx-test scaled
[[email protected] ~]# kubectl get pod -n kube-public 
NAME                          READY   STATUS              RESTARTS   AGE
nginx-test-795d659f45-6h9kj   1/1     Running             0          7m
nginx-test-795d659f45-gl6z2   0/1     ContainerCreating   0          101s
nginx-test-795d659f45-p2q9s   0/1     ContainerCreating   0          101s
2.8.7.2 Shrinkage capacity

kubectl scale deployment nginx-test --replicas=1 -n kube-public

[[email protected] ~]# kubectl scale deployment nginx-test --replicas=1 -n kube-public 
deployment.apps/nginx-test scaled
[[email protected] ~]# kubectl get pod -n kube-public 
NAME                          READY   STATUS        RESTARTS   AGE
nginx-test-795d659f45-6h9kj   1/1     Running       0          8m4s
nginx-test-795d659f45-gl6z2   0/1     Terminating   0          2m45s
nginx-test-795d659f45-p2q9s   0/1     Terminating   0          2m45s
[[email protected] ~]# kubectl get pod -n kube-public 
NAME                          READY   STATUS    RESTARTS   AGE
nginx-test-795d659f45-6h9kj   1/1     Running   0          8m19s
2.8.8 Delete replica controller

kubectl delete deployment nginx-test -n kube-public
kubectl delete deployment/nginx-test -n kube-public

[[email protected] ~]# kubectl delete deployment nginx-test -n kube-public
deployment.apps "nginx-test" deleted
[[email protected] ~]# kubectl get pod -n kube-public 
NAME                          READY   STATUS        RESTARTS   AGE
nginx-test-795d659f45-6h9kj   0/1     Terminating   0          8m46s
[[email protected] ~]# kubectl get pod -n kube-public 
No resources found in kube-public namespace.

2.9 increase / Delete label

2.9.1 increase label

kubectl label deploy nginx-test version=nginx1.14

[[email protected] ~]# kubectl get deploy --show-labels
NAME         READY   UP-TO-DATE   AVAILABLE   AGE   LABELS
nginx-test   3/3     3            3           19m   run=nginx-test
[[email protected] ~]# kubectl label deploy nginx-test version=nginx1.14
deployment.extensions/nginx-test labeled
[[email protected] ~]# kubectl get deploy --show-labels
NAME         READY   UP-TO-DATE   AVAILABLE   AGE   LABELS
nginx-test   3/3     3            3           19m   run=nginx-test,version=nginx1.14
2.9.2 Delete label

kubectl label deploy nginx-test version-

[[email protected] ~]# kubectl get deploy --show-labels
NAME         READY   UP-TO-DATE   AVAILABLE   AGE   LABELS
nginx-test   3/3     3            3           19m   run=nginx-test,version=nginx1.14
[[email protected] ~]# kubectl label deploy nginx-test version-
deployment.extensions/nginx-test labeled
[[email protected] ~]# kubectl get deploy --show-labels
NAME         READY   UP-TO-DATE   AVAILABLE   AGE   LABELS
nginx-test   3/3     3            3           20m   run=nginx-test

3. K8S Simulation project

3.1 Project life cycle

establish –> Release –> to update –> Roll back –> Delete

3.2 establish kubectl run command

● Create and run one or more container images
● Create a deployment or job To manage containers
kubectl run --help View usage help

start-up nginx example , Exposed container port 80, Set the number of copies 3
kubectl run nginx --image=nginx:1.14 --port=80 --replicas=3

[[email protected] ~]# kubectl run nginx --image=nginx:1.14 --port=80 --replicas=3
kubectl run --generator=deployment/apps.v1 is DEPRECATED and will be removed in a future version. Use kubectl run --generator=run-pod/v1 or kubectl create instead.
deployment.apps/nginx created

kubectl get pods

[[email protected] ~]# kubectl get pods
NAME                     READY   STATUS    RESTARTS   AGE
nginx-65fc77987d-cwvwl   1/1     Running   0          7s
nginx-65fc77987d-m7cnn   1/1     Running   0          7s
nginx-65fc77987d-z7hvx   1/1     Running   0          7s

kubectl get all

[[email protected] ~]# kubectl get all
NAME                         READY   STATUS    RESTARTS   AGE
pod/nginx-65fc77987d-cwvwl   1/1     Running   0          24s
pod/nginx-65fc77987d-m7cnn   1/1     Running   0          24s
pod/nginx-65fc77987d-z7hvx   1/1     Running   0          24s


NAME                 TYPE        CLUSTER-IP   EXTERNAL-IP   PORT(S)   AGE
service/kubernetes   ClusterIP   10.1.0.1     <none>        443/TCP   82s


NAME                    READY   UP-TO-DATE   AVAILABLE   AGE
deployment.apps/nginx   3/3     3            3           24s

NAME                               DESIRED   CURRENT   READY   AGE
replicaset.apps/nginx-65fc77987d   3         3         3       24s

3.3 Release kubectl expose command

● Expose the resource as new Service
kubectl expose --help View usage help

by Deployment Of nginx establish Service, And pass Service Of 80 Port to the container's 80 On port ,Service For the name of the nginx-service, The type is NodePort
kubectl expose deployment nginx --port=80 --target-port=80 --name=nginx-service --type=NodePort

[[email protected] ~]# kubectl expose deployment nginx --port=80 --target-port=80 --name=nginx-service --type=NodePort
service/nginx-service exposed
3.3.1 Service The role of

Kubernetes The reason why we need Service, On the one hand, it's because Pod Of IP Not fixed (Pod May rebuild ), On the other hand, because of a group of Pod There is always a need for load balancing between instances .
Service adopt Label Selector Implemented on a group of Pod The interview of .
For container applications ,Kubernetes Provides the basis for VIP( fictitious IP) Bridge way access Service, Again by Service Redirect to the appropriate Pod.

3.3.2 Service The type of

img
● ClusterIP: Provide a virtual environment inside the cluster IP In order to offer Pod visit (Service Default type )
● NodePort: At every Node Open a port on for external access ,Kubernetes Will be in every Node Open a port on and each Node All the ports are the same , adopt NodeIP:NodePort The way
● LoadBalancer: Access through an external load balancer , Usually deployed on cloud platforms LoadBalancer There's an extra cost .

3.3.3 see Pod Network status details and Service Exposed ports

kubectl get pods,svc -o wide

[[email protected] ~]# kubectl get pods,svc -o wide
NAME                         READY   STATUS    RESTARTS   AGE   IP            NODE     NOMINATED NODE   READINESS GATES
pod/nginx-65fc77987d-cwvwl   1/1     Running   0          61s   10.244.1.25   node01   <none>           <none>
pod/nginx-65fc77987d-m7cnn   1/1     Running   0          61s   10.244.1.24   node01   <none>           <none>
pod/nginx-65fc77987d-z7hvx   1/1     Running   0          61s   10.244.2.15   node02   <none>           <none>

NAME                    TYPE        CLUSTER-IP     EXTERNAL-IP   PORT(S)        AGE    SELECTOR
service/kubernetes      ClusterIP   10.1.0.1       <none>        443/TCP        119s   <none>
service/nginx-service   NodePort    10.1.155.154   <none>        80:32107/TCP   15s    run=nginx
3.3.4 View the nodes associated with the backend

kubectl get endpoints

[[email protected] ~]# kubectl get endpoints
NAME            ENDPOINTS                                      AGE
kubernetes      192.168.122.10:6443                            15m
nginx-service   10.244.1.24:80,10.244.1.25:80,10.244.2.15:80   13m
3.3.5 see service Description information of

kubectl describe svc nginx

[[email protected] ~]# kubectl describe svc nginx
Name:                     nginx-service
Namespace:                default
Labels:                   run=nginx
Annotations:              <none>
Selector:                 run=nginx
Type:                     NodePort
IP:                       10.1.155.154
Port:                     <unset>  80/TCP
TargetPort:               80/TCP
NodePort:                 <unset>  32107/TCP
Endpoints:                10.244.1.24:80,10.244.1.25:80,10.244.2.15:80
Session Affinity:         None
External Traffic Policy:  Cluster
Events:                   <none>
3.3.6 Check the load balancing port

stay node01 Operation on node

[[email protected] ~]# yum install -y ipvsadm
[[email protected] ~]# ipvsadm -Ln
IP Virtual Server version 1.2.1 (size=4096)
Prot LocalAddress:Port Scheduler Flags
  -> RemoteAddress:Port           Forward Weight ActiveConn InActConn
......      
TCP  192.168.122.11:32107 rr
# Externally accessed IP And port 
  -> 10.244.1.24:80               Masq    1      0          0         
  -> 10.244.1.25:80               Masq    1      0          0         
  -> 10.244.2.15:80               Masq    1      0          0         
......        
TCP  10.1.155.154:80 rr
#pod Access within the cluster group IP And port 
  -> 10.244.1.24:80               Masq    1      0          0         
  -> 10.244.1.25:80               Masq    1      0          0         
  -> 10.244.2.15:80               Masq    1      0          0                
......     

stay node02 Operation on node

[[email protected] ~]# yum install -y ipvsadm
[[email protected] ~]# ipvsadm -Ln
IP Virtual Server version 1.2.1 (size=4096)
Prot LocalAddress:Port Scheduler Flags
  -> RemoteAddress:Port           Forward Weight ActiveConn InActConn
......
TCP  192.168.122.12:32107 rr
# Externally accessed IP And port 
  -> 10.244.1.24:80               Masq    1      0          0         
  -> 10.244.1.25:80               Masq    1      0          0         
  -> 10.244.2.15:80               Masq    1      0          0         
......
TCP  10.1.155.154:80 rr
#pod Access within the cluster group IP And port 
  -> 10.244.1.24:80               Masq    1      0          0         
  -> 10.244.1.25:80               Masq    1      0          0         
  -> 10.244.2.15:80               Masq    1      0          0         
......
3.3.7 Visit to view

curl 10.1.155.154

[[email protected] ~]# curl 10.1.155.154
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
<style>
    body {
    
        width: 35em;
        margin: 0 auto;
        font-family: Tahoma, Verdana, Arial, sans-serif;
    }
</style>
</head>
<body>
<h1>Welcome to nginx!</h1>
<p>If you see this page, the nginx web server is successfully installed and
working. Further configuration is required.</p>

<p>For online documentation and support please refer to
<a href="http://nginx.org/">nginx.org</a>.<br/>
Commercial support is available at
<a href="http://nginx.com/">nginx.com</a>.</p>

<p><em>Thank you for using nginx.</em></p>
</body>
</html>

curl 192.168.122.11:32107

[[email protected] ~]# curl 192.168.122.11:32107
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
<style>
    body {
    
        width: 35em;
        margin: 0 auto;
        font-family: Tahoma, Verdana, Arial, sans-serif;
    }
</style>
</head>
<body>
<h1>Welcome to nginx!</h1>
<p>If you see this page, the nginx web server is successfully installed and
working. Further configuration is required.</p>

<p>For online documentation and support please refer to
<a href="http://nginx.org/">nginx.org</a>.<br/>
Commercial support is available at
<a href="http://nginx.com/">nginx.com</a>.</p>

<p><em>Thank you for using nginx.</em></p>
</body>
</html>
3.3.8 View the access log
[[email protected] ~]# kubectl logs nginx-65fc77987d-cwvwl
10.244.0.0 - - [02/Nov/2021:12:58:38 +0000] "GET / HTTP/1.1" 200 612 "-" "curl/7.29.0" "-"
[[email protected] ~]# kubectl logs nginx-65fc77987d-m7cnn
10.244.1.1 - - [02/Nov/2021:13:00:06 +0000] "GET / HTTP/1.1" 200 612 "-" "curl/7.29.0" "-"
[[email protected] ~]# kubectl logs nginx-65fc77987d-z7hvx
10.244.2.1 - - [02/Nov/2021:13:00:10 +0000] "GET / HTTP/1.1" 200 612 "-" "curl/7.29.0" "-"

3.4 to update kubectl set

● Change some information about existing application resources .
kubectl set --help View usage help

3.4.1 Get modify template

kubectl set image --help obtain

[[email protected] ~]# kubectl set image --help
......
Examples:
  # Set a deployment's nginx container image to 'nginx:1.9.1', and its busybox container image to 'busybox'.
  kubectl set image deployment/nginx busybox=busybox nginx=nginx:1.9.1
......
3.4.2 View the current nginx Version number of
[[email protected] ~]# curl -I 192.168.122.11:32107
# Check the version number through the message header 
HTTP/1.1 200 OK
Server: nginx/1.14.2
#nginx The version number is 1.14.2
Date: Tue, 02 Nov 2021 13:10:49 GMT
Content-Type: text/html
Content-Length: 612
Last-Modified: Tue, 04 Dec 2018 14:44:49 GMT
Connection: keep-alive
ETag: "5c0692e1-264"
Accept-Ranges: bytes
3.4.3 take nginx Version updated to 1.15

kubectl set image deployment/nginx nginx=nginx:1.15

[[email protected] ~]# kubectl set image deployment/nginx nginx=nginx:1.15
deployment.extensions/nginx image updated
3.4.4 monitor pod state

In dynamic listening pod state , Because the rolling update method is used , So Mr. will become a new pod, Then delete an old pod, And so on
kubectl get pods -w

[[email protected] ~]# kubectl get pods -w
NAME                     READY   STATUS              RESTARTS   AGE
nginx-65fc77987d-cwvwl   1/1     Running             0          62m
nginx-65fc77987d-m7cnn   1/1     Running             0          62m
nginx-65fc77987d-z7hvx   1/1     Running             0          62m
nginx-6cbd4b987c-65qtx   0/1     ContainerCreating   0          23s
# New first pod
nginx-6cbd4b987c-65qtx   1/1     Running             0          24s
nginx-65fc77987d-cwvwl   1/1     Terminating         0          63m
# The first new pod After operation , Delete an old pod
nginx-6cbd4b987c-27qz7   0/1     Pending             0          0s
nginx-6cbd4b987c-27qz7   0/1     Pending             0          0s
nginx-6cbd4b987c-27qz7   0/1     ContainerCreating   0          0s
# Create a second pod
nginx-65fc77987d-cwvwl   0/1     Terminating         0          63m
nginx-65fc77987d-cwvwl   0/1     Terminating         0          63m
nginx-65fc77987d-cwvwl   0/1     Terminating         0          63m
nginx-6cbd4b987c-27qz7   1/1     Running             0          8s
nginx-65fc77987d-m7cnn   1/1     Terminating         0          63m
# Second new pod After operation , Delete the second old pod
nginx-6cbd4b987c-m467f   0/1     Pending             0          0s
nginx-6cbd4b987c-m467f   0/1     Pending             0          0s
nginx-6cbd4b987c-m467f   0/1     ContainerCreating   0          0s
# Create a third pod
nginx-65fc77987d-m7cnn   0/1     Terminating         0          63m
nginx-6cbd4b987c-m467f   1/1     Running             0          2s
nginx-65fc77987d-z7hvx   1/1     Terminating         0          63m
# The third new pod After operation , Delete the third old pod
nginx-65fc77987d-z7hvx   0/1     Terminating         0          63m
nginx-65fc77987d-m7cnn   0/1     Terminating         0          63m
nginx-65fc77987d-m7cnn   0/1     Terminating         0          63m
nginx-65fc77987d-z7hvx   0/1     Terminating         0          63m
nginx-65fc77987d-z7hvx   0/1     Terminating         0          63m

Update rules can be accessed through “kubetl describe deployment nginx” Of “RollingUpdateStrategy” see , Default configuration is “25% max unavailable, 25% max surge”, Namely, in accordance with the 25% Scroll through the proportion of .

3.4.5 see pod Of ip change

kubectl get pod -o wide

[[email protected] ~]# kubectl get pod -o wide
NAME                     READY   STATUS    RESTARTS   AGE     IP            NODE     NOMINATED NODE   READINESS GATES
nginx-6cbd4b987c-27qz7   1/1     Running   0          6m19s   10.244.2.16   node02   <none>           <none>
nginx-6cbd4b987c-65qtx   1/1     Running   0          6m43s   10.244.1.26   node01   <none>           <none>
nginx-6cbd4b987c-m467f   1/1     Running   0          6m11s   10.244.1.27   node01   <none>           <none>

pod After the update ,ip change

3.4.6 Review nginx Version number
[[email protected] ~]# curl -I 192.168.122.11:32107
HTTP/1.1 200 OK
Server: nginx/1.15.12
#nginx Version updated to 1.15.12
Date: Tue, 02 Nov 2021 13:22:29 GMT
Content-Type: text/html
Content-Length: 612
Last-Modified: Tue, 16 Apr 2019 13:08:19 GMT
Connection: keep-alive
ETag: "5cb5d3c3-264"
Accept-Ranges: bytes

3.5 Roll back kubectl rollout

● Rollback management of resources
kubectl rollout --help View usage help

3.5.1 View historical version

kubectl rollout history deployment/nginx

[[email protected] ~]# kubectl rollout history deployment/nginx
deployment.extensions/nginx 
REVISION  CHANGE-CAUSE
1         <none>
2         <none>
3.5.2 Execute rollback to the previous version

kubectl rollout undo deployment/nginx

[[email protected] ~]# kubectl rollout undo deployment/nginx
deployment.extensions/nginx rolled back

see pod Of ip change

[[email protected] ~]# kubectl get pods -o wide
NAME                     READY   STATUS    RESTARTS   AGE   IP            NODE     NOMINATED NODE   READINESS GATES
# After rollback ip Change again 
nginx-65fc77987d-2525z   1/1     Running   0          42s   10.244.2.17   node02   <none>           <none>
nginx-65fc77987d-9qkzp   1/1     Running   0          40s   10.244.2.18   node02   <none>           <none>
nginx-65fc77987d-qg75q   1/1     Running   0          41s   10.244.1.28   node01   <none>           <none>

View the current nginx edition

[[email protected] ~]# curl -I 192.168.122.11:32107
HTTP/1.1 200 OK
Server: nginx/1.14.2
#nginx The version goes back to 1.14.2
Date: Tue, 02 Nov 2021 13:31:35 GMT
Content-Type: text/html
Content-Length: 612
Last-Modified: Tue, 04 Dec 2018 14:44:49 GMT
Connection: keep-alive
ETag: "5c0692e1-264"
Accept-Ranges: bytes
3.5.3 Execute rollback to the specified version

View historical version

[[email protected] ~]# kubectl rollout history deployment/nginx
deployment.extensions/nginx 
REVISION  CHANGE-CAUSE
2         <none>
3         <none>

go back to revison2, namely 1.15 edition
kubectl rollout undo deployment/nginx --to-revision=2

[[email protected] ~]# kubectl rollout undo deployment/nginx --to-revision=2
deployment.extensions/nginx rolled back

see pod Of ip change

[[email protected] ~]# kubectl get pods -o wide
NAME                     READY   STATUS    RESTARTS   AGE   IP            NODE     NOMINATED NODE   READINESS GATES
# After rollback ip Change again 
nginx-6cbd4b987c-mhqbc   1/1     Running   0          37s   10.244.1.29   node01   <none>           <none>
nginx-6cbd4b987c-tf462   1/1     Running   0          36s   10.244.2.19   node02   <none>           <none>
nginx-6cbd4b987c-z86d6   1/1     Running   0          35s   10.244.1.30   node01   <none>           <none>

View the current nginx edition

[[email protected] ~]# curl -I 192.168.122.11:32107
HTTP/1.1 200 OK
Server: nginx/1.15.12
#nginx The version goes back to 1.15.12
Date: Tue, 02 Nov 2021 13:36:42 GMT
Content-Type: text/html
Content-Length: 612
Last-Modified: Tue, 16 Apr 2019 13:08:19 GMT
Connection: keep-alive
ETag: "5cb5d3c3-264"
Accept-Ranges: bytes
3.5.4 Check the rollback status

kubectl rollout status deployment/nginx

[[email protected] ~]# kubectl rollout status deployment/nginx
deployment "nginx" successfully rolled out

3.6 Delete kubectl delete

3.6.1 Delete replica controller

kubectl delete deployment/nginx

[[email protected] ~]# kubectl get deploy
NAME    READY   UP-TO-DATE   AVAILABLE   AGE
nginx   3/3     3            3           88m
[[email protected] ~]# kubectl delete deployment/nginx
deployment.extensions "nginx" deleted
[[email protected] ~]# kubectl get deploy
No resources found.
3.6.2 Delete service

kubectl delete svc/nginx-service

[[email protected] ~]# kubectl get svc
NAME            TYPE        CLUSTER-IP     EXTERNAL-IP   PORT(S)        AGE
kubernetes      ClusterIP   10.1.0.1       <none>        443/TCP        91m
nginx-service   NodePort    10.1.155.154   <none>        80:32107/TCP   89m
[[email protected] ~]# kubectl delete svc/nginx-service
service "nginx-service" deleted
[[email protected] ~]# kubectl get svc
NAME         TYPE        CLUSTER-IP   EXTERNAL-IP   PORT(S)   AGE
kubernetes   ClusterIP   10.1.0.1     <none>        443/TCP   91m
[[email protected] ~]# kubectl get all


NAME                 TYPE        CLUSTER-IP   EXTERNAL-IP   PORT(S)   AGE
service/kubernetes   ClusterIP   10.1.0.1     <none>        443/TCP   92m

4. Release of canary / Grayscale Publishing (Canary Release)

4.1 Canary release profile

Deployment The controller supports custom control of the rolling rhythm in the update process , Such as “ Pause (pause)” or “ continue (resume)” update operation . For example, waiting for the first batch of new Pod Pause the update process as soon as the resource is created , here , There are only a few new versions of the app , The main part is still the old version . then , After filtering, a small number of user requests are routed to the new version of Pod application , Continue to see if you can run steadily in the way you want . Make sure there's no problem before continuing with the rest Pod Resources rolling update , Otherwise, roll back the update immediately . This is the so-called Canary release .

4.2 to update deployment Version of , And configure pause deployment

4.2.1 establish pods

kubectl run nginx-test --image=nginx:1.14 --replicas=3

[[email protected] ~]# kubectl run nginx-test --image=nginx:1.14 --replicas=3
kubectl run --generator=deployment/apps.v1 is DEPRECATED and will be removed in a future version. Use kubectl run --generator=run-pod/v1 or kubectl create instead.
deployment.apps/nginx-test created
[[email protected] ~]# kubectl get pods,deploy -o wide
NAME                              READY   STATUS    RESTARTS   AGE   IP            NODE     NOMINATED NODE   READINESS GATES
pod/nginx-test-6cc7cd5547-4xqcb   1/1     Running   0          51s   10.244.2.23   node02   <none>           <none>
pod/nginx-test-6cc7cd5547-gcbh5   1/1     Running   0          51s   10.244.1.37   node01   <none>           <none>
pod/nginx-test-6cc7cd5547-nw6k6   1/1     Running   0          51s   10.244.1.38   node01   <none>           <none>

NAME                               READY   UP-TO-DATE   AVAILABLE   AGE   CONTAINERS   IMAGES       SELECTOR
deployment.extensions/nginx-test   3/3     3            3           51s   nginx-test   nginx:1.14   run=nginx-test
4.2.2 Publishing services

kubectl expose deploy nginx-test --port=80 --target-port=80 --name=nginx-service --type=NodePort

[[email protected] ~]# kubectl expose deploy nginx-test --port=80 --target-port=80 --name=nginx-service --type=NodePort
service/nginx-service exposed
[[email protected] ~]# kubectl get svc -o wide
NAME            TYPE        CLUSTER-IP    EXTERNAL-IP   PORT(S)        AGE   SELECTOR
kubernetes      ClusterIP   10.1.0.1      <none>        443/TCP        23h   <none>
nginx-service   NodePort    10.1.36.134   <none>        80:30191/TCP   9s    run=nginx-test
4.2.3 see nginx edition
[[email protected] ~]# curl -I 192.168.122.11:30191
HTTP/1.1 200 OK
Server: nginx/1.14.2
# The version number is 1.14.2
Date: Wed, 03 Nov 2021 11:54:11 GMT
Content-Type: text/html
Content-Length: 612
Last-Modified: Tue, 04 Dec 2018 14:44:49 GMT
Connection: keep-alive
ETag: "5c0692e1-264"
Accept-Ranges: bytes
4.2.4 Define the version CHANGE-CAUSE
4.2.4.1 View historical version

Not defined in CHANGE-CAUSE Under the circumstances , The default value is , When there are many historical versions , It is not convenient for us to identify the version number when rolling back . therefore , Suggested definition CHANGE-CAUSE Provide a service version to help us identify the current service .
kubectl rollout history deploy/nginx-test

[[email protected] ~]# kubectl rollout history deploy/nginx-test
deployment.extensions/nginx-test 
REVISION  CHANGE-CAUSE
1         <none>
4.2.4.2 Define the version CHANGE-CAUSE

It is generally defined by modifying the configuration change-cause

[[email protected] ~]# kubectl edit deploy/nginx-test

......
kind: Deployment
metadata:
  annotations:
# The following line can define the historical version revision
    deployment.kubernetes.io/revision: "1"
# stay Deployment Of matadata Under annotations Middle and lower line definitions change-cause
    kubernetes.io/change-cause: "nginx1.14"
......
4.2.4.3 Check the historical version again
[[email protected] ~]# kubectl rollout history deploy/nginx-test
deployment.extensions/nginx-test 
REVISION  CHANGE-CAUSE
1         nginx1.14
4.2.5 to update nginx Version is 1.15 And configure pause

kubectl set image deploy/nginx-test nginx-test=nginx:1.15 && kubectl rollout pause deploy/nginx-test

[[email protected] ~]# kubectl set image deploy/nginx-test nginx-test=nginx:1.15 && kubectl rollout pause deploy/nginx-test
deployment.extensions/nginx-test image updated
deployment.extensions/nginx-test paused
4.2.6 Observe the update status

kubectl rollout status deploy/nginx-test

[[email protected] ~]# kubectl rollout status deploy/nginx-test
Waiting for deployment "nginx-test" rollout to finish: 1 out of 3 new replicas have been updated...
4.2.7 Monitor the update process

You can see that a new one has been added pod, However, an old resource is not deleted as expected , Because of the use of pause Suspend order
kubectl get pods -w

[[email protected] ~]# kubectl get pod -o wide
NAME                          READY   STATUS    RESTARTS   AGE     IP            NODE     NOMINATED NODE   READINESS GATES
nginx-test-679dcbd68d-zw8w5   1/1     Running   0          8m28s   10.244.2.24   node02   <none>           <none>
nginx-test-6cc7cd5547-4xqcb   1/1     Running   0          48m     10.244.2.23   node02   <none>           <none>
nginx-test-6cc7cd5547-gcbh5   1/1     Running   0          48m     10.244.1.37   node01   <none>           <none>
nginx-test-6cc7cd5547-nw6k6   1/1     Running   0          48m     10.244.1.38   node01   <none>           <none>
4.2.8 see nginx edition

kubectl get pod -o wide

[[email protected] ~]# kubectl get pod -o wide
NAME                          READY   STATUS    RESTARTS   AGE     IP            NODE     NOMINATED NODE   READINESS GATES
nginx-test-679dcbd68d-zw8w5   1/1     Running   0          8m28s   10.244.2.24   node02   <none>           <none>
nginx-test-6cc7cd5547-4xqcb   1/1     Running   0          48m     10.244.2.23   node02   <none>           <none>
nginx-test-6cc7cd5547-gcbh5   1/1     Running   0          48m     10.244.1.37   node01   <none>           <none>
nginx-test-6cc7cd5547-nw6k6   1/1     Running   0          48m     10.244.1.38   node01   <none>           <none>

see nginx edition

[[email protected] ~]# curl -I 192.168.122.12:30191
HTTP/1.1 200 OK
Server: nginx/1.14.2
Date: Wed, 03 Nov 2021 12:45:37 GMT
Content-Type: text/html
Content-Length: 612
Last-Modified: Tue, 04 Dec 2018 14:44:49 GMT
Connection: keep-alive
ETag: "5c0692e1-264"
Accept-Ranges: bytes

[[email protected] ~]# curl -I 192.168.122.12:30191
HTTP/1.1 200 OK
Server: nginx/1.14.2
Date: Wed, 03 Nov 2021 12:46:59 GMT
Content-Type: text/html
Content-Length: 612
Last-Modified: Tue, 04 Dec 2018 14:44:49 GMT
Connection: keep-alive
ETag: "5c0692e1-264"
Accept-Ranges: bytes

[[email protected] ~]# curl -I 192.168.122.12:30191
HTTP/1.1 200 OK
Server: nginx/1.14.2
Date: Wed, 03 Nov 2021 12:47:09 GMT
Content-Type: text/html
Content-Length: 612
Last-Modified: Tue, 04 Dec 2018 14:44:49 GMT
Connection: keep-alive
ETag: "5c0692e1-264"
Accept-Ranges: bytes

[[email protected] ~]# curl -I 192.168.122.12:30191
HTTP/1.1 200 OK
Server: nginx/1.15.12
# new pod by 1.15
Date: Wed, 03 Nov 2021 12:47:12 GMT
Content-Type: text/html
Content-Length: 612
Last-Modified: Tue, 16 Apr 2019 13:08:19 GMT
Connection: keep-alive
ETag: "5cb5d3c3-264"
Accept-Ranges: bytes
4.2.9 View and update historical versions change-cause

kubectl rollout history deploy/nginx-test

[[email protected] ~]# kubectl rollout history deploy/nginx-test
deployment.extensions/nginx-test 
REVISION  CHANGE-CAUSE
1         nginx1.14
2         nginx1.14

kubectl edit deploy/nginx-test

[[email protected] ~]# kubectl edit deploy/nginx-test

kind: Deployment
metadata:
  annotations:
# Down revison Automatically update to 2
    deployment.kubernetes.io/revision: "2"
# Modify downlink change-cause by nginx1.15
    kubernetes.io/change-cause: nginx1.15

kubectl rollout history deploy/nginx-test

[[email protected] ~]# kubectl rollout history deploy/nginx-test
deployment.extensions/nginx-test 
REVISION  CHANGE-CAUSE
1         nginx1.14
2         nginx1.15
4.2.10 resume Continue to update

No problem testing the new version, continue to update
kubectl rollout resume deploy/nginx-test

[[email protected] ~]# kubectl rollout resume deploy/nginx-test
deployment.extensions/nginx-test resumed
4.2.11 Check the last update
[[email protected] ~]# kubectl get pods -w
NAME                          READY   STATUS    RESTARTS   AGE
nginx-test-679dcbd68d-zw8w5   1/1     Running   0          61s
nginx-test-6cc7cd5547-4xqcb   1/1     Running   0          41m
nginx-test-6cc7cd5547-gcbh5   1/1     Running   0          41m
nginx-test-6cc7cd5547-nw6k6   1/1     Running   0          41m
nginx-test-6cc7cd5547-gcbh5   1/1     Terminating   0          63m
nginx-test-679dcbd68d-cljzh   0/1     Pending       0          0s
nginx-test-679dcbd68d-cljzh   0/1     Pending       0          0s
nginx-test-679dcbd68d-cljzh   0/1     ContainerCreating   0          0s
nginx-test-6cc7cd5547-gcbh5   0/1     Terminating         0          63m
nginx-test-6cc7cd5547-gcbh5   0/1     Terminating         0          63m
nginx-test-6cc7cd5547-gcbh5   0/1     Terminating         0          63m
nginx-test-679dcbd68d-cljzh   1/1     Running             0          1s
nginx-test-6cc7cd5547-nw6k6   1/1     Terminating         0          63m
nginx-test-679dcbd68d-s2gck   0/1     Pending             0          0s
nginx-test-679dcbd68d-s2gck   0/1     Pending             0          0s
nginx-test-679dcbd68d-s2gck   0/1     ContainerCreating   0          0s
nginx-test-679dcbd68d-s2gck   1/1     Running             0          1s
nginx-test-6cc7cd5547-4xqcb   1/1     Terminating         0          63m
nginx-test-6cc7cd5547-nw6k6   0/1     Terminating         0          63m
nginx-test-6cc7cd5547-4xqcb   0/1     Terminating         0          63m
nginx-test-6cc7cd5547-nw6k6   0/1     Terminating         0          63m
nginx-test-6cc7cd5547-nw6k6   0/1     Terminating         0          63m
nginx-test-6cc7cd5547-4xqcb   0/1     Terminating         0          63m
nginx-test-6cc7cd5547-4xqcb   0/1     Terminating         0          63m

Two 、 Declarative management

1. Declarative Management

  1. It is suitable for modifying resources
  2. The declarative resource management method relies on the resource configuration file to manage resources
    The resource configuration manifest file has two formats :yaml( Hommization , Easy to read ),json( Easy to api Interface analysis )
  3. In the concept of resources , It is defined in the same resource configuration list through implementation , Then apply the declarative command to k8s In cluster
  4. Grammar format :kubectl create/apply/delete -f -o yaml

2. View the resource configuration list

kubectl get deploy/nginx-test -o yaml

[[email protected] ~]# kubectl get deploy/nginx-test -o yaml
apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  annotations:
    deployment.kubernetes.io/revision: "3"
    kubernetes.io/change-cause: nginx1.14
  creationTimestamp: "2021-11-03T11:47:56Z"
  generation: 7
  labels:
    run: nginx-test
  name: nginx-test
  namespace: default
  resourceVersion: "105895"
  selfLink: /apis/extensions/v1beta1/namespaces/default/deployments/nginx-test
  uid: 634d471e-3907-4717-a02e-f5cce101d2f4
spec:
  progressDeadlineSeconds: 600
  replicas: 3
  revisionHistoryLimit: 10
  selector:
    matchLabels:
      run: nginx-test
  strategy:
    rollingUpdate:
      maxSurge: 25%
      maxUnavailable: 25%
    type: RollingUpdate
  template:
    metadata:
      creationTimestamp: null
      labels:
        run: nginx-test
    spec:
      containers:
      - image: nginx:1.14
        imagePullPolicy: IfNotPresent
        name: nginx-test
        resources: {
    }
        terminationMessagePath: /dev/termination-log
        terminationMessagePolicy: File
      dnsPolicy: ClusterFirst
      restartPolicy: Always
      schedulerName: default-scheduler
      securityContext: {
    }
      terminationGracePeriodSeconds: 30
status:
  availableReplicas: 3
  conditions:
  - lastTransitionTime: "2021-11-03T11:47:58Z"
    lastUpdateTime: "2021-11-03T11:47:58Z"
    message: Deployment has minimum availability.
    reason: MinimumReplicasAvailable
    status: "True"
    type: Available
  - lastTransitionTime: "2021-11-03T12:50:56Z"
    lastUpdateTime: "2021-11-03T12:57:35Z"
    message: ReplicaSet "nginx-test-6cc7cd5547" has successfully progressed.
    reason: NewReplicaSetAvailable
    status: "True"
    type: Progressing
  observedGeneration: 7
  readyReplicas: 3
  replicas: 3
  updatedReplicas: 3

kubectl get service nginx-service -o yaml

[[email protected] ~]# kubectl get service nginx-service -o yaml
apiVersion: v1
kind: Service
metadata:
  creationTimestamp: "2021-11-03T11:52:40Z"
  labels:
    run: nginx-test
  name: nginx-service
  namespace: default
  resourceVersion: "100051"
  selfLink: /api/v1/namespaces/default/services/nginx-service
  uid: b2ec9834-864a-4146-9296-5420ac15451d
spec:
  clusterIP: 10.1.36.134
  externalTrafficPolicy: Cluster
  ports:
  - nodePort: 30191
    port: 80
    protocol: TCP
    targetPort: 80
  selector:
    run: nginx-test
  sessionAffinity: None
  type: NodePort
status:
  loadBalancer: {
    }

3. Explain the resource allocation list

kubectl explain deployment.metadata

[[email protected] ~]# kubectl explain deployment.metadata
KIND:     Deployment
VERSION:  extensions/v1beta1

RESOURCE: metadata <Object>

DESCRIPTION:
     Standard object metadata.

     ObjectMeta is metadata that all persisted resources must have, which
     includes all objects users must create.

FIELDS:
   annotations	<map[string]string>
     Annotations is an unstructured key value map stored with a resource that
     may be set by external tools to store and retrieve arbitrary metadata. They
     are not queryable and should be preserved when modifying objects. More
     info: http://kubernetes.io/docs/user-guide/annotations
......

kubectl explain service.metadata

[[email protected] ~]# kubectl explain service.metadata
KIND:     Service
VERSION:  v1

RESOURCE: metadata <Object>

DESCRIPTION:
     Standard object's metadata. More info:
     https://git.k8s.io/community/contributors/devel/api-conventions.md#metadata

     ObjectMeta is metadata that all persisted resources must have, which
     includes all objects users must create.

FIELDS:
   annotations	<map[string]string>
     Annotations is an unstructured key value map stored with a resource that
     may be set by external tools to store and retrieve arbitrary metadata. They
     are not queryable and should be preserved when modifying objects. More
     info: http://kubernetes.io/docs/user-guide/annotations
......

4. Modify the resource configuration list and apply

4.1 Offline modification

modify yaml file : And use kubectl apply -f xxxx.yaml Document to make it effective
Be careful : When apply When you don't come into effect , First use delete Clear resources , Again apply Create resources
kubectl get service nginx-service -o yaml > nginx-svc.yaml

[[email protected] ~]# kubectl get service nginx-service -o yaml > nginx-svc.yaml
[[email protected] ~]# vim nginx-svc.yaml 

apiVersion: v1
kind: Service
metadata:
  creationTimestamp: "2021-11-03T11:52:40Z"
  labels:
    run: nginx-test
  name: nginx-service
  namespace: default
  resourceVersion: "100051"
  selfLink: /api/v1/namespaces/default/services/nginx-service
  uid: b2ec9834-864a-4146-9296-5420ac15451d
spec:
  clusterIP: 10.1.36.134
  externalTrafficPolicy: Cluster
  ports:
  - nodePort: 30191
# modify port by 80
    port: 8080
    protocol: TCP
    targetPort: 80
  selector:
    run: nginx-test
  sessionAffinity: None
  type: NodePort
status:
  loadBalancer: {
    }

Delete resources
kubectl delete -f nginx-svc.yaml

[[email protected] ~]# kubectl delete -f nginx-svc.yaml
service "nginx-service" deleted

New resources
kubectl apply -f nginx-svc.yaml

[[email protected] ~]# kubectl apply -f nginx-svc.yaml
service/nginx-service created

see service resources
kubectl get svc

[[email protected] ~]# kubectl get svc
NAME            TYPE        CLUSTER-IP    EXTERNAL-IP   PORT(S)          AGE
kubernetes      ClusterIP   10.1.0.1      <none>        443/TCP          25h
nginx-service   NodePort    10.1.36.134   <none>        8080:30191/TCP   56s

4.2 Modify online

Use it directly kubectl edit service nginx-service Edit the configuration resource list online and save it. Exit will take effect immediately ( Such as port: 888)
PS: This modification will not affect yaml File content modification
kubectl edit service nginx-service

[[email protected] ~]# kubectl edit service nginx-service
 
......
  ports:
  - nodePort: 30191
# modify port by 888
    port: 888
    protocol: TCP
    targetPort: 80
......

see service resources
kubectl get svc

[[email protected] ~]# kubectl get svc
NAME            TYPE        CLUSTER-IP    EXTERNAL-IP   PORT(S)         AGE
kubernetes      ClusterIP   10.1.0.1      <none>        443/TCP         25h
nginx-service   NodePort    10.1.36.134   <none>        888:30191/TCP   6m50s

5. Delete resource configuration list

5.1 Statement delete

kubectl delete service nginx-service

[[email protected] ~]# kubectl delete service nginx-service
service "nginx-service" deleted
[[email protected] ~]# kubectl get svc
NAME         TYPE        CLUSTER-IP   EXTERNAL-IP   PORT(S)   AGE
kubernetes   ClusterIP   10.1.0.1     <none>        443/TCP   25h

5.2 Declarative deletion

kubectl delete -f nginx-svc.yaml

[[email protected] ~]# kubectl apply -f nginx-svc.yaml 
service/nginx-service created
[[email protected] ~]# kubectl get svc
NAME            TYPE        CLUSTER-IP    EXTERNAL-IP   PORT(S)          AGE
kubernetes      ClusterIP   10.1.0.1      <none>        443/TCP          25h
nginx-service   NodePort    10.1.36.134   <none>        8080:30191/TCP   1s
[[email protected] ~]# kubectl delete -f nginx-svc.yaml 
service "nginx-service" deleted
[[email protected] ~]# kubectl get svc
NAME         TYPE        CLUSTER-IP   EXTERNAL-IP   PORT(S)   AGE
kubernetes   ClusterIP   10.1.0.1     <none>        443/TCP   25h

copyright notice
author[Public righteousness],Please bring the original link to reprint, thank you.
https://en.cdmana.com/2022/01/202201270829505954.html

Random recommended