找回密码
 立即注册
首页 业界区 业界 Kubernetes基础教程-通过部署Nginx快速学习基本使用命令 ...

Kubernetes基础教程-通过部署Nginx快速学习基本使用命令

滑清怡 2025-6-2 00:33:29
1、验证节点信息

1.1、查看控制平面组件的状态
  1. [root@linux-servertwo software]# kubectl get cs
  2. Warning: v1 ComponentStatus is deprecated in v1.19+
  3. NAME                 STATUS    MESSAGE             ERROR
  4. controller-manager   Healthy   ok                  
  5. scheduler            Healthy   ok                  
  6. etcd-0               Healthy   {"health":"true"}  
  7. #controller-manager: 控制器管理器,负责维护集群的状态,例如复制控制器、部署控制器等。
  8. #scheduler: 调度器,负责决定将哪个 Pod 安排到哪个节点。
  9. #etcd-0: 分布式键值存储,用于存储 Kubernetes 集群的所有数据。
复制代码
1.2、查看节点信息

1.2.1、查看节点信息
  1. #查看节点信息
  2. [root@linux-servertwo software]# kubectl get nodes
  3. NAME              STATUS   ROLES                  AGE   VERSION
  4. linux-servertwo   Ready    control-plane,master,node   26h   v1.20.9
复制代码
1.2.2、查看更加充分的节点信息
  1. #查看更加充分的节点信息
  2. [root@linux-servertwo software]# kubectl get nodes -o wide
  3. NAME              STATUS   ROLES                  AGE   VERSION   INTERNAL-IP   EXTERNAL-IP   OS-IMAGE                KERNEL-VERSION                 CONTAINER-RUNTIME
  4. linux-servertwo   Ready    control-plane,master,node   27h   v1.20.9   10.0.4.16     <none>        CentOS Linux 7 (Core)   3.10.0-1160.108.1.el7.x86_64   docker://26.1.3
复制代码
1.2.3、查看节点详情
  1. #查看节点详情:
  2. [root@linux-servertwo software]# kubectl describe node linux-servertwo
  3. Name:               linux-servertwo
  4. Roles:              control-plane,master,node
  5. Labels:             beta.kubernetes.io/arch=amd64
  6.                     beta.kubernetes.io/os=linux
  7.                     kubernetes.io/arch=amd64
  8.                     kubernetes.io/hostname=linux-servertwo
  9.                     kubernetes.io/os=linux
  10.                     node-role.kubernetes.io/control-plane=
  11.                     node-role.kubernetes.io/master=
  12.                     node-role.kubernetes.io/node=
  13. ......
复制代码
1.3、查看系统组件
  1. # 集群中的各个组件也都是以Pod方式运行的
  2. [root@linux-servertwo software]# kubectl get pods -n kube-system
  3. NAME                                      READY   STATUS    RESTARTS   AGE
  4. coredns-7f89b7bc75-2k74p                  1/1     Running   0          27h
  5. coredns-7f89b7bc75-6xrvb                  1/1     Running   0          27h
  6. etcd-linux-servertwo                      1/1     Running   0          27h
  7. kube-apiserver-linux-servertwo            1/1     Running   0          27h
  8. kube-controller-manager-linux-servertwo   1/1     Running   0          25h
  9. kube-proxy-bmfzr                          1/1     Running   0          27h
  10. kube-scheduler-linux-servertwo            1/1     Running   0          25h
复制代码
1.4、查看所有Pod

1.4.1、查看所有Pod信息
  1. [root@linux-servertwo software]# kubectl get pods --all-namespaces
  2. NAMESPACE      NAME                                      READY   STATUS    RESTARTS   AGE
  3. kube-flannel   kube-flannel-ds-lbmdr                     1/1     Running   0          5d
  4. kube-system    coredns-7f89b7bc75-47d56                  1/1     Running   0          6d4h
  5. kube-system    coredns-7f89b7bc75-h4c9b                  1/1     Running   0          6d4h
  6. kube-system    etcd-linux-servertwo                      1/1     Running   0          6d4h
  7. kube-system    kube-apiserver-linux-servertwo            1/1     Running   0          6d4h
  8. kube-system    kube-controller-manager-linux-servertwo   1/1     Running   0          5d
  9. kube-system    kube-proxy-j7d4v                          1/1     Running   0          6d4h
  10. kube-system    kube-scheduler-linux-servertwo            1/1     Running   0          5d
复制代码
1.4.2、查看更充分的所有pod信息
  1. # 查看更充分的所有pod详情信息
  2. [root@linux-servertwo software]# kubectl get pods --all-namespaces -o wide
  3. NAMESPACE      NAME                                      READY   STATUS    RESTARTS   AGE    IP           NODE              NOMINATED NODE   READINESS GATES
  4. kube-flannel   kube-flannel-ds-lbmdr                     1/1     Running   0          5d     10.0.4.16    linux-servertwo   <none>           <none>
  5. kube-system    coredns-7f89b7bc75-47d56                  1/1     Running   0          6d4h   172.17.0.3   linux-servertwo   <none>           <none>
  6. kube-system    coredns-7f89b7bc75-h4c9b                  1/1     Running   0          6d4h   172.17.0.2   linux-servertwo   <none>           <none>
  7. kube-system    etcd-linux-servertwo                      1/1     Running   0          6d4h   10.0.4.16    linux-servertwo   <none>           <none>
  8. kube-system    kube-apiserver-linux-servertwo            1/1     Running   0          6d4h   10.0.4.16    linux-servertwo   <none>           <none>
  9. kube-system    kube-controller-manager-linux-servertwo   1/1     Running   0          5d     10.0.4.16    linux-servertwo   <none>           <none>
  10. kube-system    kube-proxy-j7d4v                          1/1     Running   0          6d4h   10.0.4.16    linux-servertwo   <none>           <none>
  11. kube-system    kube-scheduler-linux-servertwo            1/1     Running   0          5d     10.0.4.16    linux-servertwo   <none>           <none>
复制代码
1.5、查看节点日志
  1. 使用 journalctl -u kubelet 命令查看日志信息
  2. # 动态查看 kubelet 日志的命令
  3. [root@linux-servertwo software]# journalctl -u kubelet -f
  4. Mar 19 15:53:58 linux-servertwo kubelet[25155]: I0319 15:53:58.023328   25155 reconciler.go:224] operationExecutor.VerifyControllerAttachedVolume started for volume "config-volume" (UniqueName: "kubernetes.io/configmap/9d6647d1-caeb-448a-9628-c5ac14821995-config-volume") pod "coredns-7f89b7bc75-47d56" (UID: "9d6647d1-caeb-448a-9628-c5ac14821995")
  5. Mar 19 15:53:58 linux-servertwo kubelet[25155]: map[string]interface {}{"cniVersion":"0.3.1", "hairpinMode":true, "ipMasq":false, "ipam":map[string]interface {}{"ranges":[][]map[string]interface {}{[]map[string]interface {}{map[string]interface {}{"subnet":"172.17.0.0/24"}}}, "routes":[]types.Route{types.Route{Dst:net.IPNet{IP:net.IP{0xac, 0x11, 0x0, 0x0}, Mask:net.IPMask{0xff, 0xff, 0x0, 0x0}}, GW:net.IP(nil)}}, "type":"host-local"}, "isDefaultGateway":true, "isGateway":true, "mtu":(*uint)(0xc00001c928), "name":"cbr0", "type":"bridge"}
  6. Mar 19 15:53:58 linux-servertwo kubelet[25155]: {"cniVersion":"0.3.1","hairpinMode":true,"ipMasq":false,"ipam":{"ranges":[[{"subnet":"172.17.0.0/24"}]],"routes":[{"dst":"172.17.0.0/16"}],"type":"host-local"},"isDefaultGateway":true,"isGateway":true,"mtu":1450,"name":"cbr0","type":"bridge"}
  7. Mar 19 15:53:58 linux-servertwo kubelet[25155]: map[string]interface {}{"cniVersion":"0.3.1", "hairpinMode":true, "ipMasq":false, "ipam":map[string]interface {}{"ranges":[][]map[string]interface {}{[]map[string]interface {}{map[string]interface {}{"subnet":"172.17.0.0/24"}}}, "routes":[]types.Route{types.Route{Dst:net.IPNet{IP:net.IP{0xac, 0x11, 0x0, 0x0}, Mask:net.IPMask{0xff, 0xff, 0x0, 0x0}}, GW:net.IP(nil)}}, "type":"host-local"}, "isDefaultGateway":true, "isGateway":true, "mtu":(*uint)(0xc0000a28e8), "name":"cbr0", "type":"bridge"}
复制代码
2、Namespaces

2.1、介绍

命名空间Namespaces主要作用是用来实现多套环境的资源隔离或者多租户的资源隔离。它能够将资源划分为不同的分组,帮助我们在一个集群中划分不同的项目、团队或者环境(如开发、测试和生产环境),从而提高资源的隔离性和管理效率。
2.2、查看创建的命名空间
  1. [root@linux-servertwo software]# kubectl get namespaces
  2. NAME              STATUS   AGE
  3. default           Active   24h
  4. kube-flannel      Active   19h
  5. kube-node-lease   Active   24h
  6. kube-public       Active   24h
  7. kube-system       Active   24h
复制代码
2.3、创建命名空间
  1. [root@linux-servertwo software]# kubectl create namespace blog-dev
  2. namespace/blog-dev created
  3. # 再次查看-命名空间 blog-dev 创建成功
  4. [root@linux-servertwo software]# kubectl get namespaces
  5. NAME              STATUS   AGE
  6. blog-dev          Active   17s
  7. default           Active   24h
  8. kube-flannel      Active   19h
  9. kube-node-lease   Active   24h
  10. kube-public       Active   24h
  11. kube-system       Active   24h
复制代码
2.4、删除命名空间
  1. #删除
  2. [root@linux-servertwo software]# kubectl delete namespace blog-dev
  3. namespace "blog-dev" deleted
  4. #再次查看-发现已经删除
  5. [root@linux-servertwo software]# kubectl get namespaces
  6. NAME              STATUS   AGE
  7. default           Active   24h
  8. kube-flannel      Active   20h
  9. kube-node-lease   Active   24h
  10. kube-public       Active   24h
  11. kube-system       Active   24h
复制代码
2.5、检索指定命名空间
  1. # 查看-检索指定命名空间
  2. [root@linux-servertwo software]# kubectl get namespaces blog-dev
  3. NAME       STATUS   AGE
  4. blog-dev   Active   39s
  5. # 查看-指定命名空间详情
  6. [root@linux-servertwo software]# kubectl describe namespace blog-dev
  7. Name:         blog-dev
  8. Labels:       <none>
  9. Annotations:  <none>
  10. Status:       Active
  11. No resource quota.
  12. No LimitRange resource.
