1. introduction
The API Server of k8s provides a RESTful-style gateway interface that allows users to initiate requests to the k8s cluster. Such operations as creating a Pod or destroying a Pod
Users can communicate with API Server through programming language following API Server's Gateway Interface Specification. They can also communicate with API Server through the kubectl command and API Server provided by k8s, or through Web UI and API Server provided by Dashboard.
Among them, kubectl is an official CLI tool for communicating with API Server and is the most commonly used interactive command-line tool.
2. kubectl
2.1. View Command Help
# View kubectl command help [root@master ~]# kubectl --help # Basic commands (for beginners) Basic Commands (Beginner): create Create resources, k8s Support from yaml File or command line parameters directly create resources expose Exposure service run Function Pod set Setting Object Properties # Basic command Basic Commands (Intermediate): explain get Access to resource information edit Editorial resources delete Delete resources # Deployment command Deploy Commands: rollout Update management scale Manual management of copies autoscale Automated management of replicas # Cluster Management Command Cluster Management Commands: certificate Certificate management cluster-info Viewing Cluster Information top Display resources(CPU/Memory/storage)Usage situation cordon Will specify node Set to"Unavailable"(unschedulable)state uncordon Will specify node Set to"available"(schedulable)state drain Emptying node taint by node Statement Stain and Standard Behavior # Troubleshooting and debugging commands Troubleshooting and Debugging Commands: describe Display details of a particular resource or resource group logs Printing Pod Container log in attach Connect to a running container exec Execute commands in containers port-forward Forwarding one or more local ports to Pod in proxy Function k8s API Server agent cp Copy files or directories across containers auth Check authorization # Advanced command Advanced Commands: apply Based on file or stdin Applying configuration to resources patch Update resource fields with policy merge patches replace Based on file or stdin Replace a resource wait At present, it is in the testing stage., Waiting for a condition on one or more resources convert For different API Version Conversion Profile # Resource settings Settings Commands: label Update labels on resources(label) annotate Renewal of resources a nnotation completion Output specified shell Complement code # Other orders Other Commands: alpha Commands for features in alpha api-resources Print supported on the server API Resources api-versions with "group/version" Format Printing Server Supported API Version information config modify kubeconfig file plugin Run the command line plug-in version See k8s Edition # Use format Usage: kubectl [flags] [options] Use "kubectl <command> --help" for more information about a given command. Use "kubectl options" for a list of global command-line options (applies to all commands).
2.2. Running a Pod using kubectl
# Run a pod managed by the deployment manager [root@master ~]# kubectl run nginx --image=nginx:1.14-alpine --replicas=5 deployment.apps/nginx created # View pod [root@master ~]# kubectl get pod -o wide NAME READY STATUS RESTARTS AGE IP NODE nginx-65759d8bcb-96kgd 1/1 Running 0 7s 10.244.3.6 node02 nginx-65759d8bcb-97dch 1/1 Running 0 7s 10.244.1.5 node01 nginx-65759d8bcb-mzzwh 1/1 Running 0 8s 10.244.1.4 node01 nginx-65759d8bcb-vxs74 1/1 Running 0 8s 10.244.3.5 node02 nginx-65759d8bcb-z6d4r 1/1 Running 0 8s 10.244.3.4 node02 NAME Pod Name READY this Pod There should be several containers running inside/Several containers are ready STATUS running state RESTARTS Pod Restart times AGE How long has it been in existence?, Unit second(s) IP Pod IP(This address can only be used within the cluster, And Pod IP Change will happen at any time) NODE Operation node # View the deployment manager [root@master ~]# kubectl get deployment NAME DESIRED CURRENT UP-TO-DATE AVAILABLE AGE nginx 5 5 5 5 18s NAME deployment Manager name DESIRED How many copies are expected CURRENT How many copies are there currently? UP-TO-DATE Updated Pod Number AVAILABLE Active Pod Number AGE How long has it been in existence?, Unit second(s) # Accessing Pod within the cluster [root@master ~]# curl 10.244.1.5 <!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>
2.3. Exposing Services with service
Pod's clients are mainly divided into two categories: cluster client and cluster client. Clients in the cluster can access Pod directly through Pod IP, while external clients in the cluster can not access Pod IP, and Pod IP may change at any time. We should not use Pod IP directly even if we only access inside the cluster.
Service exists mainly to solve these two problems. By creating service, it gives service a fixed access interface and binds related Pod to the service. When accessing service, it automatically distributes client browsing to back-end Pod.
If k8s installs CoreDNS, it can assign a DNS to all Pod s through CoreDNS. If service changes, CoreDNS will update its internal parsing records to ensure the validity of DNS parsing records.
# Create a service [root@master ~]# kubectl expose deployment nginx --name=nginx-service --port=80 --target-port=80 --protocol=TCP --type=ClusterIP service/nginx-service exposed kubectl expose Establish service Keyword deployment nginx Bound Pod Manager(This will be exposed. Pod All managed by the manager Pod) --name Appoint service Name --port Exposed ports --target-port Target port --protocol Exposed agreements(Default is TCP) --type service type, ClusterIP Cluster IP, This type of service Not accessible outside the cluster # View existing service s [root@master ~]# kubectl get service NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE kubernetes ClusterIP 10.96.0.1 <none> 443/TCP 6d nginx-service ClusterIP 10.107.73.166 <none> 80/TCP 33s # View service details [root@master ~]# kubectl describe service nginx-service Name: nginx-service Namespace: default Labels: run=nginx Annotations: <none> # All pods with the tag run and run as nginx (through which the binding of pod and service is completed) Selector: run=nginx Type: ClusterIP IP: 10.107.73.166 Port: <unset> 80/TCP TargetPort: 80/TCP Endpoints: 10.244.1.4:80,10.244.1.5:80,10.244.3.4:80 + 2 more... Session Affinity: None Events: <none> # label showing each pod [root@master ~]# kubectl get pod --show-labels NAME READY STATUS RESTARTS AGE LABELS client 1/1 Running 0 54m run=client nginx-65759d8bcb-96kgd 1/1 Running 0 5h pod-template-hash=2131584676,run=nginx nginx-65759d8bcb-97dch 1/1 Running 0 5h pod-template-hash=2131584676,run=nginx nginx-65759d8bcb-mzzwh 1/1 Running 0 5h pod-template-hash=2131584676,run=nginx nginx-65759d8bcb-vxs74 1/1 Running 0 5h pod-template-hash=2131584676,run=nginx nginx-65759d8bcb-z6d4r 1/1 Running 0 5h pod-template-hash=2131584676,run=nginx # Accessing Pod with service ip [root@master ~]# curl 10.107.73.166 <!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>
2.4. Access Pod with DNS Name
# View the service address of kube-dns (real CoreDNS) [root@master ~]# kubectl get service -n kube-system NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE kube-dns ClusterIP 10.96.0.10 <none> 53/UDP,53/TCP 7d [root@master ~]# kubectl get service NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE kubernetes ClusterIP 10.96.0.1 <none> 443/TCP 7d nginx-service ClusterIP 10.107.73.166 <none> 80/TCP 46m # Resolve hostname using CoreDNS, nginx-service as service name, default.svc.cluster.local as DNS suffix [root@master ~]# dig -t A nginx-service.default.svc.cluster.local @10.96.0.10 ...... # Analytical results nginx-service.default.svc.cluster.local. 5 IN A 10.107.73.166 ;; Query time: 7 msec ;; SERVER: 10.96.0.10#53(10.96.0.10) ;; WHEN: Thu Feb 28 16:36:29 CST 2019 ;; MSG SIZE rcvd: 123 # Create a client Pod [root@master ~]# kubectl run client --image=busybox -it --restart=Never # Access within Pod using service name / # wget -O - -q nginx-service <!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>
2.5. Modify the number of pod replicas dynamically
# Modify the number of copies to 2 [root@master ~]# kubectl scale --replicas=2 deployment nginx deployment.extensions/nginx scaled # View the details of the nginx controller [root@master ~]# kubectl describe deployment nginx Name: nginx Namespace: default CreationTimestamp: Thu, 28 Feb 2019 12:05:59 +0800 Labels: run=nginx Annotations: deployment.kubernetes.io/revision=1 Selector: run=nginx # Copy details Replicas: 2 desired | 2 updated | 2 total | 2 available | 0 unavailable StrategyType: RollingUpdate MinReadySeconds: 0 RollingUpdateStrategy: 25% max unavailable, 25% max surge Pod Template: Labels: run=nginx Containers: nginx: Image: nginx:1.14-alpine 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-65759d8bcb (2/2 replicas created) Events: Type Reason Age From Message ---- ------ ---- ---- ------- Normal ScalingReplicaSet 1m deployment-controller Scaled down replica set nginx-65759d8bcb to 2
2.6. update
# View the details of the current Pod [root@master ~]# kubectl describe pod nginx-65759d8bcb-97dch Name: nginx-65759d8bcb-97dch Namespace: default Priority: 0 PriorityClassName: <none> Node: node01/192.168.1.51 Start Time: Thu, 28 Feb 2019 12:06:00 +0800 Labels: pod-template-hash=2131584676 run=nginx Annotations: <none> Status: Running IP: 10.244.1.5 Controlled By: ReplicaSet/nginx-65759d8bcb # Containers running in pod Containers: # Container name nginx: Container ID: docker://2a97be8c74ac715569b4cbd542cb1df0b52f49cd1ee89f1d7bdf15464678d274 # Container mirroring Image: nginx:1.14-alpine Image ID: docker-pullable://nginx@sha256:b96aeeb1687703c49096f4969358d44f8520b671da94848309a3ba5be5b4c632 Port: <none> Host Port: <none> State: Running Started: Thu, 28 Feb 2019 12:06:01 +0800 Ready: True Restart Count: 0 Environment: <none> Mounts: /var/run/secrets/kubernetes.io/serviceaccount from default-token-t9pnn (ro) # The second container running in the pod. There's only one container. Conditions: Type Status Initialized True Ready True ContainersReady True PodScheduled True Volumes: default-token-t9pnn: Type: Secret (a volume populated by a Secret) SecretName: default-token-t9pnn Optional: false QoS Class: BestEffort Node-Selectors: <none> Tolerations: node.kubernetes.io/not-ready:NoExecute for 300s node.kubernetes.io/unreachable:NoExecute for 300s Events: <none> # Update Mirror Version [root@master ~]# kubectl set image deployment nginx nginx=nginx:alpine deployment.extensions/nginx image updated kubectl set image Update keywords deployment nginx nginx deployment Controller nginx pod Name of container in(Update containers can only be specified when updating) nginx:alpine Mirror version # View the update process [root@master ~]# kubectl rollout status deployment nginx Waiting for deployment "nginx" rollout to finish: 1 out of 2 new replicas have been updated... Waiting for deployment "nginx" rollout to finish: 1 old replicas are pending termination... Waiting for deployment "nginx" rollout to finish: 1 old replicas are pending termination... deployment "nginx" successfully rolled out # View the updated pod [root@master ~]# kubectl get pod NAME READY STATUS RESTARTS AGE client 1/1 Running 0 1h nginx-5557945897-87st5 1/1 Running 0 1m nginx-5557945897-zgggq 1/1 Running 0 1m # View pod details [root@master ~]# kubectl describe pod nginx-5557945897-87st5 Name: nginx-5557945897-87st5 Namespace: default Priority: 0 PriorityClassName: <none> Node: node02/192.168.1.52 Start Time: Thu, 28 Feb 2019 17:52:21 +0800 Labels: pod-template-hash=1113501453 run=nginx Annotations: <none> Status: Running IP: 10.244.3.8 Controlled By: ReplicaSet/nginx-5557945897 Containers: nginx: Container ID: docker://fcb8166d53a6c2c6392bc14f80cd9161caf13e3e26cad433ed0d9da133b41c6b Image: nginx:alpine Image ID: docker-pullable://nginx@sha256:0f7920c93d6b60f3e13c1b847f1863f423c3149d06e53475e64560933d168adc ......
2.7. rollback
# Roll back to the specified version, default rollback to the previous version [root@master ~]# kubectl rollout undo deployment nginx deployment.extensions/nginx kubectl rollout undo Keyword deployment nginx Controller --to-revision Specify rollback to that version [root@master ~]# kubectl get pod NAME READY STATUS RESTARTS AGE client 1/1 Running 0 1h nginx-65759d8bcb-gm4sj 1/1 Running 0 1m nginx-65759d8bcb-n2222 1/1 Running 0 1m # View pod information after rollback [root@master ~]# kubectl describe deployment nginx nginx-65759d8bcb-gm4sj Name: nginx Namespace: default CreationTimestamp: Thu, 28 Feb 2019 12:05:59 +0800 Labels: run=nginx Annotations: deployment.kubernetes.io/revision=5 Selector: run=nginx Replicas: 2 desired | 2 updated | 2 total | 2 available | 0 unavailable StrategyType: RollingUpdate MinReadySeconds: 0 RollingUpdateStrategy: 25% max unavailable, 25% max surge Pod Template: Labels: run=nginx Containers: nginx: Image: nginx:1.14-alpine Port: <none> Host Port: <none> Environment: <none> Mounts: <none> Volumes: <none>
2.8. Publish services outside the cluster
# Create a new service. Service's Node Port mode allows external traffic to access the k8s cluster [root@master ~]# kubectl expose deployment nginx --name=nginx-service-internet --port=80 --type=NodePort service/nginx-service-internet exposed # nginx pod can be accessed by accessing 32081 of any k8s node externally [root@master ~]# kubectl get service NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE kubernetes ClusterIP 10.96.0.1 <none> 443/TCP 7d nginx-service ClusterIP 10.107.73.166 <none> 80/TCP 18h nginx-service-internet NodePort 10.107.217.105 <none> 80:32081/TCP 11s # Or modify the type of the existing service to publish it outside the cluster [root@master ~]# kubectl edit service nginx-service apiVersion: v1 kind: Service metadata: creationTimestamp: 2019-02-28T07:50:21Z labels: run: nginx name: nginx-service namespace: default resourceVersion: "474911" selfLink: /api/v1/namespaces/default/services/nginx-service uid: 7f7ef303-3b2d-11e9-9b82-000c292a04ff spec: clusterIP: 10.107.73.166 externalTrafficPolicy: Cluster ports: - nodePort: 31987 port: 80 protocol: TCP targetPort: 80 selector: run: nginx sessionAffinity: None # Modified to NodePort type: NodePort status: loadBalancer: {} # Now 31987 and 32081 accessing any node can access back-end pod resources [root@master ~]# kubectl get service NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE kubernetes ClusterIP 10.96.0.1 <none> 443/TCP 7d nginx-service NodePort 10.107.73.166 <none> 80:31987/TCP 18h nginx-service-internet NodePort 10.107.217.105 <none> 80:32081/TCP 3m