复制代码
2.6、查看命名空间中的资源
  1. [root@linux-servertwo software]# kubectl get pods -n blog-dev
  2. No resources found in blog-dev namespace.
  3. [root@linux-servertwo software]# kubectl get pod -n kube-system
  4. NAME                                      READY   STATUS    RESTARTS   AGE
  5. coredns-7f89b7bc75-47d56                  1/1     Running   0          6d4h
  6. coredns-7f89b7bc75-h4c9b                  1/1     Running   0          6d4h
  7. etcd-linux-servertwo                      1/1     Running   0          6d4h
  8. kube-apiserver-linux-servertwo            1/1     Running   0          6d4h
  9. kube-controller-manager-linux-servertwo   1/1     Running   0          5d1h
  10. kube-proxy-j7d4v                          1/1     Running   0          6d4h
  11. kube-scheduler-linux-servertwo            1/1     Running   0          5d1h
复制代码
2.7、输出yaml格式
  1. # 查看-输出yaml格式
  2. [root@linux-servertwo software]# kubectl get namespaces blog-dev -o yaml
  3. apiVersion: v1
  4. kind: Namespace
  5. metadata:
  6.   creationTimestamp: "2024-12-10T03:58:55Z"
  7.   managedFields:
  8.   - apiVersion: v1
  9.     fieldsType: FieldsV1
  10.     fieldsV1:
  11.       f:status:
  12.         f:phase: {}
  13.     manager: kubectl-create
  14.     operation: Update
  15.     time: "2024-12-10T03:58:55Z"
  16.   name: blog-dev
  17.   resourceVersion: "106051"
  18.   uid: 406d2440-b725-409f-9a01-2bf8c606e5cf
  19. spec:
  20.   finalizers:
  21.   - kubernetes
  22. status:
  23.   phase: Active
  24.   
  25. # 输出一个yaml创建命名空间的格式,但不运行
  26. [root@linux-servertwo software]# kubectl create namespace blog-dev-1 --dry-run=client -o yaml
  27. apiVersion: v1
  28. kind: Namespace
  29. metadata:
  30.   creationTimestamp: null
  31.   name: blog-dev-1
  32. spec: {}
  33. status: {}
  34. # 输出一个yaml创建命名空间的格式,但不运行 ,输出到主机blog-dev-1.yaml文件中
  35. [root@linux-servertwo software]# kubectl create namespace blog-dev-1 --dry-run=client -o yaml > blog-dev-1.yaml
  36. #查看输出的文件信息
  37. [root@linux-servertwo software]# ls
  38. blog-dev-1.yaml
  39. [root@linux-servertwo software]# cat blog-dev-1.yaml
  40. apiVersion: v1
  41. kind: Namespace
  42. metadata:
  43.   creationTimestamp: null
  44.   name: blog-dev-1
  45. spec: {}
  46. status: {}
复制代码
2.8、YAML创建
  1. # 声明文件创建
  2. [root@linux-servertwo software]# kubectl apply -f blog-dev-1.yaml
  3. namespace/blog-dev-1 created
  4. [root@linux-servertwo software]# kubectl get namespaces
  5. NAME              STATUS   AGE
  6. blog-dev          Active   3h11m
  7. blog-dev-1        Active   9s
  8. default           Active   27h
  9. kube-flannel      Active   23h
  10. kube-node-lease   Active   27h
  11. kube-public       Active   27h
  12. kube-system       Active   27h
  13. nginx             Active   37m
复制代码
2.9、YAML删除
  1. # 删除命名空间-以yml的形式
  2. [root@linux-servertwo software]# kubectl delete -f blog-dev-1.yaml
  3. namespace "blog-dev-1" deleted
  4. [root@linux-servertwo software]# kubectl get namespaces
  5. NAME              STATUS   AGE
  6. blog-dev          Active   3h13m
  7. default           Active   27h
  8. kube-flannel      Active   23h
  9. kube-node-lease   Active   27h
  10. kube-public       Active   27h
  11. kube-system       Active   27h
  12. nginx             Active   38m
复制代码
2.10、切换命名空间
  1. # 通过设置默认命名空间,可以在运行其他命令时避免每次都加上 -n <namespace-name>
  2. [root@linux-servertwo software]# kubectl config set-context --current --namespace=kube-system
  3. Context "kubernetes-admin@kubernetes" modified.
  4. # 查看pod
  5. [root@linux-servertwo software]# kubectl get pods
  6. NAME                                      READY   STATUS    RESTARTS   AGE
  7. coredns-7f89b7bc75-47d56                  1/1     Running   0          6d4h
  8. coredns-7f89b7bc75-h4c9b                  1/1     Running   0          6d4h
  9. etcd-linux-servertwo                      1/1     Running   0          6d4h
  10. kube-apiserver-linux-servertwo            1/1     Running   0          6d4h
  11. kube-controller-manager-linux-servertwo   1/1     Running   0          5d1h
  12. kube-proxy-j7d4v                          1/1     Running   0          6d4h
  13. kube-scheduler-linux-servertwo            1/1     Running   0          5d1h
  14. # 查看当前使用的命名空间
  15. [root@linux-servertwo software]# kubectl config view --minify | grep namespace:
  16. namespace: kube-system
  17. # 设置为默认
  18. [root@linux-servertwo software]# kubectl config set-context --current --namespace=default
  19. Context "kubernetes-admin@kubernetes" modified.
  20. [root@linux-servertwo software]# kubectl config view --minify | grep namespace:
  21. namespace: default
  22.    
  23. [root@linux-servertwo software]# kubectl get pods
  24. No resources found in default namespace.
复制代码
3、Pod命令使用

3.1、介绍

Pod是Kubernetes中可以创建和管理的最小部署单元,也是Kubernetes应用的基本运行单位,它封装了一个或多个容器和存储资源。Pod中的所有容器共享相同的网络命名空间、IP 地址、端口空间以及存储卷。通常情况下不直接管理 Pod,而是通过更高层次的抽象(如 Deployment、StatefulSet 等)来管理 Pod 的生命周期。下面就以安装nginx为例,单独介绍一下Pod的相关使用。
3.2、创建命名空间

首先创建好一个nginx的命名空间,做好数据隔离。
  1. # 创建命名空间nginx
  2. [root@linux-servertwo software]#  kubectl create namespace nginx
  3. namespace/nginx created
  4. # 列出所有Pod: kubectl get pods -n <namespace-name>
  5. [root@linux-servertwo software]# kubectl get pods -n nginx
  6. No resources found in nginx namespace.
复制代码
3.3、创建Pod
  1. # 创建Pod 通过Pod控制器创建Pod
  2. # 命令格式: kubectl run (pod控制器名称) [参数]
  3. # --image  指定Pod的镜像
  4. # --port   指定端口
  5. # --namespace  指定namespace
  6. [root@linux-servertwo nginx]# kubectl run nginx --image nginx:latest --port 80 --namespace nginx
  7. pod/nginx created
复制代码
3.4、查看Pod信息
  1. # 查看Pods信息
  2. [root@linux-servertwo nginx]# kubectl get pods -n nginx
  3. NAME    READY   STATUS    RESTARTS   AGE
  4. nginx   1/1     Running   0          9m6s
  5. # 更详细得查看pods信息
  6. [root@linux-servertwo nginx]#  kubectl get pods -n nginx -o wide
  7. NAME    READY   STATUS    RESTARTS   AGE   IP            NODE              NOMINATED NODE   READINESS GATES
  8. nginx   1/1     Running   0          15m   172.17.0.68   linux-servertwo   <none>           <none>
  9. # 查看详情Pod信息
  10. [root@linux-servertwo nginx]# kubectl describe pods nginx -n nginx
  11. Name:         nginx
  12. Namespace:    nginx
  13. Priority:     0
  14. Node:         linux-servertwo/10.0.4.16
  15. Start Time:   Wed, 11 Dec 2024 16:16:48 +0800
  16. Labels:       run=nginx
  17. Annotations:  <none>
  18. Status:       Running
  19. IP:           172.17.0.68
  20. IPs:
  21.   IP:  172.17.0.68
  22. ......
  23. Events:
  24.   Type    Reason     Age    From               Message
  25.   ----    ------     ----   ----               -------
  26.   Normal  Scheduled  9m29s  default-scheduler  Successfully assigned nginx/nginx to linux-servertwo
  27.   Normal  Pulling    9m28s  kubelet            Pulling image "nginx:latest"
  28.   Normal  Pulled     8m36s  kubelet            Successfully pulled image "nginx:latest" in 52.683702042s
  29.   Normal  Created    8m35s  kubelet            Created container nginx
  30.   Normal  Started    8m35s  kubelet            Started container nginx
复制代码
3.5、验证创建成功
  1. # 根据IP访问nginx,发现nginx启动成功
  2. [root@linux-servertwo nginx]# curl 172.17.0.68:80
  3. <!DOCTYPE html>
  4. <html>
  5. <head>
  6. <title>Welcome to nginx!</title>
  7. </head>
  8. <body>
  9. <h1>Welcome to nginx!</h1>
  10. <p>If you see this page, the nginx web server is successfully installed and
  11. working. Further configuration is required.</p>
  12. <p>For online documentation and support please refer to
  13. nginx.org.<br/>
  14. Commercial support is available at
  15. nginx.com.</p>
  16. <p><em>Thank you for using nginx.</em></p>
  17. </body>
  18. </html>
复制代码
3.6、删除Pod
  1. # 删除Pod
  2. [root@linux-servertwo nginx]# kubectl delete pods -n nginx nginx
  3. pod "nginx" deleted
  4. # 再次查看,发现已经删除
  5. [root@linux-servertwo nginx]# kubectl get pod -n nginx
  6. No resources found in nginx namespace.
  7. # 上面只删除Pod,创建的命名空间还在
  8. [root@linux-servertwo nginx]# kubectl get namespaces
  9. NAME                   STATUS   AGE
  10. blog-dev               Active   28h
  11. default                Active   2d4h
  12. kube-flannel           Active   2d
  13. kube-node-lease        Active   2d4h
  14. kube-public            Active   2d4h
  15. kube-system            Active   2d4h
  16. kubernetes-dashboard   Active   155m
  17. nginx                  Active   26h
复制代码
3.7、YAML创建Pod

接下来使用yaml格式文件创建nginx
  1. # 输出一个 nginx 的 yaml 格式 pod 到 nginx-pod.yaml 文件
  2. [root@linux-servertwo nginx]# kubectl run nginx --image nginx:latest --port 80 --namespace nginx --dry-run=client -o yaml > nginx-pod.yaml
  3. # 查看 nginx-pod.yaml 文件
  4. [root@linux-servertwo nginx]# cat nginx-pod.yaml
  5. apiVersion: v1
  6. kind: Pod
  7. metadata:
  8.   creationTimestamp: null
  9.   labels:
  10.     run: nginx
  11.   name: nginx
  12.   namespace: nginx
  13. spec:
  14.   containers:
  15.   - image: nginx:latest
  16.     name: nginx
  17.     ports:
  18.     - containerPort: 80
  19.     resources: {}
  20.   dnsPolicy: ClusterFirst
  21.   restartPolicy: Always
  22. status: {}
  23. # pod 声明
  24. [root@linux-servertwo nginx]# kubectl apply -f nginx-pod.yaml
  25. pod/nginx created
  26. # 查看-发现创建成功
  27. [root@linux-servertwo nginx]# kubectl get pod nginx -n nginx
  28. NAME    READY   STATUS    RESTARTS   AGE
  29. nginx   1/1     Running   0          20s
  30. # 查看详情
  31. [root@linux-servertwo nginx]# kubectl describe pod nginx -n nginx
  32. Name:         nginx
  33. Namespace:    nginx
  34. Priority:     0
  35. Node:         linux-servertwo/10.0.4.16
  36. Start Time:   Wed, 11 Dec 2024 16:42:53 +0800
  37. Labels:       run=nginx
  38. Annotations:  <none>
  39. Status:       Running
  40. IP:           172.17.0.69
  41. IPs:
  42.   IP:  172.17.0.69
  43.   ......
  44. Events:
  45.   Type    Reason     Age   From               Message
  46.   ----    ------     ----  ----               -------
  47.   Normal  Scheduled  93s   default-scheduler  Successfully assigned nginx/nginx to linux-servertwo
  48.   Normal  Pulling    93s   kubelet            Pulling image "nginx:latest"
  49.   Normal  Pulled     91s   kubelet            Successfully pulled image "nginx:latest" in 2.213103384s
  50.   Normal  Created    91s   kubelet            Created container nginx
  51.   Normal  Started    91s   kubelet            Started container nginx
复制代码
3.8、验证是否成功
  1. # 访问
  2. [root@linux-servertwo nginx]# curl  172.17.0.69:80
  3. <!DOCTYPE html>
  4. <html>
  5. <head>
  6. <title>Welcome to nginx!</title>
  7. </head>
  8. <body>
  9. <h1>Welcome to nginx!</h1>
  10. <p>If you see this page, the nginx web server is successfully installed and
  11. working. Further configuration is required.</p>
  12. <p>For online documentation and support please refer to
  13. nginx.org.<br/>
  14. Commercial support is available at
  15. nginx.com.</p>
  16. <p><em>Thank you for using nginx.</em></p>
  17. </body>
  18. </html>
复制代码
3.9、YAML删除Pod
  1. #删除-通过yaml方式
  2. [root@linux-servertwo nginx]# kubectl delete  -f nginx-pod.yaml
  3. pod "nginx" deleted
  4. #再次查看,发现和使用命令删除Pod一样,只删除Pod不删除namespaces
  5. [root@linux-servertwo nginx]# kubectl get pod -n nginx
  6. No resources found in nginx namespace.
  7. [root@linux-servertwo nginx]# kubectl get namespaces
  8. NAME                   STATUS   AGE
  9. blog-dev               Active   28h
  10. default                Active   2d5h
  11. kube-flannel           Active   2d
  12. kube-node-lease        Active   2d5h
  13. kube-public            Active   2d5h
  14. kube-system            Active   2d5h
  15. kubernetes-dashboard   Active   168m
  16. nginx                  Active   26h
复制代码
3.10、查看Pod日志
  1. # 通过 kubectl logs <pod-name> -n <namespace-name> 进行查看特定命名空间中 Pod 的日志
  2. [root@linux-servertwo software]# kubectl logs nginx -n nginx
  3. /docker-entrypoint.sh: /docker-entrypoint.d/ is not empty, will attempt to perform configuration
  4. /docker-entrypoint.sh: Looking for shell scripts in /docker-entrypoint.d/
  5. /docker-entrypoint.sh: Launching /docker-entrypoint.d/10-listen-on-ipv6-by-default.sh
  6. 10-listen-on-ipv6-by-default.sh: info: Getting the checksum of /etc/nginx/conf.d/default.conf
  7. 10-listen-on-ipv6-by-default.sh: info: Enabled listen on IPv6 in /etc/nginx/conf.d/default.conf
  8. /docker-entrypoint.sh: Sourcing /docker-entrypoint.d/15-local-resolvers.envsh
  9. /docker-entrypoint.sh: Launching /docker-entrypoint.d/20-envsubst-on-templates.sh
  10. /docker-entrypoint.sh: Launching /docker-entrypoint.d/30-tune-worker-processes.sh
  11. /docker-entrypoint.sh: Configuration complete; ready for start up
  12. 2025/03/24 09:32:43 [notice] 1#1: using the "epoll" event method
  13. 2025/03/24 09:32:43 [notice] 1#1: nginx/1.27.4
  14. 2025/03/24 09:32:43 [notice] 1#1: built by gcc 12.2.0 (Debian 12.2.0-14)
  15. 2025/03/24 09:32:43 [notice] 1#1: OS: Linux 3.10.0-1160.108.1.el7.x86_64
  16. 2025/03/24 09:32:43 [notice] 1#1: getrlimit(RLIMIT_NOFILE): 65536:65536
  17. 2025/03/24 09:32:43 [notice] 1#1: start worker processes
  18. 2025/03/24 09:32:43 [notice] 1#1: start worker process 29
  19. 2025/03/24 09:32:43 [notice] 1#1: start worker process 30
  20. 172.17.0.1 - - [24/Mar/2025:09:33:19 +0000] "GET / HTTP/1.1" 200 615 "-" "curl/7.29.0" "-"
  21. 172.17.0.1 - - [24/Mar/2025:09:34:24 +0000] "GET / HTTP/1.1" 200 615 "-" "curl/7.29.0" "-"
  22. 172.17.0.1 - - [24/Mar/2025:09:34:26 +0000] "GET / HTTP/1.1" 200 615 "-" "curl/7.29.0" "-"
  23. # 如果 Pod 包含多个容器,可以指定容器名称
  24. # kubectl logs <pod-name> -c <container-name>
  25. [root@linux-servertwo software]# kubectl logs nginx -n nginx -c nginx -f
  26. /docker-entrypoint.sh: /docker-entrypoint.d/ is not empty, will attempt to perform configuration
  27. /docker-entrypoint.sh: Looking for shell scripts in /docker-entrypoint.d/
  28. /docker-entrypoint.sh: Launching /docker-entrypoint.d/10-listen-on-ipv6-by-default.sh
  29. 10-listen-on-ipv6-by-default.sh: info: Getting the checksum of /etc/nginx/conf.d/default.conf
  30. 10-listen-on-ipv6-by-default.sh: info: Enabled listen on IPv6 in /etc/nginx/conf.d/default.conf
  31. /docker-entrypoint.sh: Sourcing /docker-entrypoint.d/15-local-resolvers.envsh
  32. /docker-entrypoint.sh: Launching /docker-entrypoint.d/20-envsubst-on-templates.sh
  33. /docker-entrypoint.sh: Launching /docker-entrypoint.d/30-tune-worker-processes.sh
  34. /docker-entrypoint.sh: Configuration complete; ready for start up
  35. 2025/03/24 13:01:13 [notice] 1#1: using the "epoll" event method
  36. 2025/03/24 13:01:13 [notice] 1#1: nginx/1.27.4
  37. 2025/03/24 13:01:13 [notice] 1#1: built by gcc 12.2.0 (Debian 12.2.0-14)
  38. 2025/03/24 13:01:13 [notice] 1#1: OS: Linux 3.10.0-1160.108.1.el7.x86_64
  39. 2025/03/24 13:01:13 [notice] 1#1: getrlimit(RLIMIT_NOFILE): 65536:65536
  40. 2025/03/24 13:01:13 [notice] 1#1: start worker processes
  41. 2025/03/24 13:01:13 [notice] 1#1: start worker process 29
  42. 2025/03/24 13:01:13 [notice] 1#1: start worker process 30
  43. 172.17.0.1 - - [24/Mar/2025:13:01:40 +0000] "GET / HTTP/1.1" 200 615 "-" "curl/7.29.0" "-"
  44. 172.17.0.1 - - [24/Mar/2025:13:03:47 +0000] "GET / HTTP/1.1" 200 615 "-" "curl/7.29.0" "-"
  45. 172.17.0.1 - - [25/Mar/2025:02:24:58 +0000] "GET / HTTP/1.1" 200 615 "-" "curl/7.29.0" "-"
复制代码
3.11、进入容器
  1. #  进入Pod容器:kubectl exec -it <pod-name> -- /bin/bash
  2. [root@linux-servertwo software]# kubectl exec -it nginx -n nginx  -- /bin/bash
  3. root@nginx:/# ls
  4. bin  boot  dev  docker-entrypoint.d  docker-entrypoint.sh  etc  home  lib  lib64  media  mnt  opt  proc  root  run  sbin  srv  sys  tmp  usr  var
  5. root@nginx:/# nginx -V      
  6. nginx version: nginx/1.27.4
  7. built by gcc 12.2.0 (Debian 12.2.0-14)
  8. built with OpenSSL 3.0.11 19 Sep 2023 (running with OpenSSL 3.0.15 3 Sep 2024)
  9. TLS SNI support enabled
  10. configure arguments: --prefix=/etc/nginx --sbin-path=/usr/sbin/nginx --modules-path=/usr/lib/nginx/modules --conf-path=/etc/nginx/nginx.conf --error-log-path=/var/log/nginx/error.log --http-log-path=/var/log/nginx/access.log --pid-path=/var/run/nginx.pid --lock-path=/var/run/nginx.lock --http-client-body-temp-path=/var/cache/nginx/client_temp --http-proxy-temp-path=/var/cache/nginx/proxy_temp --http-fastcgi-temp-path=/var/cache/nginx/fastcgi_temp --http-uwsgi-temp-path=/var/cache/nginx/uwsgi_temp --http-scgi-temp-path=/var/cache/nginx/scgi_temp --user=nginx --group=nginx --with-compat --with-file-aio --with-threads --with-http_addition_module --with-http_auth_request_module --with-http_dav_module --with-http_flv_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_mp4_module --with-http_random_index_module --with-http_realip_module --with-http_secure_link_module --with-http_slice_module --with-http_ssl_module --with-http_stub_status_module --with-http_sub_module --with-http_v2_module --with-http_v3_module --with-mail --with-mail_ssl_module --with-stream --with-stream_realip_module --with-stream_ssl_module --with-stream_ssl_preread_module --with-cc-opt='-g -O2 -ffile-prefix-map=/data/builder/debuild/nginx-1.27.4/debian/debuild-base/nginx-1.27.4=. -fstack-protector-strong -Wformat -Werror=format-security -Wp,-D_FORTIFY_SOURCE=2 -fPIC' --with-ld-opt='-Wl,-z,relro -Wl,-z,now -Wl,--as-needed -pie'
  11. root@nginx:/#
  12. # 如果 Pod 中有多个容器,可以通过 -c 参数指定容器:kubectl exec -it <pod-name> -c <container-name> -- /bin/bash
  13. [root@linux-servertwo software]# kubectl exec -it nginx -c nginx  -n nginx -- /bin/bash
  14. root@nginx:/# ls
  15. bin  boot  dev  docker-entrypoint.d  docker-entrypoint.sh  etc  home  lib  lib64  media  mnt  opt  proc  root  run  sbin  srv  sys  tmp  usr  var
  16. root@nginx:/#
复制代码
3.12、查看 Pod 关联的事件
  1. # 查看与 Pod 相关的事件,了解 Pod 的运行状态以及错误信息:
  2. [root@linux-servertwo software]# kubectl get events --field-selector involvedObject.name=nginx -n nginx
  3. LAST SEEN   TYPE     REASON      OBJECT      MESSAGE
  4. 5m42s       Normal   Scheduled   pod/nginx   Successfully assigned nginx/nginx to linux-servertwo
  5. 5m42s       Normal   Pulling     pod/nginx   Pulling image "nginx:latest"
  6. 5m32s       Normal   Pulled      pod/nginx   Successfully pulled image "nginx:latest" in 9.177513284s
  7. 5m32s       Normal   Created     pod/nginx   Created container nginx
  8. 5m32s       Normal   Started     pod/nginx   Started container nginx
复制代码
3.13、Pod 的扩展和缩容

直接修改 Pod 数量需要使用副本集(ReplicaSet)或部署(Deployment)来管理。例如,使用以下命令扩展或缩容 Pod 副本数:
  1. # kubectl scale --replicas=<num> deployment/<deployment-name>
  2. kubectl scale --replicas=3 deployment/my-app-nginx
复制代码
在 Kubernetes 中,Pod 的扩展和缩容通常是通过它们的资源来管理的。Deployment 允许定义多个副本(Pod 实例),并可以根据需要进行扩展和缩容。Deployment 会自动管理 Pod 的生命周期和状态,包括在需要时扩展和缩容 Pod 数量。下面就来介绍Deployment 的相关使用命令。
4、Deployment命令使用

4.1、介绍

在 Kubernetes中,Pod 是最小的调度和管理单元,但Kubernetes很少直接操作单个 Pod。通常,Kubernetes是通过 Pod 控制器 来间接管理 Pod,实现对 Pod 的控制与维护,确保 Pod 的状态始终符合预期。这些控制器负责自动化创建、调度、更新和扩展 Pod,并确保其高可用性和健康。当 Pod 发生故障或失效时,控制器会自动执行恢复操作,如重启或重新创建 Pod,以确保应用的连续性和稳定性。Kubernetes中常见的 Pod控制器 包括 DeploymentReplicaSetStatefulSetDaemonSetJobCronJob,它们各自负责不同的用例和场景,提供了灵活的管理方式,满足不同的需求场景。通过这些控制器,Kubernetes实现了强大的自愈能力、扩展性和灵活性,使得容器化应用的管理更加高效、可靠。下面介绍其中一个 Pod控制器 :Deployment
4.2、创建 Deployment

可以通过 kubectl create 或 kubectl apply 命令来创建 Deployment
  1. # 创建deployment控制器
  2. # 命令格式:
  3. #    kubectl create deployment 名称  [参数]
  4. # 参数:
  5. #    -n/--namespace  指定创建的所属命名空间
  6. #    --image  指定pod的镜像
  7. #    --port   指定端口
  8. #    --replicas 指定创建pod数量  --replicas=3:指定该 Deployment 创建的 Pod 副本数量为 3,
  9. # 该命令表示 Kubernetes 将确保始终有 3 个运行中的 nginx Pod 实例来提供服务,实现高可用性和负载均衡
  10. [root@linux-servertwo software]# kubectl create deployment nginx -n nginx --image nginx:latest --port 80 --replicas=3
  11. deployment.apps/nginx created
  12. # 查看命名空间下面的Pod
  13. [root@linux-servertwo nginx]# kubectl get pods -n nginx
  14. NAME                    READY   STATUS    RESTARTS   AGE
  15. nginx-585449566-6788b   1/1     Running   0          39s
  16. nginx-585449566-bhbtp   1/1     Running   0          39s
  17. nginx-585449566-gk2kl   1/1     Running   0          39s
复制代码
4.3、查看 Deployment
  1. # 查看deployment状态
  2. [root@linux-servertwo nginx]# kubectl get deployment -n nginx
  3. NAME    READY   UP-TO-DATE   AVAILABLE   AGE
  4. nginx   3/3     3            3           88s
  5. # 查看某一个 Deployment 信息 kubectl get deployment <deployment-name> <namespaces>
  6. [root@linux-servertwo software]# kubectl get deployment nginx -n nginx
  7. NAME    READY   UP-TO-DATE   AVAILABLE   AGE
  8. nginx   3/3     3            3           25m
  9. # 查看 Deployment 的 YAML 配置
  10. [root@linux-servertwo software]# kubectl get deployment nginx -n nginx -o yaml
  11. apiVersion: apps/v1
  12. kind: Deployment
  13. metadata:
  14.   annotations:
  15.     deployment.kubernetes.io/revision: "1"
  16.   generation: 1
  17.   labels:
  18.     app: nginx
  19. ......
  20. status:
  21.   availableReplicas: 3
  22.   conditions:
  23.   - lastTransitionTime: "2025-03-25T07:38:18Z"
  24.     lastUpdateTime: "2025-03-25T07:38:18Z"
  25.     message: Deployment has minimum availability.
  26.     reason: MinimumReplicasAvailable
  27.     status: "True"
  28.     type: Available
  29.   - lastTransitionTime: "2025-03-25T07:38:14Z"
  30.     lastUpdateTime: "2025-03-25T07:38:18Z"
  31.     message: ReplicaSet "nginx-585449566" has successfully progressed.
  32.     reason: NewReplicaSetAvailable
  33.     status: "True"
  34.     type: Progressing
  35.   observedGeneration: 1
  36.   readyReplicas: 3
  37.   replicas: 3
  38.   updatedReplicas: 3
  39. # 更详细得查看deployment信息 UP-TO-DATE:成功升级的副本数量, AVAILABLE:可用副本的数量
  40. [root@linux-servertwo nginx]# kubectl get deployment -n nginx -o wide
  41. NAME    READY   UP-TO-DATE   AVAILABLE   AGE     CONTAINERS   IMAGES         SELECTOR
  42. nginx   3/3     3            3           4m56s   nginx        nginx:latest   app=nginx
  43. # 查看deployment详情
  44. [root@linux-servertwo nginx]# kubectl describe deployment -n nginx
  45. Name:                   nginx
  46. Namespace:              nginx
  47. CreationTimestamp:      Fri, 13 Dec 2024 10:26:15 +0800
  48. Labels:                 app=nginx
  49. Annotations:            deployment.kubernetes.io/revision: 1
  50. Selector:               app=nginx
  51. Replicas:               3 desired | 3 updated | 3 total | 3 available | 0 unavailable
  52. StrategyType:           RollingUpdate
  53. MinReadySeconds:        0
  54. RollingUpdateStrategy:  25% max unavailable, 25% max surge
  55. Pod Template:
  56.   Labels:  app=nginx
  57.   Containers:
  58.    nginx:
  59.     Image:        nginx:latest
  60.     Port:         80/TCP
  61.     Host Port:    0/TCP
  62.     Environment:  <none>
  63.     Mounts:       <none>
  64.   Volumes:        <none>
  65. Conditions:
  66.   Type           Status  Reason
  67.   ----           ------  ------
  68.   Available      True    MinimumReplicasAvailable
  69.   Progressing    True    NewReplicaSetAvailable
  70. OldReplicaSets:  <none>
  71. NewReplicaSet:   nginx-585449566 (3/3 replicas created)
  72. Events:
  73.   Type    Reason             Age   From                   Message
  74.   ----    ------             ----  ----                   -------
  75.   Normal  ScalingReplicaSet  3m9s  deployment-controller  Scaled up replica set nginx-585449566 to 3
复制代码
4.4、验证访问
  1. # 查看每一个nginx启动的容器IP
  2. [root@linux-servertwo nginx]# kubectl get pod -n nginx -o wide
  3. NAME                    READY   STATUS    RESTARTS   AGE     IP            NODE              NOMINATED NODE   READINESS GATES
  4. nginx-585449566-6788b   1/1     Running   0          9m33s   172.17.0.71   linux-servertwo   <none>           <none>
  5. nginx-585449566-bhbtp   1/1     Running   0          9m33s   172.17.0.72   linux-servertwo   <none>           <none>
  6. nginx-585449566-gk2kl   1/1     Running   0          9m33s   172.17.0.73   linux-servertwo   <none>           <none>
  7. # 通过IP尝试访问 172.17.0.71
  8. [root@linux-servertwo nginx]# curl 172.17.0.71
  9. <!DOCTYPE html>
  10. <html>
  11. <head>
  12. <title>Welcome to nginx!</title>
  13. </head>
  14. <body>
  15. <h1>Welcome to nginx!</h1>
  16. <p>If you see this page, the nginx web server is successfully installed and
  17. working. Further configuration is required.</p>
  18. <p>For online documentation and support please refer to
  19. nginx.org.<br/>
  20. Commercial support is available at
  21. nginx.com.</p>
  22. <p><em>Thank you for using nginx.</em></p>
  23. </body>
  24. </html>
  25. # 通过IP尝试访问 172.17.0.72
  26. [root@linux-servertwo nginx]# curl 172.17.0.72
  27. <!DOCTYPE html>
  28. <html>
  29. <head>
  30. <title>Welcome to nginx!</title>
  31. </head>
  32. <body>
  33. <h1>Welcome to nginx!</h1>
  34. <p>If you see this page, the nginx web server is successfully installed and
  35. working. Further configuration is required.</p>
  36. <p>For online documentation and support please refer to
  37. nginx.org.<br/>
  38. Commercial support is available at
  39. nginx.com.</p>
  40. <p><em>Thank you for using nginx.</em></p>
  41. </body>
  42. </html>
  43. #  通过IP尝试访问 172.17.0.73
  44. [root@linux-servertwo nginx]# curl 172.17.0.73
  45. <!DOCTYPE html>
  46. <html>
  47. <head>
  48. <title>Welcome to nginx!</title>
  49. </head>
  50. <body>
  51. <h1>Welcome to nginx!</h1>
  52. <p>If you see this page, the nginx web server is successfully installed and
  53. working. Further configuration is required.</p>
  54. <p>For online documentation and support please refer to
  55. nginx.org.<br/>
  56. Commercial support is available at
  57. nginx.com.</p>
  58. <p><em>Thank you for using nginx.</em></p>
  59. </body>
  60. </html>
复制代码
4.5、进入容器
  1. # 进入其中一个POD的容器内部
  2. [root@linux-servertwo nginx]# kubectl exec -it -n nginx nginx-585449566-6788b /bin/bash
  3. kubectl exec [POD] [COMMAND] is DEPRECATED and will be removed in a future version. Use kubectl exec [POD] -- [COMMAND] instead.
  4. root@nginx-585449566-6788b:/#
  5. # 上面命令提示已经准备弃用,使用新命令进入 需要加 --
  6. [root@linux-servertwo nginx]# kubectl exec -it -n nginx nginx-585449566-6788b -- /bin/bash
  7. root@nginx-585449566-6788b:/# nginx -v
  8. nginx version: nginx/1.27.3
复制代码
4.6、更新 Deployment

更新 Deployment 可以通过 kubectl set 或 kubectl apply 实现
  1. # 将上面部署的 nginx 的 deployment 的容器镜像更新为 nginx:1.19.0
  2. # kubectl set image deployment/<deployment-name> <container-name>=<new-image>
  3. [root@linux-servertwo software]# kubectl set image deployment/nginx nginx=nginx:1.19 -n nginx
  4. deployment.apps/nginx image updated
  5. # 查看是否更新-查看信息发现更新成功
  6. [root@linux-servertwo software]# kubectl get deployment -n nginx -o wide
  7. NAME    READY   UP-TO-DATE   AVAILABLE   AGE   CONTAINERS   IMAGES       SELECTOR
  8. nginx   3/3     3            3           40m   nginx        nginx:1.19   app=nginx
  9. # 进入其中一个POD的容器内部 查看nginx版本
  10. [root@linux-servertwo software]# kubectl exec -it -n nginx nginx-5479877cb4-2lpwv  -- /bin/bash
  11. root@nginx-5479877cb4-2lpwv:/# nginx -v
  12. nginx version: nginx/1.19.10
复制代码
4.7、查看和管理 Deployment 版本
  1. # 查看 Deployment 的历史版本
  2. [root@linux-servertwo software]# kubectl rollout history deployment/nginx -n nginx
  3. deployment.apps/nginx
  4. REVISION  CHANGE-CAUSE
  5. 1         <none>
  6. 2         <none>
  7. # 变更记录,REVISION 1: 初始部署的版本,REVISION 2: 更新后的版本,CHANGE-CAUSE: 每个修订版本的变更原因或描述。当前两个版本的 CHANGE-CAUSE 都为空。
  8. # 这可以通过在 kubectl set image 命令中添加 --record 参数来实现,每次更新时提供 CHANGE-CAUSE 信息
  9. # --record 参数会将命令记录到 Deployment 的变更历史中,方便后续查看和回滚。
  10. # 如以上更新命令加上参数 kubectl set image deployment/nginx nginx=nginx:1.19 -n nginx --record
  11. # 查看 Deployment 的滚动更新状态
  12. [root@linux-servertwo software]# kubectl rollout status deployment/nginx -n nginx
  13. deployment "nginx" successfully rolled out
  14. # 输出以上信息,表示 nginx Deployment 的滚动更新已经成功完成
复制代码
4.8、回滚 Deployment 版本

如果更新后的应用出现问题,可以通过回滚命令恢复到先前的版本。
  1. # 回滚到上一个版本:kubectl rollout undo deployment/<deployment-name>
  2. [root@linux-servertwo software]# kubectl rollout undo deployment/nginx -n nginx
  3. deployment.apps/nginx rolled back
  4. # 查看是否回滚成功
  5. [root@linux-servertwo software]# kubectl get deployment -n nginx -o wide
  6. NAME    READY   UP-TO-DATE   AVAILABLE   AGE   CONTAINERS   IMAGES         SELECTOR
  7. nginx   3/3     3            3           68m   nginx        nginx:latest   app=nginx
  8. # 可以发现nginx版本已经变为部署时候的最新版本。
  9. # 回滚到某个特定版本:kubectl rollout undo deployment/<deployment-name> --to-revision=<revision-number>
  10. [root@linux-servertwo software]# kubectl rollout undo deployment/nginx  -n nginx --to-revision=2
  11. deployment.apps/nginx rolled back
  12. # 查看是否回滚成功
  13. [root@linux-servertwo software]# kubectl get deployment -n nginx -o wide
  14. NAME    READY   UP-TO-DATE   AVAILABLE   AGE   CONTAINERS   IMAGES       SELECTOR
  15. nginx   3/3     3            3           75m   nginx        nginx:1.19   app=nginx
  16. # 发现又回到了更新之后的版本。
复制代码
4.9、暂停和恢复 Deployment
  1. # 暂停正在进行的更新操作:kubectl rollout pause deployment/<deployment-name>
  2. [root@linux-servertwo software]# kubectl rollout pause deployment/nginx -n nginx
  3. deployment.apps/nginx paused
  4. # 恢复暂停的更新操作:kubectl rollout resume deployment/<deployment-name>
  5. [root@linux-servertwo software]# kubectl rollout resume deployment/nginx -n nginx
  6. deployment.apps/nginx resumed
复制代码
4.10、删除 Deployment
  1. # 删除某个 Deployment:kubectl delete deployment <deployment-name>
  2. [root@linux-servertwo software]# kubectl delete deployment nginx -n nginx
  3. deployment.apps "nginx" deleted
  4. # 再次查看deployment发现已经删除
  5. [root@linux-servertwo software]#  kubectl get deployment -n nginx
  6. No resources found in nginx namespace.
  7. # 删除 deployment后,Pod也自动删除了
  8. [root@linux-servertwo software]# kubectl get pod -n nginx
  9. No resources found in nginx namespace.
复制代码
4.11、YAML创建
  1. # 输出一个yaml创建nginx的Deployment格式文件,但不运行 ,输出到主机nginx-deployment.yml文件中
  2. [root@linux-servertwo software]# kubectl create deployment nginx -n nginx --image nginx:latest --port 80 --replicas=3 --dry-run=client -o yaml > nginx-deployment.yml
  3. # 输出成功后,查看输出的yml文件
  4. [root@linux-servertwo software]# cat nginx-deployment.yml
  5. apiVersion: apps/v1
  6. kind: Deployment
  7. metadata:
  8.   creationTimestamp: null
  9.   labels:
  10.     app: nginx
  11.   name: nginx
  12.   namespace: nginx
  13. spec:
  14.   replicas: 3
  15.   selector:
  16.     matchLabels:
  17.       app: nginx
  18.   strategy: {}
  19.   template:
  20.     metadata:
  21.       creationTimestamp: null
  22.       labels:
  23.         app: nginx
  24.     spec:
  25.       containers:
  26.       - image: nginx:latest
  27.         name: nginx
  28.         ports:
  29.         - containerPort: 80
  30.         resources: {}
  31. status: {}
  32. # 运行nginx的YML文件
  33. [root@linux-servertwo software]# kubectl apply -f nginx-deployment.yml
  34. deployment.apps/nginx created
  35. # 查看是否创建成功
  36. [root@linux-servertwo software]# kubectl get deployment -n nginx -o wide
  37. NAME    READY   UP-TO-DATE   AVAILABLE   AGE     CONTAINERS   IMAGES         SELECTOR
  38. nginx   3/3     3            3           2m29s   nginx        nginx:latest   app=nginx
  39. # 查看运行的Pod
  40. [root@linux-servertwo software]# kubectl get pod -n nginx -o wide
  41. NAME                    READY   STATUS    RESTARTS   AGE     IP            NODE              NOMINATED NODE   READINESS GATES
  42. nginx-585449566-46b9w   1/1     Running   0          5m31s   172.17.0.21   linux-servertwo   <none>           <none>
  43. nginx-585449566-lcmlp   1/1     Running   0          5m31s   172.17.0.22   linux-servertwo   <none>           <none>
  44. nginx-585449566-x6rcl   1/1     Running   0          5m31s   172.17.0.20   linux-servertwo   <none>           <none>
复制代码
4.12、YAML删除
  1. # 通过  kubectl delete 命令进行删除,删除 Deployment 会自动删除与之关联的所有 Pod。
  2. [root@linux-servertwo software]# kubectl delete -f nginx-deployment.yml
  3. deployment.apps "nginx" deleted
  4. # 查看Deployment
  5. [root@linux-servertwo software]#  kubectl get deployment -n nginx
  6. No resources found in nginx namespace.
  7. # 查看Pod
  8. [root@linux-servertwo software]# kubectl get pod -n nginx
  9. No resources found in nginx namespace.
复制代码
4.13、删除指定Pod
  1. # 如果只需要删除其中一个Pod,而不删除Deployment,执行删除Pod的命令即可
  2. [root@linux-servertwo nginx]# kubectl delete pods -n nginx nginx-585449566-lcmlp
  3. pod "nginx-585449566-lcmlp" deleted
  4. # 删除其中一个后,Deployment 会根据其配置,在自动创建一个新的 Pod 来保持所需的副本数量
  5. # 再次查看运行的Pod,发现还是保持3个副本数量,但是Ip地址已经更新了。
  6. [root@linux-servertwo software]# kubectl get pod -n nginx -o wide
  7. NAME                    READY   STATUS    RESTARTS   AGE   IP            NODE              NOMINATED NODE   READINESS GATES
  8. nginx-585449566-46b9w   1/1     Running   0          5m31s 172.17.0.21   linux-servertwo   <none>           <none>
  9. nginx-585449566-krqsh   1/1     Running   0          14s   172.17.0.26   linux-servertwo   <none>           <none>
  10. nginx-585449566-x6rcl   1/1     Running   0          5m31s 172.17.0.20   linux-servertwo   <none>           <none>
复制代码
5、Service命令使用

5.1、介绍

Service 是 Kubernetes一种资源类型,它主要定义了一组Pod的访问策略,并为这些Pod提供一个稳定的固定网络地址,而无需了解这些Pod的具体 IP 地址。Service 主要用于将一组 Pod 暴露给集群内的其他服务或外部用户,使其可以通过网络与其他应用程序之间提供一个更加可靠和灵活的通信。
5.2、创建 Service

首先执行nginx-deployment.yml 文件创建一个Deployment的nginx服务,
  1. # 创建 Deployment nginx
  2. [root@linux-servertwo software]# kubectl apply -f nginx-deployment.yml
  3. deployment.apps/nginx created
  4. # 查看是否启动成功
  5. [root@linux-servertwo software]# kubectl get deployment -n nginx -o wide
  6. NAME    READY   UP-TO-DATE   AVAILABLE   AGE   CONTAINERS   IMAGES         SELECTOR
  7. nginx   3/3     3            3           33s   nginx        nginx:latest   app=nginx
  8. [root@linux-servertwo software]# kubectl get pod -n nginx -o wide
  9. NAME                    READY   STATUS    RESTARTS   AGE   IP            NODE              NOMINATED NODE   READINESS GATES
  10. nginx-585449566-5lxwx   1/1     Running   0          40s   172.17.0.29   linux-servertwo   <none>           <none>
  11. nginx-585449566-l9wvw   1/1     Running   0          40s   172.17.0.28   linux-servertwo   <none>           <none>
  12. nginx-585449566-lfjgc   1/1     Running   0          40s   172.17.0.27   linux-servertwo   <none>           <none>
复制代码
然后在进入每一个Pod的Nginx容器内部,配置一下html页面信息,方便后面查看
  1. # 进入 nginx-585449566-5lxwx 容器内部
  2. [root@linux-servertwo nginx]# kubectl exec -it -n nginx nginx-585449566-5lxwx -- bash
  3. root@nginx-585449566-6788b:/# echo this is 172.17.0.29 nginx > /usr/share/nginx/html/index.html
  4. root@nginx-585449566-6788b:/# cat /usr/share/nginx/html/index.html
  5. this is 172.17.0.29 nginx
  6. # 进入 nginx-585449566-l9wvw 容器内部
  7. [root@linux-servertwo nginx]# kubectl exec -it -n nginx nginx-585449566-l9wvw -- bash
  8. root@nginx-585449566-bhbtp:/# echo this is 172.17.0.28 nginx > /usr/share/nginx/html/index.html
  9. root@nginx-585449566-bhbtp:/#  cat /usr/share/nginx/html/index.html
  10. this is 172.17.0.28 nginx
  11. # 进入 nginx-585449566-lfjgc 容器内部
  12. [root@linux-servertwo nginx]# kubectl exec -it -n nginx nginx-585449566-lfjgc -- bash
  13. root@nginx-585449566-gk2kl:/# echo this is 172.17.0.27 nginx > /usr/share/nginx/html/index.html
  14. root@nginx-585449566-gk2kl:/# cat /usr/share/nginx/html/index.html
  15. this is 172.17.0.27 nginx
  16. # 验证访问
  17. [root@linux-servertwo software]# curl 172.17.0.29
  18. this is 172.17.0.29 nginx
  19. [root@linux-servertwo software]# curl 172.17.0.28
  20. this is 172.17.0.28 nginx
  21. [root@linux-servertwo software]# curl 172.17.0.27
  22. this is 172.17.0.27 nginx
复制代码
接下来就可以创建一个集群内部可访问的Service了
  1. # 通过以下命令创建一个内部的Service服务访问Pods
  2. # kubectl expose pod <pod-name> --name=<service-name> --port=<port> --target-port=<target-port> --type=<service-type>
  3. [root@linux-servertwo nginx]# kubectl expose deployment -n nginx nginx --name=svc-nginx --type=ClusterIP --port=80 --target-port=80
  4. service/svc-nginx exposed
  5. # type 类型:
  6. #  ClusterIP:默认类型,服务只在集群内部可访问。
  7. #  NodePort:在每个 Node 上打开一个端口,并通过该端口暴露服务。
  8. #  LoadBalancer:使用云服务提供商的负载均衡器来暴露服务,通常适用于云环境。
  9. #  ExternalName:通过 DNS 名称将外部服务映射到 Kubernetes 集群中的服务,适用于需要访问集群外部服务的情况。
复制代码
5.3、查看 Service
  1. # 查看创建的Service
  2. [root@linux-servertwo software]# kubectl get service -n nginx
  3. NAME        TYPE        CLUSTER-IP       EXTERNAL-IP   PORT(S)   AGE
  4. svc-nginx   ClusterIP   172.16.251.156   <none>        80/TCP    19s
  5. # 查看更充分的Service
  6. [root@linux-servertwo software]#  kubectl get service -n nginx -o wide
  7. NAME        TYPE        CLUSTER-IP       EXTERNAL-IP   PORT(S)   AGE   SELECTOR
  8. svc-nginx   ClusterIP   172.16.251.156   <none>        80/TCP    56s   app=nginx
  9. # ClusterIP 此类型只允许集群内访问,这里生成了一个CLUSTER-IP的IP,这就是service的IP。在Service的生命周期中,这个地址是不会变动的,可以通过这个IP访问当前service对应的Pod
  10. # 详情查看 kubectl describe service <service-name>
  11. [root@linux-servertwo software]# kubectl describe service svc-nginx -n nginx
  12. Name:              svc-nginx
  13. Namespace:         nginx
  14. Labels:            app=nginx
  15. Annotations:       <none>
  16. Selector:          app=nginx
  17. Type:              ClusterIP
  18. IP Families:       <none>
  19. IP:                172.16.251.156
  20. IPs:               172.16.251.156
  21. Port:              <unset>  80/TCP
  22. TargetPort:        80/TCP
  23. Endpoints:         172.17.0.27:80,172.17.0.28:80,172.17.0.29:80
  24. Session Affinity:  None
  25. Events:            <none>
  26. # 查看 Endpoint 信息-存储了Service对应的Pod的实际IP地址和端口信息
  27. [root@linux-servertwo software]#  kubectl get endpoints -n nginx svc-nginx
  28. NAME        ENDPOINTS                                      AGE
  29. svc-nginx   172.17.0.27:80,172.17.0.28:80,172.17.0.29:80   42m
复制代码
5.4、验证访问

通过访问CLUSTER-IP对应的IP 进行测试
  1. [root@linux-servertwo software]# curl 172.16.251.156
  2. this is 172.17.0.29 nginx
  3. [root@linux-servertwo software]# curl 172.16.251.156
  4. this is 172.17.0.28 nginx
  5. [root@linux-servertwo software]# curl 172.16.251.156
  6. this is 172.17.0.27 nginx
  7. [root@linux-servertwo software]# curl 172.16.251.156
  8. this is 172.17.0.28 nginx
  9. [root@linux-servertwo software]# curl 172.16.251.156
  10. this is 172.17.0.29 nginx
  11. [root@linux-servertwo software]# curl 172.16.251.156
  12. this is 172.17.0.29 nginx
  13. [root@linux-servertwo software]# curl 172.16.251.156
  14. this is 172.17.0.27 nginx
  15. [root@linux-servertwo software]# curl 172.16.251.156
  16. this is 172.17.0.27 nginx
  17. [root@linux-servertwo software]# curl 172.16.251.156
  18. this is 172.17.0.29 nginx
复制代码
通过以上的多次访问,可以看到 Service IP 会随机将请求转发到其中一个 Pod 上的 Nginx 中,这表明内部实现了负载均衡。这个负载均衡通过 kube-proxy  在第四层(传输层)完成的,适用于 TCP 和 UDP 流量。无论是 ClusterIP 还是 NodePort 类型的 Service,kube-proxy 都会在集群内部创建路由规则,将请求转发到后端的 Pod。当客户端请求发送到 Service 的 Cluster IP 地址时,kube-proxy 会把请求转发到一个或多个 Pod。由于这种负载均衡是在第四层(传输层)进行的, 因此不需要理解更高层次的应用协议。
5.5、kube-proxy 实现负载均衡介绍

在 Kubernetes 中,kube-proxy 使用 iptables 规则来实现 Service 的负载均衡。通过查看 iptables 规则,可以了解访问 Service 的 Cluster IP 地址时的具体链路规则。以下是具体步骤和示例:
  1. # 查看 iptables 规则
  2. # iptables-save | grep KUBE 或者 iptables -L -t nat | grep KUBE
  3. [root@linux-servertwo software]# iptables -L -t nat | grep KUBE
  4. # 只截取部署nginx的重要部分进行说明
  5. # 通过注释可以查看 /* nginx/svc-nginx */  表明这是与 nginx/svc-nginx 服务相关的流量
  6. Chain KUBE-SEP-MEC45OHITDUK5UCI (1 references)
  7. KUBE-MARK-MASQ  all  --  172.17.0.27          anywhere             /* nginx/svc-nginx */
  8. Chain KUBE-SEP-OVGUVNLN5SZ5SJPC (1 references)
  9. KUBE-MARK-MASQ  all  --  172.17.0.28          anywhere             /* nginx/svc-nginx */
  10. Chain KUBE-SEP-Q7FC6ND2772R7A3Y (1 references)
  11. KUBE-MARK-MASQ  all  --  172.17.0.29          anywhere             /* nginx/svc-nginx */
  12. # KUBE-SERVICES 链是 Kubernetes 服务暴露的入口。它是 Kubernetes 网络代理(kube-proxy)实现负载均衡的地方,可以看到IP:172.16.251.156 就是创建的nginx service的IP
  13. Chain KUBE-SERVICES (2 references)
  14. KUBE-MARK-MASQ  tcp  -- !linux-servertwo/16   172.16.251.156       /* nginx/svc-nginx cluster IP */ tcp dpt:http
  15. KUBE-SVC-XDC2TBTFGP42ST2T  tcp  --  anywhere             172.16.251.156       /* nginx/svc-nginx cluster IP */ tcp dpt:http
  16. # 通过下面可以看出,使用了 加权随机负载均衡
  17. KUBE-SEP-MEC45OHITDUK5UCI  all  --  anywhere             anywhere             /* nginx/svc-nginx */ statistic mode random probability 0.33333333349
  18. KUBE-SEP-OVGUVNLN5SZ5SJPC  all  --  anywhere             anywhere             /* nginx/svc-nginx */ statistic mode random probability 0.50000000000
  19. KUBE-SEP-Q7FC6ND2772R7A3Y  all  --  anywhere             anywhere             /* nginx/svc-nginx */
  20. # statistic mode random 是一种概率机制,表示 Kubernetes 根据给定的概率将流量随机地发送到指定的 Pod。这里的概率是:
  21. # 33% 的流量会被转发到 MEC45OHITDUK5UCI 这个 Pod。
  22. # 50% 的流量会被转发到 OVGUVNLN5SZ5SJPC 这个 Pod。
  23. #  剩余的流量会被转发到 Q7FC6ND2772R7A3Y 这个 Pod。
  24. #  结合这些规则,Kubernetes 通过随机概率来实现加权负载均衡,确保流量按照一定的比例(33%、50%)分发到不同的后端 Pod。这样的方式可以根据服务负载或者其他策略调整流量分配比例。
复制代码
5.6、创建外部可访问的Service

想要创建集群外部也可访问的Service ,只需要在创建 service 指定--type= 的类型为 NodePord 类型 即可。
  1. # 查看 Service
  2. [root@linux-servertwo software]# kubectl get service -n nginx -o wide
  3. NAME        TYPE        CLUSTER-IP       EXTERNAL-IP   PORT(S)   AGE    SELECTOR
  4. svc-nginx   ClusterIP   172.16.251.156   <none>        80/TCP    169m   app=nginx
  5. # 删除原先的 ClusterIP 类型的服务
  6. [root@linux-servertwo software]# kubectl delete service -n nginx svc-nginx
  7. service "svc-nginx" deleted
  8. # 再次查看,发现已经删除
  9. [root@linux-servertwo software]#  kubectl get service -n nginx
  10. No resources found in nginx namespace.
  11. # 创建NodePord类型的服务
  12. [root@linux-servertwo software]# kubectl expose deployment -n nginx nginx --name=svc-nginx --type=NodePort --port=80 --target-port=80
  13. service/svc-nginx exposed
  14. # 查看是否创建成功
  15. [root@linux-servertwo software]#  kubectl get service -n nginx
  16. NAME        TYPE       CLUSTER-IP       EXTERNAL-IP   PORT(S)        AGE
  17. svc-nginx   NodePort   172.16.237.241   <none>        80:31918/TCP   17s
  18. # 通过以上输出可以发现PORT(S) 属性80端口映射到31918端口了, 然后就可以通过访问31918端口在外部访问 nginx 了,访问主机IP+指定端口号31918就可以访问的随机一个 Pod 的 Nginx。使用宿主机访问31918端口:
  19. [root@linux-servertwo software]# curl localhost:31918
  20. this is 172.17.0.29 nginx
  21. [root@linux-servertwo software]# curl localhost:31918
  22. this is 172.17.0.28 nginx
  23. [root@linux-servertwo software]# curl localhost:31918
  24. this is 172.17.0.29 nginx
  25. [root@linux-servertwo software]# curl localhost:31918
  26. this is 172.17.0.27 nginx
  27. # 所以,如果是集群内部访问,可以通过 172.16.237.241:80 访问 svc-nginx。如果是集群外部访问,使用节点的 IP 地址和端口 31918 访问 svc-nginx
复制代码
5.7、删除 Service
  1. # 通过 kubectl delete service  <service-name> 进行删除
  2. [root@linux-servertwo software]# kubectl delete service -n nginx svc-nginx
  3. service "svc-nginx" deleted
  4. # 再次查看发现已经删除
  5. [root@linux-servertwo software]#  kubectl get service -n nginx
  6. No resources found in nginx namespace.
复制代码
5.8、YAML创建
  1. # 输出一个 yaml 创建 nginx 的 Service 格式文件但不运行,输出到主机nginx-service.yml文件中
  2. [root@linux-servertwo software]# kubectl expose deployment -n nginx nginx --name=svc-nginx --type=NodePort --port=80 --target-port=80 --dry-run=client -o yaml > nginx-service.yml
  3. # 输出成功后,查看输出的yml文件
  4. [root@linux-servertwo software]# cat nginx-service.yml
  5. apiVersion: v1
  6. kind: Service
  7. metadata:
  8.   creationTimestamp: null
  9.   labels:
  10.     app: nginx
  11.   name: svc-nginx
  12. spec:
  13.   ports:
  14.   - port: 80
  15.     protocol: TCP
  16.     targetPort: 80
  17.   selector:
  18.     app: nginx
  19.   type: NodePort
  20. status:
  21.   loadBalancer: {}
  22. # 在使用kubectl expose命令生成Service的YAML文件时,生成的YAML文件默认不会包含命名空间信息,需要手动在生成的YAML文件中添加命名空间。
  23. # 编辑 nginx-service.yml 文件,添加需要创建的命名空间后,再次查看
  24. [root@linux-servertwo software]# cat nginx-service.yml
  25. apiVersion: v1
  26. kind: Service
  27. metadata:
  28.   creationTimestamp: null
  29.   labels:
  30.     app: nginx
  31.   name: svc-nginx
  32.   namespace: nginx  # 添加命名空间信息
  33. spec:
  34.   ports:
  35.   - port: 80
  36.     protocol: TCP
  37.     targetPort: 80
  38.   selector:
  39.     app: nginx
  40.   type: NodePort
  41. status:
  42.   loadBalancer: {}
  43.   
  44. # 运行nginx的YML文件
  45. [root@linux-servertwo software]# kubectl apply -f nginx-service.yml
  46. service/svc-nginx created
  47. # 查看是否创建成功
  48. [root@linux-servertwo software]# kubectl get service -n nginx
  49. NAME        TYPE       CLUSTER-IP     EXTERNAL-IP   PORT(S)        AGE
  50. svc-nginx   NodePort   172.16.87.14   <none>        80:30501/TCP   17s
  51. # 验证访问
  52. # 访问内部IP+端口
  53. [root@linux-servertwo software]# curl 172.16.87.14
  54. this is 172.17.0.28 nginx
  55. [root@linux-servertwo software]# curl 172.16.87.14
  56. this is 172.17.0.29 nginx
  57. [root@linux-servertwo software]# curl 172.16.87.14
  58. this is 172.17.0.28 nginx
  59. # 访问主机节点IP+端口
  60. [root@linux-servertwo software]# curl localhost:30501
  61. this is 172.17.0.27 nginx
  62. [root@linux-servertwo software]# curl localhost:30501
  63. this is 172.17.0.28 nginx
复制代码
5.9、YAML删除
  1. # 删除
  2. [root@linux-servertwo software]# kubectl delete -f nginx-service.yml
  3. service "svc-nginx" deleted
  4. # 再次查看
  5. [root@linux-servertwo software]# kubectl get service -n nginx
  6. No resources found in nginx namespace.
复制代码
6、ipvs配置

kube-proxy 支持多种模式来实现这种负载均衡,包括:
iptables 模式:这是默认的模式,kube-proxy 使用 iptables 规则来实现 Service 到 Pod 的负载均衡。
ipvs 模式:从Kubernetes 1.8开始支持,使用 IPVS(IP Virtual Server)代替iptables来实现负载均衡,IPVS 通常被认为比iptables更高效,尤其是在高并发场景下。
  1. # 查看所有 iptables规则
  2. iptables -t nat -nL | iptables -L -v -n
  3. # k8s开启ipvs,首先查看,发现没有该命令
  4. [root@linux-servertwo software]# ipvsadm -ln
  5. -bash: ipvsadm: command not found
  6. # 安装 ipvsadm 工具
  7. yum install ipvsadm -y
  8. # 再次执行
  9. [root@linux-servertwo software]#  ipvsadm -ln
  10. IP Virtual Server version 1.2.1 (size=4096)
  11. Prot LocalAddress:Port Scheduler Flags
  12.   -> RemoteAddress:Port           Forward Weight ActiveConn InActConn
  13.   
  14. # 查看加载内核模快是否加载ipvs
  15. [root@linux-servertwo software]# lsmod | grep ip_vs
  16. ip_vs_sh               12688  0
  17. ip_vs_wrr              12697  0
  18. ip_vs_rr               12600  0
  19. ip_vs                 145458  6 ip_vs_rr,ip_vs_sh,ip_vs_wrr
  20. nf_conntrack          143411  7 ip_vs,nf_nat,nf_nat_ipv4,xt_conntrack,nf_nat_masquerade_ipv4,nf_conntrack_netlink,nf_conntrack_ipv4
  21. libcrc32c              12644  3 ip_vs,nf_nat,nf_conntrack
  22. # 由于kube-proxy默认是通过iptables来进行转发的,需要将iptables转换为ipvs(提高性能)
  23. [root@linux-servertwo software]# kubectl  edit -n kube-system  configmaps kube-proxy
  24. # 默认为空,加上 ipvs 修改成功后保存
  25. mode: "" -> mode: "ipvs"
  26. # 查看系统运行的Pod
  27. [root@linux-servertwo software]# kubectl get pod -n kube-system
  28. NAME                                      READY   STATUS    RESTARTS   AGE
  29. coredns-7f89b7bc75-47d56                  1/1     Running   0          8d
  30. coredns-7f89b7bc75-h4c9b                  1/1     Running   0          8d
  31. etcd-linux-servertwo                      1/1     Running   0          8d
  32. kube-apiserver-linux-servertwo            1/1     Running   0          8d
  33. kube-controller-manager-linux-servertwo   1/1     Running   0          7d
  34. kube-proxy-j7d4v                          1/1     Running   0          8d
  35. kube-scheduler-linux-servertwo            1/1     Running   0          7d
  36. # 删除包含 kube-proxy的Pod
  37. [root@linux-servertwo software]#  kubectl delete pod -n kube-system kube-proxy-j7d4v
  38. pod "kube-proxy-j7d4v" deleted
  39. # 删除成功后,再次查看,发现会重新创建一个新的 kube-proxy 的pod
  40. [root@linux-servertwo software]# kubectl get pod -n kube-system
  41. NAME                                      READY   STATUS    RESTARTS   AGE
  42. coredns-7f89b7bc75-47d56                  1/1     Running   0          8d
  43. coredns-7f89b7bc75-h4c9b                  1/1     Running   0          8d
  44. etcd-linux-servertwo                      1/1     Running   0          8d
  45. kube-apiserver-linux-servertwo            1/1     Running   0          8d
  46. kube-controller-manager-linux-servertwo   1/1     Running   0          7d
  47. kube-proxy-wbst6                          1/1     Running   0          16s
  48. kube-scheduler-linux-servertwo            1/1     Running   0          7d
  49. #重新查看-列出所有
  50. [root@linux-servertwo nginx]# ipvsadm -ln
  51. # 条件筛选
  52. [root@linux-servertwo software]# ipvsadm -ln | grep -A 3 "127.0.0.1:30501"
  53. TCP  127.0.0.1:30501 rr
  54.   -> 172.17.0.27:80               Masq    1      0          0         
  55.   -> 172.17.0.28:80               Masq    1      0          0         
  56.   -> 172.17.0.29:80               Masq    1      0          0   
  57. # 输出以上信息,说明使用ipvs负载均衡成功
复制代码
7、实践-部署nginx

7.1、描述

通过以上的命令介绍,已经会使用K8s部署一个简单的应用了,接下来就来通过使用Deployment+NodePort的模式 安装部署一个高可用的Nginx服务。
7.2、创建YML

创建一个 ingress-nginx.yml 文件,配置Nginx的部署信息
  1. # 1、创建 Namespace
  2. apiVersion: v1
  3. kind: Namespace
  4. metadata:
  5.   creationTimestamp: null
  6.   name: nginx-proxy
  7. spec: {}
  8. status: {}
  9. ---
  10. # 2、创建 Deployment
  11. apiVersion: apps/v1
  12. kind: Deployment
  13. metadata:
  14.   creationTimestamp: null
  15.   labels:
  16.     app: nginx-proxy
  17.   name: nginx-proxy
  18.   namespace: nginx-proxy
  19. spec:
  20.   replicas: 3
  21.   selector:
  22.     matchLabels:
  23.       app: nginx-proxy
  24.   strategy: {}
  25.   template:
  26.     metadata:
  27.       creationTimestamp: null
  28.       labels:
  29.         app: nginx-proxy
  30.     spec:
  31.       #hostNetwork: true 使用宿主机的网络接口
  32.       nodeSelector:
  33.         beta.kubernetes.io/os: linux
  34.       priorityClassName: system-node-critical
  35.       containers:
  36.       - image: nginx:1.23.1
  37.         name: nginx
  38.         imagePullPolicy: IfNotPresent
  39.         ports:
  40.         - containerPort: 80
  41.         resources:
  42.           limits:
  43.             cpu: 300m
  44.             memory: 512M
  45.           requests:
  46.             cpu: 25m
  47.             memory: 32M
  48.         volumeMounts:
  49.         - name: conf
  50.           mountPath: /etc/nginx/nginx.conf
  51.           readOnly: true     
  52.       volumes:
  53.       - name: conf
  54.         hostPath:
  55.           path: /opt/software/k8s-deployment/nginx/conf/nginx.conf         
  56. status: {}
  57. ---
  58. # 3、创建 Service
  59. apiVersion: v1
  60. kind: Service
  61. metadata:
  62.   creationTimestamp: null
  63.   labels:
  64.     app: nginx-proxy
  65.   name: svc-nginx
  66.   namespace: nginx-proxy
  67. spec:
  68.   ports:
  69.   - port: 80
  70.     protocol: TCP
  71.     targetPort: 80
  72.     nodePort: 31001
  73.   selector:
  74.     app: nginx-proxy
  75.   type: NodePort
  76. status:
  77.   loadBalancer: {}
复制代码
参数配置说明:
分隔符
  1. --- 分隔符是 Kubernetes YAML 文件中的标准语法,用于区分同一文件中的多个资源定义,使得一个文件可以包含多个资源对象。Deployment、Service 和 Namespace 是三个不同的 Kubernetes 资源定义,因此需要使用 --- 进行分隔。通过将多个资源定义写在一个 YAML 文件中,并用 --- 分隔,kubectl apply 可以一次性创建或更新多个资源,而不需要分别写多个文件或执行多次命令。
复制代码
Namespace 配置说明:
  1. # kind:Namespace 表示yaml文件创建的是命名空间
  2. # metadata 表示命名空间的元信息
  3. # metadata.name 是命名空间的名称 取值nginx
  4. # metadata.labels 是命名空间的标签 name=nginx
复制代码
Deployment 配置说明
  1. hostNetwork: true # 使用宿主机的网络接口
  2. priorityClassName: system-node-critical # 用来设置Pod优先级,确保其在集群中具有较高的优先权。
  3. # 关于 priorityClassName 优先级说明
  4. # Kubernetes 默认提供了以下几种优先级类:
  5. #   system-node-critical:关键节点服务,优先级最高。 主要作用:Pod 会在资源紧张时优先保留,不会被驱逐,确保它们在节点上保持运行。
  6. #   system-cluster-critical:集群级别的关键服务,优先级最高。确保关键组件(如控制平面组件)能够在资源不足的情况下继续运行,如 kube-apiserver、             kube-controller-manager、kube-scheduler 等
  7. #   default:普通的默认优先级类。它的优先级低于 system-node-critical 和 system-cluster-critical
  8. #   可以根据需要自定义优先级类。
  9. beta.kubernetes.io/os: linux  # 确保Pod只会在具有该标签的节点上运行,避免调度到不符合条件的节点上
复制代码
Service 配置说明
  1. # 创建 NodePort Service 时,可以指定范围为30000-32767的端口
复制代码
7.3、启动YML
  1. # 通过 kubectl apply -f 创建
  2. [root@linux-servertwo nginx]# kubectl apply -f ingress-nginx.yml
  3. namespace/nginx-proxy created
  4. deployment.apps/nginx-proxy created
  5. service/svc-nginx created
复制代码
7.4、查看
  1. # 查看命名空间
  2. [root@linux-servertwo nginx]# kubectl get namespace nginx-proxy
  3. NAME          STATUS   AGE
  4. nginx-proxy   Active   4m7s
  5. # 查看资源
  6. [root@linux-servertwo nginx]# kubectl get deploy,svc,pod -n nginx-proxy
  7. NAME                          READY   UP-TO-DATE   AVAILABLE   AGE
  8. deployment.apps/nginx-proxy   3/3     3            3           4m20s
  9. NAME                TYPE       CLUSTER-IP      EXTERNAL-IP   PORT(S)        AGE
  10. service/svc-nginx   NodePort   172.16.44.247   <none>        80:31001/TCP   4m20s
  11. NAME                               READY   STATUS    RESTARTS   AGE
  12. pod/nginx-proxy-6966ffc86c-289vk   1/1     Running   0          4m20s
  13. pod/nginx-proxy-6966ffc86c-f47vl   1/1     Running   0          4m20s
  14. pod/nginx-proxy-6966ffc86c-hqjvp   1/1     Running   0          4m20s
复制代码
7.5、验证是否成功
  1. # 查看资源详情显示IP地址
  2. [root@linux-servertwo nginx]# kubectl get deploy,svc,pod -n nginx-proxy -o wide
  3. NAME                          READY   UP-TO-DATE   AVAILABLE   AGE     CONTAINERS   IMAGES         SELECTOR
  4. deployment.apps/nginx-proxy   3/3     3            3           4m39s   nginx        nginx:1.23.1   app=nginx-proxy
  5. NAME                TYPE       CLUSTER-IP      EXTERNAL-IP   PORT(S)        AGE     SELECTOR
  6. service/svc-nginx   NodePort   172.16.44.247   <none>        80:31001/TCP   4m39s   app=nginx-proxy
  7. NAME                               READY   STATUS    RESTARTS   AGE     IP            NODE              NOMINATED NODE   READINESS GATES
  8. pod/nginx-proxy-6966ffc86c-289vk   1/1     Running   0          4m39s   172.17.0.58   linux-servertwo   <none>           <none>
  9. pod/nginx-proxy-6966ffc86c-f47vl   1/1     Running   0          4m39s   172.17.0.59   linux-servertwo   <none>           <none>
  10. pod/nginx-proxy-6966ffc86c-hqjvp   1/1     Running   0          4m39s   172.17.0.57   linux-servertwo   <none>           <none>
  11. # 查看ipvs链路规则
  12. [root@linux-servertwo nginx]# ipvsadm -ln | grep -A 3 "127.0.0.1:31001"
  13. TCP  127.0.0.1:31001 rr
  14.   -> 172.17.0.57:80               Masq    1      0          0         
  15.   -> 172.17.0.58:80               Masq    1      0          0         
  16.   -> 172.17.0.59:80               Masq    1      0          0   
  17.   
  18. # 验证负载均衡-首先进入容器内部配置html页面
  19. [root@linux-servertwo nginx]# kubectl exec -it -n nginx-proxy nginx-proxy-6966ffc86c-289vk -- bash
  20. root@nginx-proxy-6966ffc86c-289vk:/# echo this is 172.17.0.58  nginx > /usr/share/nginx/html/index.html
  21. root@nginx-proxy-6966ffc86c-289vk:/# cat /usr/share/nginx/html/index.html
  22. this is 172.17.0.58 nginx
  23. # 进入容器 172.17.0.59
  24. [root@linux-servertwo nginx]# kubectl exec -it -n nginx-proxy nginx-proxy-6966ffc86c-f47vl -- bash
  25. root@nginx-proxy-6966ffc86c-f47vl:/# echo this is 172.17.0.59  nginx > /usr/share/nginx/html/index.html
  26. root@nginx-proxy-6966ffc86c-f47vl:/# cat /usr/share/nginx/html/index.html
  27. this is 172.17.0.59 nginx
  28. # 进入容器 172.17.0.57
  29. [root@linux-servertwo nginx]# kubectl exec -it -n nginx-proxy nginx-proxy-6966ffc86c-hqjvp -- bash
  30. root@nginx-proxy-6966ffc86c-hqjvp:/# echo this is 172.17.0.57  nginx > /usr/share/nginx/html/index.html
  31. root@nginx-proxy-6966ffc86c-hqjvp:/# cat /usr/share/nginx/html/index.html
  32. this is 172.17.0.57 nginx
  33. # 访问服务service
  34. root@nginx-proxy-6966ffc86c-hqjvp:/# curl 172.16.44.247
  35. this is 172.17.0.59 nginx
  36. root@nginx-proxy-6966ffc86c-hqjvp:/# curl 172.16.44.247
  37. this is 172.17.0.58 nginx
  38. root@nginx-proxy-6966ffc86c-hqjvp:/# curl 172.16.44.247
  39. this is 172.17.0.57 nginx
  40. root@nginx-proxy-6966ffc86c-hqjvp:/# curl 172.16.44.247
  41. this is 172.17.0.59 nginx
复制代码
7.6、删除YML
  1. # 删除 ingress-nginx.yml
  2. [root@linux-servertwo nginx]# kubectl delete -f ingress-nginx.yml
  3. namespace "nginx-proxy" deleted
  4. deployment.apps "nginx-proxy" deleted
  5. service "svc-nginx" deleted
  6. # 再次查看 namespace
  7. [root@linux-servertwo nginx]# kubectl get namespace nginx-proxy
  8. Error from server (NotFound): namespaces "nginx-proxy" not found
  9. # 查看资源
  10. [root@linux-servertwo nginx]# kubectl get deploy,svc,pod -n nginx-proxy -o wide
  11. No resources found in nginx-proxy namespace.
复制代码
来源:程序园用户自行投稿发布,如果侵权,请联系站长删除
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!

相关推荐

您需要登录后才可以回帖 登录 | 立即注册