• k8s学习笔记-完整版


    文章目录

    第一章 kubernetes介绍

    本章节主要介绍应用程序在服务器上部署方式演变以及kubernetes的概念、组件和工作原理。

    应用部署方式演变

    在部署应用程序的方式上,主要经历了三个时代:

    • 传统部署:互联网早期,会直接将应用程序部署在物理机上

      优点:简单,不需要其它技术的参与

      缺点:不能为应用程序定义资源使用边界,很难合理地分配计算资源,而且程序之间容易产生影响

    • 虚拟化部署:可以在一台物理机上运行多个虚拟机,每个虚拟机都是独立的一个环境

      优点:程序环境不会相互产生影响,提供了一定程度的安全性

      缺点:增加了操作系统,浪费了部分资源

    • 容器化部署:与虚拟化类似,但是共享了操作系统

      优点:

      ​ 可以保证每个容器拥有自己的文件系统、CPU、内存、进程空间等

      ​ 运行应用程序所需要的资源都被容器包装,并和底层基础架构解耦

      ​ 容器化的应用程序可以跨云服务商、跨Linux操作系统发行版进行部署

    image-20200505183738289

    容器化部署方式给带来很多的便利,但是也会出现一些问题,比如说:

    • 一个容器故障停机了,怎么样让另外一个容器立刻启动去替补停机的容器
    • 当并发访问量变大的时候,怎么样做到横向扩展容器数量

    这些容器管理的问题统称为容器编排问题,为了解决这些容器编排问题,就产生了一些容器编排的软件:

    • Swarm:Docker自己的容器编排工具
    • Mesos:Apache的一个资源统一管控的工具,需要和Marathon结合使用
    • Kubernetes:Google开源的的容器编排工具
    image-20200524150339551

    kubernetes简介

    image-20200406232838722

    ​ kubernetes,是一个全新的基于容器技术的分布式架构领先方案,是谷歌严格保密十几年的秘密武器----Borg系统的一个开源版本,于2014年9月发布第一个版本,2015年7月发布第一个正式版本。

    ​ kubernetes的本质是一组服务器集群,它可以在集群的每个节点上运行特定的程序,来对节点中的容器进行管理。目的是实现资源管理的自动化,主要提供了如下的主要功能:

    • 自我修复:一旦某一个容器崩溃,能够在1秒中左右迅速启动新的容器
    • 弹性伸缩:可以根据需要,自动对集群中正在运行的容器数量进行调整
    • 服务发现:服务可以通过自动发现的形式找到它所依赖的服务
    • 负载均衡:如果一个服务起动了多个容器,能够自动实现请求的负载均衡
    • 版本回退:如果发现新发布的程序版本有问题,可以立即回退到原来的版本,让原来的版本运行起来
    • 存储编排:可以根据容器自身的需求自动创建存储卷

    image-20200526203726071

    kubernetes组件

    一个kubernetes集群主要是由控制节点(master)、**工作节点(node)**构成,每个节点上都会安装不同的组件。

    master:集群的控制平面,负责集群的决策 ( 管理 )

    ApiServer : 资源操作的唯一入口,接收用户输入的命令,提供认证、授权、API注册和发现等机制

    Scheduler : 负责集群资源调度,按照预定的调度策略将Pod调度到相应的node节点上

    ControllerManager : 负责维护集群的状态,比如程序部署安排、故障检测、自动扩展、滚动更新等

    **Etcd **:负责存储集群中各种资源对象的信息

    **node:集群的数据平面,负责为容器提供运行环境 ( 干活 ) **

    Kubelet : 负责维护容器的生命周期,即通过控制docker,来创建、更新、销毁容器

    KubeProxy : 负责提供集群内部的服务发现和负载均衡

    Docker : 负责节点上容器的各种操作

    image-20200406184656917

    下面,以部署一个nginx服务来说明kubernetes系统各个组件调用关系:

    1. 首先要明确,一旦kubernetes环境启动之后,master和node都会将自身的信息存储到etcd数据库中

    2. 一个nginx服务的安装请求会首先被发送到master节点的apiServer组件

    3. apiServer组件会调用scheduler组件来决定到底应该把这个服务安装到哪个node节点上

      在此时,它会从etcd中读取各个node节点的信息,然后按照一定的算法进行选择,并将结果告知apiServer

    4. apiServer调用controller-manager去调度Node节点安装nginx服务

    5. kubelet接收到指令后,会通知docker,然后由docker来启动一个nginx的pod

      pod是kubernetes的最小操作单元,容器必须跑在pod中至此,

    6. 一个nginx服务就运行了,如果需要访问nginx,就需要通过kube-proxy来对pod产生访问的代理

    ​ 这样,外界用户就可以访问集群中的nginx服务了

    kubernetes概念

    Master:集群控制节点,每个集群需要至少一个master节点负责集群的管控

    Node:工作负载节点,由master分配容器到这些node工作节点上,然后node节点上的docker负责容器的运行

    Pod:kubernetes的最小控制单元,容器都是运行在pod中的,一个pod中可以有1个或者多个容器

    Controller:控制器,通过它来实现对pod的管理,比如启动pod、停止pod、伸缩pod的数量等等

    Service:pod对外服务的统一入口,下面可以维护者同一类的多个pod

    Label:标签,用于对pod进行分类,同一类pod会拥有相同的标签

    NameSpace:命名空间,用来隔离pod的运行环境

    image-20200403224313355

    第二章 集群环境搭建

    本章节主要介绍如何搭建kubernetes的集群环境

    环境规划

    集群类型

    kubernetes集群大体上分为两类:一主多从多主多从

    • 一主多从:一台Master节点和多台Node节点,搭建简单,但是有单机故障风险,适合用于测试环境
    • 多主多从:多台Master节点和多台Node节点,搭建麻烦,安全性高,适合用于生产环境

    image-20200404094800622

    说明:为了测试简单,本次搭建的是 一主两从 类型的集群

    安装方式

    kubernetes有多种部署方式,目前主流的方式有kubeadm、minikube、二进制包

    • minikube:一个用于快速搭建单节点kubernetes的工具
    • kubeadm:一个用于快速搭建kubernetes集群的工具
    • 二进制包 :从官网下载每个组件的二进制包,依次去安装,此方式对于理解kubernetes组件更加有效

    说明:现在需要安装kubernetes的集群环境,但是又不想过于麻烦,所以选择使用kubeadm方式

    主机规划

    作用IP地址操作系统配置
    Master192.168.109.101Centos7.5 基础设施服务器2颗CPU 2G内存 50G硬盘
    Node1192.168.109.102Centos7.5 基础设施服务器2颗CPU 2G内存 50G硬盘
    Node2192.168.109.103Centos7.5 基础设施服务器2颗CPU 2G内存 50G硬盘

    环境搭建

    ​ 本次环境搭建需要安装三台Centos服务器(一主二从),然后在每台服务器中分别安装docker(18.06.3),kubeadm(1.17.4)、kubelet(1.17.4)、kubectl(1.17.4)程序。

    主机安装

    安装虚拟机过程中注意下面选项的设置:

    • 操作系统环境:CPU(2C) 内存(2G) 硬盘(50G)

    • 语言选择:中文简体

    • 软件选择:基础设施服务器

    • 分区选择:自动分区

    • 网络配置:按照下面配置网路地址信息

      网络地址:192.168.109.100  (每台主机都不一样  分别为100、101、102)
      子网掩码:255.255.255.0
      默认网关:192.168.109.2
      DNS:    223.5.5.5
      
      • 1
      • 2
      • 3
      • 4

      image-20200505213817934

    • 主机名设置:按照下面信息设置主机名

      master节点: master
      node节点:   node1
      node节点:   node2
      
      • 1
      • 2
      • 3

      image-20200505214156148

    环境初始化

    1. 检查操作系统的版本
    # 此方式下安装kubernetes集群要求Centos版本要在7.5或之上
    [root@master ~]# cat /etc/redhat-release
    CentOS Linux release 7.5.1804 (Core)
    
    • 1
    • 2
    • 3

    2) 主机名解析

    为了方便后面集群节点间的直接调用,在这配置一下主机名解析,企业中推荐使用内部DNS服务器

    # 主机名成解析 编辑三台服务器的/etc/hosts文件,添加下面内容
    192.168.109.100  master
    192.168.109.101  node1
    192.168.109.102  node2
    
    • 1
    • 2
    • 3
    • 4

    3) 时间同步

    kubernetes要求集群中的节点时间必须精确一致,这里直接使用chronyd服务从网络同步时间。

    企业中建议配置内部的时间同步服务器

    # 启动chronyd服务
    [root@master ~]# systemctl start chronyd
    # 设置chronyd服务开机自启
    [root@master ~]# systemctl enable chronyd
    # chronyd服务启动稍等几秒钟,就可以使用date命令验证时间了
    [root@master ~]# date
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    4) 禁用iptables和firewalld服务

    kubernetes和docker在运行中会产生大量的iptables规则,为了不让系统规则跟它们混淆,直接关闭系统的规则

    # 1 关闭firewalld服务
    [root@master ~]# systemctl stop firewalld
    [root@master ~]# systemctl disable firewalld
    # 2 关闭iptables服务
    [root@master ~]# systemctl stop iptables
    [root@master ~]# systemctl disable iptables
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    5) 禁用selinux

    selinux是linux系统下的一个安全服务,如果不关闭它,在安装集群中会产生各种各样的奇葩问题

    # 编辑 /etc/selinux/config 文件,修改SELINUX的值为disabled
    # 注意修改完毕之后需要重启linux服务
    SELINUX=disabled
    
    • 1
    • 2
    • 3

    6) 禁用swap分区

    swap分区指的是虚拟内存分区,它的作用是在物理内存使用完之后,将磁盘空间虚拟成内存来使用

    启用swap设备会对系统的性能产生非常负面的影响,因此kubernetes要求每个节点都要禁用swap设备

    但是如果因为某些原因确实不能关闭swap分区,就需要在集群安装过程中通过明确的参数进行配置说明

    # 编辑分区配置文件/etc/fstab,注释掉swap分区一行
    # 注意修改完毕之后需要重启linux服务
     UUID=455cc753-7a60-4c17-a424-7741728c44a1 /boot    xfs     defaults        0 0
     /dev/mapper/centos-home /home                      xfs     defaults        0 0
    # /dev/mapper/centos-swap swap                      swap    defaults        0 0
    
    • 1
    • 2
    • 3
    • 4
    • 5

    7)修改linux的内核参数

    # 修改linux的内核参数,添加网桥过滤和地址转发功能
    # 编辑/etc/sysctl.d/kubernetes.conf文件,添加如下配置:
    net.bridge.bridge-nf-call-ip6tables = 1
    net.bridge.bridge-nf-call-iptables = 1
    net.ipv4.ip_forward = 1
    
    # 重新加载配置
    [root@master ~]# sysctl -p
    
    # 加载网桥过滤模块
    [root@master ~]# modprobe br_netfilter
    
    # 查看网桥过滤模块是否加载成功
    [root@master ~]# lsmod | grep br_netfilter
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    8)配置ipvs功能

    在kubernetes中service有两种代理模型,一种是基于iptables的,一种是基于ipvs的

    两者比较的话,ipvs的性能明显要高一些,但是如果要使用它,需要手动载入ipvs模块

    # 1 安装ipset和ipvsadm
    [root@master ~]# yum install ipset ipvsadmin -y
    
    # 2 添加需要加载的模块写入脚本文件
    [root@master ~]# cat <  /etc/sysconfig/modules/ipvs.modules
    #!/bin/bash
    modprobe -- ip_vs
    modprobe -- ip_vs_rr
    modprobe -- ip_vs_wrr
    modprobe -- ip_vs_sh
    modprobe -- nf_conntrack_ipv4
    EOF
    
    # 3 为脚本文件添加执行权限
    [root@master ~]# chmod +x /etc/sysconfig/modules/ipvs.modules
    
    # 4 执行脚本文件
    [root@master ~]# /bin/bash /etc/sysconfig/modules/ipvs.modules
    
    # 5 查看对应的模块是否加载成功
    [root@master ~]# lsmod | grep -e ip_vs -e nf_conntrack_ipv4
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21

    9) 重启服务器

    上面步骤完成之后,需要重新启动linux系统

    [root@master ~]# reboot
    
    • 1

    安装docker

    # 1 切换镜像源
    [root@master ~]# wget https://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo -O /etc/yum.repos.d/docker-ce.repo
    
    # 2 查看当前镜像源中支持的docker版本
    [root@master ~]# yum list docker-ce --showduplicates
    
    # 3 安装特定版本的docker-ce
    # 必须指定--setopt=obsoletes=0,否则yum会自动安装更高版本
    [root@master ~]# yum install --setopt=obsoletes=0 docker-ce-18.06.3.ce-3.el7 -y
    
    # 4 添加一个配置文件
    # Docker在默认情况下使用的Cgroup Driver为cgroupfs,而kubernetes推荐使用systemd来代替cgroupfs
    [root@master ~]# mkdir /etc/docker
    [root@master ~]# cat <  /etc/docker/daemon.json
    {
      "exec-opts": ["native.cgroupdriver=systemd"],
      "registry-mirrors": ["https://kn0t2bca.mirror.aliyuncs.com"]
    }
    EOF
    
    # 5 启动docker
    [root@master ~]# systemctl restart docker
    [root@master ~]# systemctl enable docker
    
    # 6 检查docker状态和版本
    [root@master ~]# docker version
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26

    安装kubernetes组件

    # 由于kubernetes的镜像源在国外,速度比较慢,这里切换成国内的镜像源
    # 编辑/etc/yum.repos.d/kubernetes.repo,添加下面的配置 
    [kubernetes]
    name=Kubernetes
    baseurl=http://mirrors.aliyun.com/kubernetes/yum/repos/kubernetes-el7-x86_64
    enabled=1
    gpgcheck=0
    repo_gpgcheck=0
    gpgkey=http://mirrors.aliyun.com/kubernetes/yum/doc/yum-key.gpg
           http://mirrors.aliyun.com/kubernetes/yum/doc/rpm-package-key.gpg
    
    # 安装kubeadm、kubelet和kubectl
    [root@master ~]# yum install --setopt=obsoletes=0 kubeadm-1.17.4-0 kubelet-1.17.4-0 kubectl-1.17.4-0 -y
    
    # 配置kubelet的cgroup
    # 编辑/etc/sysconfig/kubelet,添加下面的配置
    KUBELET_CGROUP_ARGS="--cgroup-driver=systemd"
    KUBE_PROXY_MODE="ipvs"
    
    # 4 设置kubelet开机自启
    [root@master ~]# systemctl enable kubelet
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21

    准备集群镜像

    # 在安装kubernetes集群之前,必须要提前准备好集群需要的镜像,所需镜像可以通过下面命令查看
    [root@master ~]# kubeadm config images list
    
    # 下载镜像
    # 此镜像在kubernetes的仓库中,由于网络原因,无法连接,下面提供了一种替代方案
    images=(
        kube-apiserver:v1.17.4
        kube-controller-manager:v1.17.4
        kube-scheduler:v1.17.4
        kube-proxy:v1.17.4
        pause:3.1
        etcd:3.4.3-0
        coredns:1.6.5
    )
    
    for imageName in ${images[@]} ; do
    	docker pull registry.cn-hangzhou.aliyuncs.com/google_containers/$imageName
    	docker tag registry.cn-hangzhou.aliyuncs.com/google_containers/$imageName 		k8s.gcr.io/$imageName
    	docker rmi registry.cn-hangzhou.aliyuncs.com/google_containers/$imageName
    done
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20

    集群初始化

    下面开始对集群进行初始化,并将node节点加入到集群中

    下面的操作只需要在master节点上执行即可

    # 创建集群
    [root@master ~]# kubeadm init \
    	--kubernetes-version=v1.17.4 \
        --pod-network-cidr=10.244.0.0/16 \
        --service-cidr=10.96.0.0/12 \
        --apiserver-advertise-address=192.168.109.100
    
    # 创建必要文件
    [root@master ~]# mkdir -p $HOME/.kube
    [root@master ~]# sudo cp -i /etc/kubernetes/admin.conf $HOME/.kube/config
    [root@master ~]# sudo chown $(id -u):$(id -g) $HOME/.kube/config
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    下面的操作只需要在node节点上执行即可

    # 将node节点加入集群
    [root@master ~]# kubeadm join 192.168.109.100:6443 \ 
    	--token 8507uc.o0knircuri8etnw2 \
    	--discovery-token-ca-cert-hash \
    	sha256:acc37967fb5b0acf39d7598f8a439cc7dc88f439a3f4d0c9cae88e7901b9d3f
    	
    # 查看集群状态 此时的集群状态为NotReady,这是因为还没有配置网络插件
    [root@master ~]# kubectl get nodes
    NAME     STATUS     ROLES    AGE     VERSION
    master   NotReady   master   6m43s   v1.17.4
    node1    NotReady      22s     v1.17.4
    node2    NotReady      19s     v1.17.4
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    安装网络插件

    kubernetes支持多种网络插件,比如flannel、calico、canal等等,任选一种使用即可,本次选择flannel

    下面操作依旧只在master节点执行即可,插件使用的是DaemonSet的控制器,它会在每个节点上都运行

    # 获取fannel的配置文件
    [root@master ~]# wget https://raw.githubusercontent.com/coreos/flannel/master/Documentation/kube-flannel.yml
    
    # 修改文件中quay.io仓库为quay-mirror.qiniu.com
    
    # 使用配置文件启动fannel
    [root@master ~]# kubectl apply -f kube-flannel.yml
    
    # 稍等片刻,再次查看集群节点的状态
    [root@master ~]# kubectl get nodes
    NAME     STATUS   ROLES    AGE     VERSION
    master   Ready    master   15m     v1.17.4
    node1    Ready       8m53s   v1.17.4
    node2    Ready       8m50s   v1.17.4
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    至此,kubernetes的集群环境搭建完成

    服务部署

    接下来在kubernetes集群中部署一个nginx程序,测试下集群是否在正常工作。

    # 部署nginx
    [root@master ~]# kubectl create deployment nginx --image=nginx:1.14-alpine
    
    # 暴露端口
    [root@master ~]# kubectl expose deployment nginx --port=80 --type=NodePort
    
    # 查看服务状态
    [root@master ~]# kubectl get pods,service
    NAME                         READY   STATUS    RESTARTS   AGE
    pod/nginx-86c57db685-fdc2k   1/1     Running   0          18m
    
    NAME                 TYPE        CLUSTER-IP      EXTERNAL-IP   PORT(S)        AGE
    service/kubernetes   ClusterIP   10.96.0.1               443/TCP        82m
    service/nginx        NodePort    10.104.121.45           80:30073/TCP   17m
    
    # 4 最后在电脑上访问下部署的nginx服务
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    image-20200405142656921

    第三章 资源管理

    本章节主要介绍yaml语法和kubernetes的资源管理方式

    资源管理介绍

    在kubernetes中,所有的内容都抽象为资源,用户需要通过操作资源来管理kubernetes。

    ​ kubernetes的本质上就是一个集群系统,用户可以在集群中部署各种服务,所谓的部署服务,其实就是在kubernetes集群中运行一个个的容器,并将指定的程序跑在容器中。

    ​ kubernetes的最小管理单元是pod而不是容器,所以只能将容器放在Pod中,而kubernetes一般也不会直接管理Pod,而是通过Pod控制器来管理Pod的。

    ​ Pod可以提供服务之后,就要考虑如何访问Pod中服务,kubernetes提供了Service资源实现这个功能。

    ​ 当然,如果Pod中程序的数据需要持久化,kubernetes还提供了各种存储系统。

    image-20200406225334627

    学习kubernetes的核心,就是学习如何对集群上的Pod、Pod控制器、Service、存储等各种资源进行操作

    YAML语言介绍

    ​ YAML是一个类似 XML、JSON 的标记性语言。它强调以数据为中心,并不是以标识语言为重点。因而YAML本身的定义比较简单,号称"一种人性化的数据格式语言"。

    <heima>
    	<age>15age>
        <address>Beijingaddress>
    heima>
    
    • 1
    • 2
    • 3
    • 4
    heima:
      age: 15
      address: Beijing
    
    • 1
    • 2
    • 3

    YAML的语法比较简单,主要有下面几个:

    • 大小写敏感
    • 使用缩进表示层级关系
    • 缩进不允许使用tab,只允许空格( 低版本限制 )
    • 缩进的空格数不重要,只要相同层级的元素左对齐即可
    • '#'表示注释

    YAML支持以下几种数据类型:

    • 纯量:单个的、不可再分的值
    • 对象:键值对的集合,又称为映射(mapping)/ 哈希(hash) / 字典(dictionary)
    • 数组:一组按次序排列的值,又称为序列(sequence) / 列表(list)
    # 纯量, 就是指的一个简单的值,字符串、布尔值、整数、浮点数、Null、时间、日期
    # 1 布尔类型
    c1: true (或者True)
    # 2 整型
    c2: 234
    # 3 浮点型
    c3: 3.14
    # 4 null类型 
    c4: ~  # 使用~表示null
    # 5 日期类型
    c5: 2018-02-17    # 日期必须使用ISO 8601格式,即yyyy-MM-dd
    # 6 时间类型
    c6: 2018-02-17T15:02:31+08:00  # 时间使用ISO 8601格式,时间和日期之间使用T连接,最后使用+代表时区
    # 7 字符串类型
    c7: heima     # 简单写法,直接写值 , 如果字符串中间有特殊字符,必须使用双引号或者单引号包裹 
    c8: line1
        line2     # 字符串过多的情况可以拆成多行,每一行会被转化成一个空格
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    # 对象
    # 形式一(推荐):
    heima:
      age: 15
      address: Beijing
    # 形式二(了解):
    heima: {age: 15,address: Beijing}
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    # 数组
    # 形式一(推荐):
    address:
      - 顺义
      - 昌平	
    # 形式二(了解):
    address: [顺义,昌平]
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    小提示:

    ​ 1 书写yaml切记: 后面要加一个空格

    ​ 2 如果需要将多段yaml配置放在一个文件中,中间要使用---分隔

    ​ 3 下面是一个yaml转json的网站,可以通过它验证yaml是否书写正确

    ​ https://www.json2yaml.com/convert-yaml-to-json

    资源管理方式

    • 命令式对象管理:直接使用命令去操作kubernetes资源

      kubectl run nginx-pod --image=nginx:1.17.1 --port=80

    • 命令式对象配置:通过命令配置和配置文件去操作kubernetes资源

      kubectl create/patch -f nginx-pod.yaml

    • 声明式对象配置:通过apply命令和配置文件去操作kubernetes资源

      kubectl apply -f nginx-pod.yaml

    类型操作对象适用环境优点缺点
    命令式对象管理对象测试简单只能操作活动对象,无法审计、跟踪
    命令式对象配置文件开发可以审计、跟踪项目大时,配置文件多,操作麻烦
    声明式对象配置目录开发支持目录操作意外情况下难以调试

    命令式对象管理

    kubectl命令

    ​ kubectl是kubernetes集群的命令行工具,通过它能够对集群本身进行管理,并能够在集群上进行容器化应用的安装部署。kubectl命令的语法如下:

    kubectl [command] [type] [name] [flags]
    
    • 1

    comand:指定要对资源执行的操作,例如create、get、delete

    type:指定资源类型,比如deployment、pod、service

    name:指定资源的名称,名称大小写敏感

    flags:指定额外的可选参数

    # 查看所有pod
    kubectl get pod 
    
    # 查看某个pod
    kubectl get pod pod_name
    
    # 查看某个pod,以yaml格式展示结果
    kubectl get pod pod_name -o yaml
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    资源类型

    kubernetes中所有的内容都抽象为资源,可以通过下面的命令进行查看:

    kubectl api-resources
    
    • 1

    经常使用的资源有下面这些:

    资源分类资源名称缩写资源作用
    集群级别资源nodesno集群组成部分
    namespacesns隔离Pod
    pod资源podspo装载容器
    pod资源控制器replicationcontrollersrc控制pod资源
    replicasetsrs控制pod资源
    deploymentsdeploy控制pod资源
    daemonsetsds控制pod资源
    jobs控制pod资源
    cronjobscj控制pod资源
    horizontalpodautoscalershpa控制pod资源
    statefulsetssts控制pod资源
    服务发现资源servicessvc统一pod对外接口
    ingressing统一pod对外接口
    存储资源volumeattachments存储
    persistentvolumespv存储
    persistentvolumeclaimspvc存储
    配置资源configmapscm配置
    secrets配置

    操作

    kubernetes允许对资源进行多种操作,可以通过–help查看详细的操作命令

    kubectl --help
    
    • 1

    经常使用的操作有下面这些:

    命令分类命令翻译命令作用
    基本命令create创建创建一个资源
    edit编辑编辑一个资源
    get获取获取一个资源
    patch更新更新一个资源
    delete删除删除一个资源
    explain解释展示资源文档
    运行和调试run运行在集群中运行一个指定的镜像
    expose暴露暴露资源为Service
    describe描述显示资源内部信息
    logs日志输出容器在 pod 中的日志
    attach缠绕进入运行中的容器
    exec执行执行容器中的一个命令
    cp复制在Pod内外复制文件
    rollout首次展示管理资源的发布
    scale规模扩(缩)容Pod的数量
    autoscale自动调整自动调整Pod的数量
    高级命令applyrc通过文件对资源进行配置
    label标签更新资源上的标签
    其他命令cluster-info集群信息显示集群信息
    version版本显示当前Server和Client的版本

    下面以一个namespace / pod的创建和删除简单演示下命令的使用:

    # 创建一个namespace
    [root@master ~]# kubectl create namespace dev
    namespace/dev created
    
    # 获取namespace
    [root@master ~]# kubectl get ns
    NAME              STATUS   AGE
    default           Active   21h
    dev               Active   21s
    kube-node-lease   Active   21h
    kube-public       Active   21h
    kube-system       Active   21h
    
    # 在此namespace下创建并运行一个nginx的Pod
    [root@master ~]# kubectl run pod --image=nginx -n dev
    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/pod created
    
    # 查看新创建的pod
    [root@master ~]# kubectl get pod -n dev
    NAME                   READY   STATUS    RESTARTS   AGE
    pod-864f9875b9-pcw7x   1/1     Running   0          21s
    
    # 删除指定的pod
    [root@master ~]# kubectl delete pod pod-864f9875b9-pcw7x
    pod "pod-864f9875b9-pcw7x" deleted
    
    # 删除指定的namespace
    [root@master ~]# kubectl delete ns dev
    namespace "dev" deleted
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30

    命令式对象配置

    命令式对象配置就是使用命令配合配置文件一起来操作kubernetes资源。

    1) 创建一个nginxpod.yaml,内容如下:

    apiVersion: v1
    kind: Namespace
    metadata:
      name: dev
    
    ---
    
    apiVersion: v1
    kind: Pod
    metadata:
      name: nginxpod
      namespace: dev
    spec:
      containers:
      - name: nginx-containers
        image: nginx:1.17.1
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    2)执行create命令,创建资源:

    [root@master ~]# kubectl create -f nginxpod.yaml
    namespace/dev created
    pod/nginxpod created
    
    • 1
    • 2
    • 3

    此时发现创建了两个资源对象,分别是namespace和pod

    3)执行get命令,查看资源:

    [root@master ~]#  kubectl get -f nginxpod.yaml
    NAME            STATUS   AGE
    namespace/dev   Active   18s
    
    NAME            READY   STATUS    RESTARTS   AGE
    pod/nginxpod    1/1     Running   0          17s
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    这样就显示了两个资源对象的信息

    4)执行delete命令,删除资源:

    [root@master ~]# kubectl delete -f nginxpod.yaml
    namespace "dev" deleted
    pod "nginxpod" deleted
    
    • 1
    • 2
    • 3

    此时发现两个资源对象被删除了

    总结:
    	命令式对象配置的方式操作资源,可以简单的认为:命令  +  yaml配置文件(里面是命令需要的各种参数)
    
    • 1
    • 2

    声明式对象配置

    声明式对象配置跟命令式对象配置很相似,但是它只有一个命令apply。

    # 首先执行一次kubectl apply -f yaml文件,发现创建了资源
    [root@master ~]#  kubectl apply -f nginxpod.yaml
    namespace/dev created
    pod/nginxpod created
    
    # 再次执行一次kubectl apply -f yaml文件,发现说资源没有变动
    [root@master ~]#  kubectl apply -f nginxpod.yaml
    namespace/dev unchanged
    pod/nginxpod unchanged
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    总结:
        其实声明式对象配置就是使用apply描述一个资源最终的状态(在yaml中定义状态)
    	使用apply操作资源:
            如果资源不存在,就创建,相当于 kubectl create
    		如果资源已存在,就更新,相当于 kubectl patch
    
    • 1
    • 2
    • 3
    • 4
    • 5

    扩展:kubectl可以在node节点上运行吗 ?

    ​ kubectl的运行是需要进行配置的,它的配置文件是$HOME/.kube,如果想要在node节点运行此命令,需要将master上的.kube文件复制到node节点上,即在master节点上执行下面操作:

    scp  -r  HOME/.kube   node1: HOME/
    
    • 1

    使用推荐: 三种方式应该怎么用 ?

    创建/更新资源 使用声明式对象配置 kubectl apply -f XXX.yaml

    删除资源 使用命令式对象配置 kubectl delete -f XXX.yaml

    查询资源 使用命令式对象管理 kubectl get(describe) 资源名称

    第四章 实战入门

    本章节将介绍如何在kubernetes集群中部署一个nginx服务,并且能够对其进行访问。

    Namespace

    ​ Namespace是kubernetes系统中的一种非常重要资源,它的主要作用是用来实现多套环境的资源隔离或者多租户的资源隔离

    ​ 默认情况下,kubernetes集群中的所有的Pod都是可以相互访问的。但是在实际中,可能不想让两个Pod之间进行互相的访问,那此时就可以将两个Pod划分到不同的namespace下。kubernetes通过将集群内部的资源分配到不同的Namespace中,可以形成逻辑上的"组",以方便不同的组的资源进行隔离使用和管理。

    ​ 可以通过kubernetes的授权机制,将不同的namespace交给不同租户进行管理,这样就实现了多租户的资源隔离。此时还能结合kubernetes的资源配额机制,限定不同租户能占用的资源,例如CPU使用量、内存使用量等等,来实现租户可用资源的管理。

    image-20200407100850484

    kubernetes在集群启动之后,会默认创建几个namespace

    [root@master ~]# kubectl  get namespace
    NAME              STATUS   AGE
    default           Active   45h     #  所有未指定Namespace的对象都会被分配在default命名空间
    kube-node-lease   Active   45h     #  集群节点之间的心跳维护,v1.13开始引入
    kube-public       Active   45h     #  此命名空间下的资源可以被所有人访问(包括未认证用户)
    kube-system       Active   45h     #  所有由Kubernetes系统创建的资源都处于这个命名空间
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    下面来看namespace资源的具体操作:

    查看

    # 1 查看所有的ns  命令:kubectl get ns
    [root@master ~]# kubectl get ns
    NAME              STATUS   AGE
    default           Active   45h
    kube-node-lease   Active   45h
    kube-public       Active   45h     
    kube-system       Active   45h     
    
    # 2 查看指定的ns   命令:kubectl get ns ns名称
    [root@master ~]# kubectl get ns default
    NAME      STATUS   AGE
    default   Active   45h
    
    # 3 指定输出格式  命令:kubectl get ns ns名称  -o 格式参数
    # kubernetes支持的格式有很多,比较常见的是wide、json、yaml
    [root@master ~]# kubectl get ns default -o yaml
    apiVersion: v1
    kind: Namespace
    metadata:
      creationTimestamp: "2020-04-05T04:44:16Z"
      name: default
      resourceVersion: "151"
      selfLink: /api/v1/namespaces/default
      uid: 7405f73a-e486-43d4-9db6-145f1409f090
    spec:
      finalizers:
      - kubernetes
    status:
      phase: Active
      
    # 4 查看ns详情  命令:kubectl describe ns ns名称
    [root@master ~]# kubectl describe ns default
    Name:         default
    Labels:       
    Annotations:  
    Status:       Active  # Active 命名空间正在使用中  Terminating 正在删除命名空间
    
    # ResourceQuota 针对namespace做的资源限制
    # LimitRange针对namespace中的每个组件做的资源限制
    No resource quota.
    No LimitRange resource.
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41

    创建

    # 创建namespace
    [root@master ~]# kubectl create ns dev
    namespace/dev created
    
    • 1
    • 2
    • 3

    删除

    # 删除namespace
    [root@master ~]# kubectl delete ns dev
    namespace "dev" deleted
    
    • 1
    • 2
    • 3

    配置方式

    首先准备一个yaml文件:ns-dev.yaml

    apiVersion: v1
    kind: Namespace
    metadata:
      name: dev
    
    • 1
    • 2
    • 3
    • 4

    然后就可以执行对应的创建和删除命令了:

    ​ 创建:kubectl create -f ns-dev.yaml

    ​ 删除:kubectl delete -f ns-dev.yaml

    Pod

    Pod是kubernetes集群进行管理的最小单元,程序要运行必须部署在容器中,而容器必须存在于Pod中。

    Pod可以认为是容器的封装,一个Pod中可以存在一个或者多个容器。

    image-20200407121501907

    kubernetes在集群启动之后,集群中的各个组件也都是以Pod方式运行的。可以通过下面命令查看:

    [root@master ~]# kubectl get pod -n kube-system
    NAMESPACE     NAME                             READY   STATUS    RESTARTS   AGE
    kube-system   coredns-6955765f44-68g6v         1/1     Running   0          2d1h
    kube-system   coredns-6955765f44-cs5r8         1/1     Running   0          2d1h
    kube-system   etcd-master                      1/1     Running   0          2d1h
    kube-system   kube-apiserver-master            1/1     Running   0          2d1h
    kube-system   kube-controller-manager-master   1/1     Running   0          2d1h
    kube-system   kube-flannel-ds-amd64-47r25      1/1     Running   0          2d1h
    kube-system   kube-flannel-ds-amd64-ls5lh      1/1     Running   0          2d1h
    kube-system   kube-proxy-685tk                 1/1     Running   0          2d1h
    kube-system   kube-proxy-87spt                 1/1     Running   0          2d1h
    kube-system   kube-scheduler-master            1/1     Running   0          2d1h
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    创建并运行

    kubernetes没有提供单独运行Pod的命令,都是通过Pod控制器来实现的

    # 命令格式: kubectl run (pod控制器名称) [参数] 
    # --image  指定Pod的镜像
    # --port   指定端口
    # --namespace  指定namespace
    [root@master ~]# kubectl run nginx --image=nginx:1.17.1 --port=80 --namespace dev 
    deployment.apps/nginx created
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    查看pod信息

    # 查看Pod基本信息
    [root@master ~]# kubectl get pods -n dev
    NAME                     READY   STATUS    RESTARTS   AGE
    nginx-5ff7956ff6-fg2db   1/1     Running   0          43s
    
    # 查看Pod的详细信息
    [root@master ~]# kubectl describe pod nginx-5ff7956ff6-fg2db -n dev
    Name:         nginx-5ff7956ff6-fg2db
    Namespace:    dev
    Priority:     0
    Node:         node1/192.168.109.101
    Start Time:   Wed, 08 Apr 2020 09:29:24 +0800
    Labels:       pod-template-hash=5ff7956ff6
                  run=nginx
    Annotations:  
    Status:       Running
    IP:           10.244.1.23
    IPs:
      IP:           10.244.1.23
    Controlled By:  ReplicaSet/nginx-5ff7956ff6
    Containers:
      nginx:
        Container ID:   docker://4c62b8c0648d2512380f4ffa5da2c99d16e05634979973449c98e9b829f6253c
        Image:          nginx:1.17.1
        Image ID:       docker-pullable://nginx@sha256:485b610fefec7ff6c463ced9623314a04ed67e3945b9c08d7e53a47f6d108dc7
        Port:           80/TCP
        Host Port:      0/TCP
        State:          Running
          Started:      Wed, 08 Apr 2020 09:30:01 +0800
        Ready:          True
        Restart Count:  0
        Environment:    
        Mounts:
          /var/run/secrets/kubernetes.io/serviceaccount from default-token-hwvvw (ro)
    Conditions:
      Type              Status
      Initialized       True
      Ready             True
      ContainersReady   True
      PodScheduled      True
    Volumes:
      default-token-hwvvw:
        Type:        Secret (a volume populated by a Secret)
        SecretName:  default-token-hwvvw
        Optional:    false
    QoS Class:       BestEffort
    Node-Selectors:  
    Tolerations:     node.kubernetes.io/not-ready:NoExecute for 300s
                     node.kubernetes.io/unreachable:NoExecute for 300s
    Events:
      Type    Reason     Age        From               Message
      ----    ------     ----       ----               -------
      Normal  Scheduled    default-scheduler  Successfully assigned dev/nginx-5ff7956ff6-fg2db to node1
      Normal  Pulling    4m11s      kubelet, node1     Pulling image "nginx:1.17.1"
      Normal  Pulled     3m36s      kubelet, node1     Successfully pulled image "nginx:1.17.1"
      Normal  Created    3m36s      kubelet, node1     Created container nginx
      Normal  Started    3m36s      kubelet, node1     Started container nginx
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57

    访问Pod

    # 获取podIP
    [root@master ~]# kubectl get pods -n dev -o wide
    NAME                     READY   STATUS    RESTARTS   AGE    IP             NODE    ... 
    nginx-5ff7956ff6-fg2db   1/1     Running   0          190s   10.244.1.23   node1   ...
    
    #访问POD
    [root@master ~]# curl http://10.244.1.23:80
    <!DOCTYPE html>
    
    
    	Welcome to nginx!<<span class="token operator">/</span>title>
    <<span class="token operator">/</span>head>
    <body>
    	<p><em>Thank you <span class="token keyword">for</span> <span class="token keyword">using</span> nginx<span class="token punctuation">.</span><<span class="token operator">/</span>em><<span class="token operator">/</span>p>
    <<span class="token operator">/</span>body>
    <<span class="token operator">/</span>html>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><div class="hide-preCode-box"><span class="hide-preCode-bt" data-report-view="{"spm":"1001.2101.3001.7365"}"><img class="look-more-preCode contentImg-no-view" src="https://1000bd.com/contentImg/2022/06/27/191644837.png" alt="" title=""></span></div><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li><li style="color: rgb(153, 153, 153);">2</li><li style="color: rgb(153, 153, 153);">3</li><li style="color: rgb(153, 153, 153);">4</li><li style="color: rgb(153, 153, 153);">5</li><li style="color: rgb(153, 153, 153);">6</li><li style="color: rgb(153, 153, 153);">7</li><li style="color: rgb(153, 153, 153);">8</li><li style="color: rgb(153, 153, 153);">9</li><li style="color: rgb(153, 153, 153);">10</li><li style="color: rgb(153, 153, 153);">11</li><li style="color: rgb(153, 153, 153);">12</li><li style="color: rgb(153, 153, 153);">13</li><li style="color: rgb(153, 153, 153);">14</li><li style="color: rgb(153, 153, 153);">15</li><li style="color: rgb(153, 153, 153);">16</li></ul></pre> 
    <p><strong>删除指定Pod</strong></p> 
    <pre data-index="45" class="set-code-hide prettyprint"><code class="prism language-powershell has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token comment"># 删除指定Pod</span>
    <span class="token namespace">[root@master ~]</span><span class="token comment"># kubectl delete pod nginx-5ff7956ff6-fg2db -n dev</span>
    pod <span class="token string">"nginx-5ff7956ff6-fg2db"</span> deleted
    
    <span class="token comment"># 此时,显示删除Pod成功,但是再查询,发现又新产生了一个 </span>
    <span class="token namespace">[root@master ~]</span><span class="token comment"># kubectl get pods -n dev</span>
    NAME                     READY   STATUS    RESTARTS   AGE
    nginx-5ff7956ff6-jj4ng   1/1     Running   0          21s
    
    <span class="token comment"># 这是因为当前Pod是由Pod控制器创建的,控制器会监控Pod状况,一旦发现Pod死亡,会立即重建</span>
    <span class="token comment"># 此时要想删除Pod,必须删除Pod控制器</span>
    
    <span class="token comment"># 先来查询一下当前namespace下的Pod控制器</span>
    <span class="token namespace">[root@master ~]</span><span class="token comment"># kubectl get deploy -n  dev</span>
    NAME    READY   UP-TO-DATE   AVAILABLE   AGE
    nginx   1/1     1            1           9m7s
    
    <span class="token comment"># 接下来,删除此PodPod控制器</span>
    <span class="token namespace">[root@master ~]</span><span class="token comment"># kubectl delete deploy nginx -n dev</span>
    deployment<span class="token punctuation">.</span>apps <span class="token string">"nginx"</span> deleted
    
    <span class="token comment"># 稍等片刻,再查询Pod,发现Pod被删除了</span>
    <span class="token namespace">[root@master ~]</span><span class="token comment"># kubectl get pods -n dev</span>
    No resources found in dev namespace<span class="token punctuation">.</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><div class="hide-preCode-box"><span class="hide-preCode-bt" data-report-view="{"spm":"1001.2101.3001.7365"}"><img class="look-more-preCode contentImg-no-view" src="https://1000bd.com/contentImg/2022/06/27/191644837.png" alt="" title=""></span></div><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li><li style="color: rgb(153, 153, 153);">2</li><li style="color: rgb(153, 153, 153);">3</li><li style="color: rgb(153, 153, 153);">4</li><li style="color: rgb(153, 153, 153);">5</li><li style="color: rgb(153, 153, 153);">6</li><li style="color: rgb(153, 153, 153);">7</li><li style="color: rgb(153, 153, 153);">8</li><li style="color: rgb(153, 153, 153);">9</li><li style="color: rgb(153, 153, 153);">10</li><li style="color: rgb(153, 153, 153);">11</li><li style="color: rgb(153, 153, 153);">12</li><li style="color: rgb(153, 153, 153);">13</li><li style="color: rgb(153, 153, 153);">14</li><li style="color: rgb(153, 153, 153);">15</li><li style="color: rgb(153, 153, 153);">16</li><li style="color: rgb(153, 153, 153);">17</li><li style="color: rgb(153, 153, 153);">18</li><li style="color: rgb(153, 153, 153);">19</li><li style="color: rgb(153, 153, 153);">20</li><li style="color: rgb(153, 153, 153);">21</li><li style="color: rgb(153, 153, 153);">22</li><li style="color: rgb(153, 153, 153);">23</li><li style="color: rgb(153, 153, 153);">24</li></ul></pre> 
    <p><strong>配置操作</strong></p> 
    <p>创建一个pod-nginx.yaml,内容如下:</p> 
    <pre data-index="46" class="set-code-show prettyprint"><code class="prism language-yaml has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token key atrule">apiVersion</span><span class="token punctuation">:</span> v1
    <span class="token key atrule">kind</span><span class="token punctuation">:</span> Pod
    <span class="token key atrule">metadata</span><span class="token punctuation">:</span>
      <span class="token key atrule">name</span><span class="token punctuation">:</span> nginx
      <span class="token key atrule">namespace</span><span class="token punctuation">:</span> dev
    <span class="token key atrule">spec</span><span class="token punctuation">:</span>
      <span class="token key atrule">containers</span><span class="token punctuation">:</span>
      <span class="token punctuation">-</span> <span class="token key atrule">image</span><span class="token punctuation">:</span> nginx<span class="token punctuation">:</span>1.17.1
        <span class="token key atrule">name</span><span class="token punctuation">:</span> pod
        <span class="token key atrule">ports</span><span class="token punctuation">:</span>
        <span class="token punctuation">-</span> <span class="token key atrule">name</span><span class="token punctuation">:</span> nginx<span class="token punctuation">-</span>port
          <span class="token key atrule">containerPort</span><span class="token punctuation">:</span> <span class="token number">80</span>
          <span class="token key atrule">protocol</span><span class="token punctuation">:</span> TCP
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li><li style="color: rgb(153, 153, 153);">2</li><li style="color: rgb(153, 153, 153);">3</li><li style="color: rgb(153, 153, 153);">4</li><li style="color: rgb(153, 153, 153);">5</li><li style="color: rgb(153, 153, 153);">6</li><li style="color: rgb(153, 153, 153);">7</li><li style="color: rgb(153, 153, 153);">8</li><li style="color: rgb(153, 153, 153);">9</li><li style="color: rgb(153, 153, 153);">10</li><li style="color: rgb(153, 153, 153);">11</li><li style="color: rgb(153, 153, 153);">12</li><li style="color: rgb(153, 153, 153);">13</li></ul></pre> 
    <p>然后就可以执行对应的创建和删除命令了:</p> 
    <p>​ 创建:kubectl create -f pod-nginx.yaml</p> 
    <p>​ 删除:kubectl delete -f pod-nginx.yaml</p> 
    <h3><a name="t30"></a><a id="Label_1316"></a>Label</h3> 
    <p>Label是kubernetes系统中的一个重要概念。它的作用就是在资源上添加标识,用来对它们进行区分和选择。</p> 
    <p>Label的特点:</p> 
    <ul><li>一个Label会以key/value键值对的形式附加到各种对象上,如Node、Pod、Service等等</li><li>一个资源对象可以定义任意数量的Label ,同一个Label也可以被添加到任意数量的资源对象上去</li><li>Label通常在资源对象定义时确定,当然也可以在对象创建后动态添加或者删除</li></ul> 
    <p>可以通过Label实现资源的多维度分组,以便灵活、方便地进行资源分配、调度、配置、部署等管理工作。</p> 
    <blockquote> 
     <p>一些常用的Label 示例如下:</p> 
     <ul><li>版本标签:“version”:“release”, “version”:“stable”…</li><li>环境标签:“environment”:“dev”,“environment”:“test”,“environment”:“pro”</li><li>架构标签:“tier”:“frontend”,“tier”:“backend”</li></ul> 
    </blockquote> 
    <p>标签定义完毕之后,还要考虑到标签的选择,这就要使用到Label Selector,即:</p> 
    <p>​ Label用于给某个资源对象定义标识</p> 
    <p>​ Label Selector用于查询和筛选拥有某些标签的资源对象</p> 
    <p>当前有两种Label Selector:</p> 
    <ul><li> <p>基于等式的Label Selector</p> <p>name = slave: 选择所有包含Label中key="name"且value="slave"的对象</p> <p>env != production: 选择所有包括Label中的key="env"且value不等于"production"的对象</p> </li><li> <p>基于集合的Label Selector</p> <p>name in (master, slave): 选择所有包含Label中的key="name"且value="master"或"slave"的对象</p> <p>name not in (frontend): 选择所有包含Label中的key="name"且value不等于"frontend"的对象</p> </li></ul> 
    <p>标签的选择条件可以使用多个,此时将多个Label Selector进行组合,使用逗号","进行分隔即可。例如:</p> 
    <p>​ name=slave,env!=production</p> 
    <p>​ name not in (frontend),env!=production</p> 
    <p><strong>命令方式</strong></p> 
    <pre data-index="47" class="set-code-show prettyprint"><code class="prism language-powershell has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token comment"># 为pod资源打标签[root@master ~]# kubectl label pod nginx-pod version=1.0 -n devpod/nginx-pod labeled# 为pod资源更新标签[root@master ~]# kubectl label pod nginx-pod version=2.0 -n dev --overwritepod/nginx-pod labeled# 查看标签[root@master ~]# kubectl get pod nginx-pod  -n dev --show-labelsNAME        READY   STATUS    RESTARTS   AGE   LABELSnginx-pod   1/1     Running   0          10m   version=2.0# 筛选标签[root@master ~]# kubectl get pod -n dev -l version=2.0  --show-labelsNAME        READY   STATUS    RESTARTS   AGE   LABELSnginx-pod   1/1     Running   0          17m   version=2.0[root@master ~]# kubectl get pod -n dev -l version!=2.0 --show-labelsNo resources found in dev namespace.#删除标签[root@master ~]# kubectl label pod nginx-pod version- -n devpod/nginx-pod labeled</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <p><strong>配置方式</strong></p> 
    <pre data-index="48" class="set-code-show prettyprint"><code class="prism language-yaml has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token key atrule">apiVersion</span><span class="token punctuation">:</span> <span class="token key atrule">v1kind</span><span class="token punctuation">:</span> <span class="token key atrule">Podmetadata</span><span class="token punctuation">:</span>  <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">nginx  namespace</span><span class="token punctuation">:</span> <span class="token key atrule">dev  labels</span><span class="token punctuation">:</span>    <span class="token key atrule">version</span><span class="token punctuation">:</span> "3.0"     env<span class="token punctuation">:</span> "test"spec<span class="token punctuation">:</span>  <span class="token key atrule">containers</span><span class="token punctuation">:</span>  <span class="token punctuation">-</span> <span class="token key atrule">image</span><span class="token punctuation">:</span> <span class="token key atrule">nginx:1.17.1    name</span><span class="token punctuation">:</span> <span class="token key atrule">pod    ports</span><span class="token punctuation">:</span>    <span class="token punctuation">-</span> <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">nginx-port      containerPort</span><span class="token punctuation">:</span> <span class="token key atrule">80      protocol</span><span class="token punctuation">:</span> TCP
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <p>然后就可以执行对应的更新命令了:kubectl apply -f pod-nginx.yaml</p> 
    <h3><a name="t31"></a><a id="Deployment_1374"></a>Deployment</h3> 
    <p>​ 在kubernetes中,Pod是最小的控制单元,但是kubernetes很少直接控制Pod,一般都是通过Pod控制器来完成的。Pod控制器用于pod的管理,确保pod资源符合预期的状态,当pod的资源出现故障时,会尝试进行重启或重建pod。</p> 
    <p>​ 在kubernetes中Pod控制器的种类有很多,本章节只介绍一种:Deployment。</p> 
    <img src="https://1000bd.com/contentImg/2024/04/15/4a8b916908fa4570.png" alt="image-20200408193950807"> 
    <p><strong>命令操作</strong></p> 
    <pre data-index="49" class="set-code-hide prettyprint"><code class="prism language-powershell has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token comment"># 命令格式: kubectl run deployment名称  [参数] </span>
    <span class="token comment"># --image  指定pod的镜像</span>
    <span class="token comment"># --port   指定端口</span>
    <span class="token comment"># --replicas  指定创建pod数量</span>
    <span class="token comment"># --namespace  指定namespace</span>
    <span class="token namespace">[root@master ~]</span><span class="token comment"># kubectl run nginx --image=nginx:1.17.1 --port=80 --replicas=3 -n dev</span>
    deployment<span class="token punctuation">.</span>apps/nginx created
    
    <span class="token comment"># 查看创建的Pod</span>
    <span class="token namespace">[root@master ~]</span><span class="token comment"># kubectl get pods -n dev</span>
    NAME                     READY   STATUS    RESTARTS   AGE
    nginx-5ff7956ff6-6k8cb   1/1     Running   0          19s
    nginx-5ff7956ff6-jxfjt   1/1     Running   0          19s
    nginx-5ff7956ff6-v6jqw   1/1     Running   0          19s
    
    <span class="token comment"># 查看deployment的信息</span>
    <span class="token namespace">[root@master ~]</span><span class="token comment"># kubectl get deploy -n dev</span>
    NAME    READY   UP-TO-DATE   AVAILABLE   AGE
    nginx   3/3     3            3           2m42s
    
    <span class="token comment"># UP-TO-DATE:成功升级的副本数量</span>
    <span class="token comment"># AVAILABLE:可用副本的数量</span>
    <span class="token namespace">[root@master ~]</span><span class="token comment"># kubectl get deploy -n dev -o wide</span>
    NAME    READY UP-TO-DATE  AVAILABLE   AGE     CONTAINERS   IMAGES              SELECTOR
    nginx   3/3     3         3           2m51s   nginx        nginx:1<span class="token punctuation">.</span>17<span class="token punctuation">.</span>1        run=nginx
    
    <span class="token comment"># 查看deployment的详细信息</span>
    <span class="token namespace">[root@master ~]</span><span class="token comment"># kubectl describe deploy nginx -n dev</span>
    Name:                   nginx
    Namespace:              dev
    CreationTimestamp:      Wed<span class="token punctuation">,</span> 08 Apr 2020 11:14:14 <span class="token operator">+</span>0800
    Labels:                 run=nginx
    Annotations:            deployment<span class="token punctuation">.</span>kubernetes<span class="token punctuation">.</span>io/revision: 1
    Selector:               run=nginx
    Replicas:               3 desired <span class="token punctuation">|</span> 3 updated <span class="token punctuation">|</span> 3 total <span class="token punctuation">|</span> 3 available <span class="token punctuation">|</span> 0 unavailable
    StrategyType:           RollingUpdate
    MinReadySeconds:        0
    RollingUpdateStrategy:  25% max unavailable<span class="token punctuation">,</span> 25% max surge
    Pod Template:
      Labels:  run=nginx
      Containers:
       nginx:
        Image:        nginx:1<span class="token punctuation">.</span>17<span class="token punctuation">.</span>1
        Port:         80/TCP
        Host Port:    0/TCP
        Environment:  <none>
        Mounts:       <none>
      Volumes:        <none>
    Conditions:
      <span class="token function">Type</span>           Status  Reason
      <span class="token operator">--</span><span class="token operator">--</span>           <span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span>  <span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span>
      Available      True    MinimumReplicasAvailable
      Progressing    True    NewReplicaSetAvailable
    OldReplicaSets:  <none>
    NewReplicaSet:   nginx-5ff7956ff6 <span class="token punctuation">(</span>3/3 replicas created<span class="token punctuation">)</span>
    Events:
      <span class="token function">Type</span>    Reason             Age    <span class="token keyword">From</span>                   Message
      <span class="token operator">--</span><span class="token operator">--</span>    <span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span>             <span class="token operator">--</span><span class="token operator">--</span>   <span class="token operator">--</span><span class="token operator">--</span>                   <span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">-</span>
      Normal  ScalingReplicaSet  5m43s  deployment-controller  Scaled up replicaset nginx-5ff7956ff6 to 3
      
    <span class="token comment"># 删除 </span>
    <span class="token namespace">[root@master ~]</span><span class="token comment"># kubectl delete deploy nginx -n dev</span>
    deployment<span class="token punctuation">.</span>apps <span class="token string">"nginx"</span> deleted
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><div class="hide-preCode-box"><span class="hide-preCode-bt" data-report-view="{"spm":"1001.2101.3001.7365"}"><img class="look-more-preCode contentImg-no-view" src="https://1000bd.com/contentImg/2022/06/27/191644837.png" alt="" title=""></span></div><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li><li style="color: rgb(153, 153, 153);">2</li><li style="color: rgb(153, 153, 153);">3</li><li style="color: rgb(153, 153, 153);">4</li><li style="color: rgb(153, 153, 153);">5</li><li style="color: rgb(153, 153, 153);">6</li><li style="color: rgb(153, 153, 153);">7</li><li style="color: rgb(153, 153, 153);">8</li><li style="color: rgb(153, 153, 153);">9</li><li style="color: rgb(153, 153, 153);">10</li><li style="color: rgb(153, 153, 153);">11</li><li style="color: rgb(153, 153, 153);">12</li><li style="color: rgb(153, 153, 153);">13</li><li style="color: rgb(153, 153, 153);">14</li><li style="color: rgb(153, 153, 153);">15</li><li style="color: rgb(153, 153, 153);">16</li><li style="color: rgb(153, 153, 153);">17</li><li style="color: rgb(153, 153, 153);">18</li><li style="color: rgb(153, 153, 153);">19</li><li style="color: rgb(153, 153, 153);">20</li><li style="color: rgb(153, 153, 153);">21</li><li style="color: rgb(153, 153, 153);">22</li><li style="color: rgb(153, 153, 153);">23</li><li style="color: rgb(153, 153, 153);">24</li><li style="color: rgb(153, 153, 153);">25</li><li style="color: rgb(153, 153, 153);">26</li><li style="color: rgb(153, 153, 153);">27</li><li style="color: rgb(153, 153, 153);">28</li><li style="color: rgb(153, 153, 153);">29</li><li style="color: rgb(153, 153, 153);">30</li><li style="color: rgb(153, 153, 153);">31</li><li style="color: rgb(153, 153, 153);">32</li><li style="color: rgb(153, 153, 153);">33</li><li style="color: rgb(153, 153, 153);">34</li><li style="color: rgb(153, 153, 153);">35</li><li style="color: rgb(153, 153, 153);">36</li><li style="color: rgb(153, 153, 153);">37</li><li style="color: rgb(153, 153, 153);">38</li><li style="color: rgb(153, 153, 153);">39</li><li style="color: rgb(153, 153, 153);">40</li><li style="color: rgb(153, 153, 153);">41</li><li style="color: rgb(153, 153, 153);">42</li><li style="color: rgb(153, 153, 153);">43</li><li style="color: rgb(153, 153, 153);">44</li><li style="color: rgb(153, 153, 153);">45</li><li style="color: rgb(153, 153, 153);">46</li><li style="color: rgb(153, 153, 153);">47</li><li style="color: rgb(153, 153, 153);">48</li><li style="color: rgb(153, 153, 153);">49</li><li style="color: rgb(153, 153, 153);">50</li><li style="color: rgb(153, 153, 153);">51</li><li style="color: rgb(153, 153, 153);">52</li><li style="color: rgb(153, 153, 153);">53</li><li style="color: rgb(153, 153, 153);">54</li><li style="color: rgb(153, 153, 153);">55</li><li style="color: rgb(153, 153, 153);">56</li><li style="color: rgb(153, 153, 153);">57</li><li style="color: rgb(153, 153, 153);">58</li><li style="color: rgb(153, 153, 153);">59</li><li style="color: rgb(153, 153, 153);">60</li><li style="color: rgb(153, 153, 153);">61</li><li style="color: rgb(153, 153, 153);">62</li><li style="color: rgb(153, 153, 153);">63</li></ul></pre> 
    <p><strong>配置操作</strong></p> 
    <p>创建一个deploy-nginx.yaml,内容如下:</p> 
    <pre data-index="50" class="set-code-show prettyprint"><code class="prism language-yaml has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token key atrule">apiVersion</span><span class="token punctuation">:</span> <span class="token key atrule">apps/v1kind</span><span class="token punctuation">:</span> <span class="token key atrule">Deploymentmetadata</span><span class="token punctuation">:</span>  <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">nginx  namespace</span><span class="token punctuation">:</span> <span class="token key atrule">devspec</span><span class="token punctuation">:</span>  <span class="token key atrule">replicas</span><span class="token punctuation">:</span> <span class="token key atrule">3  selector</span><span class="token punctuation">:</span>    <span class="token key atrule">matchLabels</span><span class="token punctuation">:</span>      <span class="token key atrule">run</span><span class="token punctuation">:</span> <span class="token key atrule">nginx  template</span><span class="token punctuation">:</span>    <span class="token key atrule">metadata</span><span class="token punctuation">:</span>      <span class="token key atrule">labels</span><span class="token punctuation">:</span>        <span class="token key atrule">run</span><span class="token punctuation">:</span> <span class="token key atrule">nginx    spec</span><span class="token punctuation">:</span>      <span class="token key atrule">containers</span><span class="token punctuation">:</span>      <span class="token punctuation">-</span> <span class="token key atrule">image</span><span class="token punctuation">:</span> <span class="token key atrule">nginx:1.17.1        name</span><span class="token punctuation">:</span> <span class="token key atrule">nginx        ports</span><span class="token punctuation">:</span>        <span class="token punctuation">-</span> <span class="token key atrule">containerPort</span><span class="token punctuation">:</span> <span class="token key atrule">80          protocol</span><span class="token punctuation">:</span> TCP
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <p>然后就可以执行对应的创建和删除命令了:</p> 
    <p>​ 创建:kubectl create -f deploy-nginx.yaml</p> 
    <p>​ 删除:kubectl delete -f deploy-nginx.yaml</p> 
    <h3><a name="t32"></a><a id="Service_1464"></a>Service</h3> 
    <p>通过上节课的学习,已经能够利用Deployment来创建一组Pod来提供具有高可用性的服务。</p> 
    <p>虽然每个Pod都会分配一个单独的Pod IP,然而却存在如下两问题:</p> 
    <ul><li>Pod IP 会随着Pod的重建产生变化</li><li>Pod IP 仅仅是集群内可见的虚拟IP,外部无法访问</li></ul> 
    <p>这样对于访问这个服务带来了难度。因此,kubernetes设计了Service来解决这个问题。</p> 
    <p>Service可以看作是一组同类Pod<strong>对外的访问接口</strong>。借助Service,应用可以方便地实现服务发现和负载均衡。</p> 
    <p><img src="https://1000bd.com/contentImg/2024/04/14/ce690ac052858b83.png" alt="image-20200408194716912"></p> 
    <p><strong>操作一:创建集群内部可访问的Service</strong></p> 
    <pre data-index="51" class="set-code-hide prettyprint"><code class="prism language-powershell has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token comment"># 暴露Service</span>
    <span class="token namespace">[root@master ~]</span><span class="token comment"># kubectl expose deploy nginx --name=svc-nginx1 --type=ClusterIP --port=80 --target-port=80 -n dev</span>
    service/svc-nginx1 exposed
    
    <span class="token comment"># 查看service</span>
    <span class="token namespace">[root@master ~]</span><span class="token comment"># kubectl get svc svc-nginx -n dev -o wide</span>
    NAME         <span class="token function">TYPE</span>        CLUSTER-IP       EXTERNAL-IP   PORT<span class="token punctuation">(</span>S<span class="token punctuation">)</span>   AGE     SELECTOR
    svc-nginx1   ClusterIP   10<span class="token punctuation">.</span>109<span class="token punctuation">.</span>179<span class="token punctuation">.</span>231   <none>        80/TCP    3m51s   run=nginx
    
    <span class="token comment"># 这里产生了一个CLUSTER-IP,这就是service的IP,在Service的生命周期中,这个地址是不会变动的</span>
    <span class="token comment"># 可以通过这个IP访问当前service对应的POD</span>
    <span class="token namespace">[root@master ~]</span><span class="token comment"># curl 10.109.179.231:80</span>
    <<span class="token operator">!</span>DOCTYPE html>
    <html>
    <head>
    <title>Welcome to nginx!<<span class="token operator">/</span>title>
    <<span class="token operator">/</span>head>
    <body>
    <h1>Welcome to nginx!<<span class="token operator">/</span>h1>
    <span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span>
    <<span class="token operator">/</span>body>
    <<span class="token operator">/</span>html>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><div class="hide-preCode-box"><span class="hide-preCode-bt" data-report-view="{"spm":"1001.2101.3001.7365"}"><img class="look-more-preCode contentImg-no-view" src="https://1000bd.com/contentImg/2022/06/27/191644837.png" alt="" title=""></span></div><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li><li style="color: rgb(153, 153, 153);">2</li><li style="color: rgb(153, 153, 153);">3</li><li style="color: rgb(153, 153, 153);">4</li><li style="color: rgb(153, 153, 153);">5</li><li style="color: rgb(153, 153, 153);">6</li><li style="color: rgb(153, 153, 153);">7</li><li style="color: rgb(153, 153, 153);">8</li><li style="color: rgb(153, 153, 153);">9</li><li style="color: rgb(153, 153, 153);">10</li><li style="color: rgb(153, 153, 153);">11</li><li style="color: rgb(153, 153, 153);">12</li><li style="color: rgb(153, 153, 153);">13</li><li style="color: rgb(153, 153, 153);">14</li><li style="color: rgb(153, 153, 153);">15</li><li style="color: rgb(153, 153, 153);">16</li><li style="color: rgb(153, 153, 153);">17</li><li style="color: rgb(153, 153, 153);">18</li><li style="color: rgb(153, 153, 153);">19</li><li style="color: rgb(153, 153, 153);">20</li><li style="color: rgb(153, 153, 153);">21</li><li style="color: rgb(153, 153, 153);">22</li></ul></pre> 
    <p><strong>操作二:创建集群外部也可访问的Service</strong></p> 
    <pre data-index="52" class="set-code-show prettyprint"><code class="prism language-powershell has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token comment"># 上面创建的Service的type类型为ClusterIP,这个ip地址只用集群内部可访问</span>
    <span class="token comment"># 如果需要创建外部也可以访问的Service,需要修改type为NodePort</span>
    <span class="token namespace">[root@master ~]</span><span class="token comment"># kubectl expose deploy nginx --name=svc-nginx2 --type=NodePort --port=80 --target-port=80 -n dev</span>
    service/svc-nginx2 exposed
    
    <span class="token comment"># 此时查看,会发现出现了NodePort类型的Service,而且有一对Port(80:31928/TC)</span>
    <span class="token namespace">[root@master ~]</span><span class="token comment"># kubectl get svc  svc-nginx-1  -n dev -o wide</span>
    NAME          <span class="token function">TYPE</span>        CLUSTER-IP       EXTERNAL-IP   PORT<span class="token punctuation">(</span>S<span class="token punctuation">)</span>        AGE    SELECTOR
    svc-nginx2    NodePort    10<span class="token punctuation">.</span>100<span class="token punctuation">.</span>94<span class="token punctuation">.</span>0      <none>        80:31928/TCP   9s     run=nginx
    
    <span class="token comment"># 接下来就可以通过集群外的主机访问 节点IP:31928访问服务了</span>
    <span class="token comment"># 例如在的电脑主机上通过浏览器访问下面的地址</span>
    http:<span class="token operator">/</span><span class="token operator">/</span>192<span class="token punctuation">.</span>168<span class="token punctuation">.</span>109<span class="token punctuation">.</span>100:31928/
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li><li style="color: rgb(153, 153, 153);">2</li><li style="color: rgb(153, 153, 153);">3</li><li style="color: rgb(153, 153, 153);">4</li><li style="color: rgb(153, 153, 153);">5</li><li style="color: rgb(153, 153, 153);">6</li><li style="color: rgb(153, 153, 153);">7</li><li style="color: rgb(153, 153, 153);">8</li><li style="color: rgb(153, 153, 153);">9</li><li style="color: rgb(153, 153, 153);">10</li><li style="color: rgb(153, 153, 153);">11</li><li style="color: rgb(153, 153, 153);">12</li><li style="color: rgb(153, 153, 153);">13</li></ul></pre> 
    <p><strong>删除Service</strong></p> 
    <pre data-index="53" class="set-code-show prettyprint"><code class="prism language-powershell has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token namespace">[root@master ~]</span><span class="token comment"># kubectl delete svc svc-nginx-1 -n dev                                   service "svc-nginx-1" deleted</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <p><strong>配置方式</strong></p> 
    <p>创建一个svc-nginx.yaml,内容如下:</p> 
    <pre data-index="54" class="set-code-show prettyprint"><code class="prism language-yaml has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token key atrule">apiVersion</span><span class="token punctuation">:</span> <span class="token key atrule">v1kind</span><span class="token punctuation">:</span> <span class="token key atrule">Servicemetadata</span><span class="token punctuation">:</span>  <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">svc-nginx  namespace</span><span class="token punctuation">:</span> <span class="token key atrule">devspec</span><span class="token punctuation">:</span>  <span class="token key atrule">clusterIP</span><span class="token punctuation">:</span> <span class="token key atrule">10.109.179.231  ports</span><span class="token punctuation">:</span>  <span class="token punctuation">-</span> <span class="token key atrule">port</span><span class="token punctuation">:</span> <span class="token key atrule">80    protocol</span><span class="token punctuation">:</span> <span class="token key atrule">TCP    targetPort</span><span class="token punctuation">:</span> <span class="token key atrule">80  selector</span><span class="token punctuation">:</span>    <span class="token key atrule">run</span><span class="token punctuation">:</span> <span class="token key atrule">nginx  type</span><span class="token punctuation">:</span> ClusterIP
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <p>然后就可以执行对应的创建和删除命令了:</p> 
    <p>​ 创建:kubectl create -f svc-nginx.yaml</p> 
    <p>​ 删除:kubectl delete -f svc-nginx.yaml</p> 
    <blockquote> 
     <p><strong>小结</strong></p> 
     <p>​ 至此,已经掌握了Namespace、Pod、Deployment、Service资源的基本操作,有了这些操作,就可以在kubernetes集群中实现一个服务的简单部署和访问了,但是如果想要更好的使用kubernetes,就需要深入学习这几种资源的细节和原理。</p> 
    </blockquote> 
    <h2><a name="t33"></a><a id="_Pod_1550"></a>第五章 Pod详解</h2> 
    <p>本章节将详细介绍Pod资源的各种配置(yaml)和原理。</p> 
    <h3><a name="t34"></a><a id="Pod_1554"></a>Pod介绍</h3> 
    <h4><a name="t35"></a><a id="Pod_1556"></a>Pod结构</h4> 
    <img src="https://1000bd.com/contentImg/2023/10/27/000132537.png" alt="image-20200407121501907"> 
    <p>每个Pod中都可以包含一个或者多个容器,这些容器可以分为两类:</p> 
    <ul><li> <p>用户程序所在的容器,数量可多可少</p> </li><li> <p>Pause容器,这是每个Pod都会有的一个<strong>根容器</strong>,它的作用有两个:</p> 
      <ul><li> <p>可以以它为依据,评估整个Pod的健康状态</p> </li><li> <p>可以在根容器上设置Ip地址,其它容器都此Ip(Pod IP),以实现Pod内部的网路通信</p> <pre data-index="55" class="set-code-show prettyprint"><code class="prism language-md has-numbering" onclick="mdcp.signin(event)" style="position: unset;">这里是Pod内部的通讯,Pod的之间的通讯采用虚拟二层网络技术来实现,我们当前环境用的是Flannel
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> </li></ul> </li></ul> 
    <h4><a name="t36"></a><a id="Pod_1574"></a>Pod定义</h4> 
    <p>下面是Pod的资源清单:</p> 
    <pre data-index="56" class="set-code-hide prettyprint"><code class="prism language-yaml has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token key atrule">apiVersion</span><span class="token punctuation">:</span> v1     <span class="token comment">#必选,版本号,例如v1</span>
    <span class="token key atrule">kind</span><span class="token punctuation">:</span> Pod         <span class="token comment">#必选,资源类型,例如 Pod</span>
    <span class="token key atrule">metadata</span><span class="token punctuation">:</span>         <span class="token comment">#必选,元数据</span>
      <span class="token key atrule">name</span><span class="token punctuation">:</span> string     <span class="token comment">#必选,Pod名称</span>
      <span class="token key atrule">namespace</span><span class="token punctuation">:</span> string  <span class="token comment">#Pod所属的命名空间,默认为"default"</span>
      <span class="token key atrule">labels</span><span class="token punctuation">:</span>           <span class="token comment">#自定义标签列表</span>
        <span class="token punctuation">-</span> <span class="token key atrule">name</span><span class="token punctuation">:</span> string                 
    <span class="token key atrule">spec</span><span class="token punctuation">:</span>  <span class="token comment">#必选,Pod中容器的详细定义</span>
      <span class="token key atrule">containers</span><span class="token punctuation">:</span>  <span class="token comment">#必选,Pod中容器列表</span>
      <span class="token punctuation">-</span> <span class="token key atrule">name</span><span class="token punctuation">:</span> string   <span class="token comment">#必选,容器名称</span>
        <span class="token key atrule">image</span><span class="token punctuation">:</span> string  <span class="token comment">#必选,容器的镜像名称</span>
        <span class="token key atrule">imagePullPolicy</span><span class="token punctuation">:</span> <span class="token punctuation">[</span> Always<span class="token punctuation">|</span>Never<span class="token punctuation">|</span>IfNotPresent <span class="token punctuation">]</span>  <span class="token comment">#获取镜像的策略 </span>
        <span class="token key atrule">command</span><span class="token punctuation">:</span> <span class="token punctuation">[</span>string<span class="token punctuation">]</span>   <span class="token comment">#容器的启动命令列表,如不指定,使用打包时使用的启动命令</span>
        <span class="token key atrule">args</span><span class="token punctuation">:</span> <span class="token punctuation">[</span>string<span class="token punctuation">]</span>      <span class="token comment">#容器的启动命令参数列表</span>
        <span class="token key atrule">workingDir</span><span class="token punctuation">:</span> string  <span class="token comment">#容器的工作目录</span>
        <span class="token key atrule">volumeMounts</span><span class="token punctuation">:</span>       <span class="token comment">#挂载到容器内部的存储卷配置</span>
        <span class="token punctuation">-</span> <span class="token key atrule">name</span><span class="token punctuation">:</span> string      <span class="token comment">#引用pod定义的共享存储卷的名称,需用volumes[]部分定义的的卷名</span>
          <span class="token key atrule">mountPath</span><span class="token punctuation">:</span> string <span class="token comment">#存储卷在容器内mount的绝对路径,应少于512字符</span>
          <span class="token key atrule">readOnly</span><span class="token punctuation">:</span> boolean <span class="token comment">#是否为只读模式</span>
        <span class="token key atrule">ports</span><span class="token punctuation">:</span> <span class="token comment">#需要暴露的端口库号列表</span>
        <span class="token punctuation">-</span> <span class="token key atrule">name</span><span class="token punctuation">:</span> string        <span class="token comment">#端口的名称</span>
          <span class="token key atrule">containerPort</span><span class="token punctuation">:</span> int  <span class="token comment">#容器需要监听的端口号</span>
          <span class="token key atrule">hostPort</span><span class="token punctuation">:</span> int       <span class="token comment">#容器所在主机需要监听的端口号,默认与Container相同</span>
          <span class="token key atrule">protocol</span><span class="token punctuation">:</span> string    <span class="token comment">#端口协议,支持TCP和UDP,默认TCP</span>
        <span class="token key atrule">env</span><span class="token punctuation">:</span>   <span class="token comment">#容器运行前需设置的环境变量列表</span>
        <span class="token punctuation">-</span> <span class="token key atrule">name</span><span class="token punctuation">:</span> string  <span class="token comment">#环境变量名称</span>
          <span class="token key atrule">value</span><span class="token punctuation">:</span> string <span class="token comment">#环境变量的值</span>
        <span class="token key atrule">resources</span><span class="token punctuation">:</span> <span class="token comment">#资源限制和请求的设置</span>
          <span class="token key atrule">limits</span><span class="token punctuation">:</span>  <span class="token comment">#资源限制的设置</span>
            <span class="token key atrule">cpu</span><span class="token punctuation">:</span> string     <span class="token comment">#Cpu的限制,单位为core数,将用于docker run --cpu-shares参数</span>
            <span class="token key atrule">memory</span><span class="token punctuation">:</span> string  <span class="token comment">#内存限制,单位可以为Mib/Gib,将用于docker run --memory参数</span>
          <span class="token key atrule">requests</span><span class="token punctuation">:</span> <span class="token comment">#资源请求的设置</span>
            <span class="token key atrule">cpu</span><span class="token punctuation">:</span> string    <span class="token comment">#Cpu请求,容器启动的初始可用数量</span>
            <span class="token key atrule">memory</span><span class="token punctuation">:</span> string <span class="token comment">#内存请求,容器启动的初始可用数量</span>
        <span class="token key atrule">lifecycle</span><span class="token punctuation">:</span> <span class="token comment">#生命周期钩子</span>
    		<span class="token key atrule">postStart</span><span class="token punctuation">:</span> <span class="token comment">#容器启动后立即执行此钩子,如果执行失败,会根据重启策略进行重启</span>
    		<span class="token key atrule">preStop</span><span class="token punctuation">:</span> <span class="token comment">#容器终止前执行此钩子,无论结果如何,容器都会终止</span>
        <span class="token key atrule">livenessProbe</span><span class="token punctuation">:</span>  <span class="token comment">#对Pod内各容器健康检查的设置,当探测无响应几次后将自动重启该容器</span>
          <span class="token key atrule">exec</span><span class="token punctuation">:</span>         <span class="token comment">#对Pod容器内检查方式设置为exec方式</span>
            <span class="token key atrule">command</span><span class="token punctuation">:</span> <span class="token punctuation">[</span>string<span class="token punctuation">]</span>  <span class="token comment">#exec方式需要制定的命令或脚本</span>
          <span class="token key atrule">httpGet</span><span class="token punctuation">:</span>       <span class="token comment">#对Pod内个容器健康检查方法设置为HttpGet,需要制定Path、port</span>
            <span class="token key atrule">path</span><span class="token punctuation">:</span> string
            <span class="token key atrule">port</span><span class="token punctuation">:</span> number
            <span class="token key atrule">host</span><span class="token punctuation">:</span> string
            <span class="token key atrule">scheme</span><span class="token punctuation">:</span> string
            <span class="token key atrule">HttpHeaders</span><span class="token punctuation">:</span>
            <span class="token punctuation">-</span> <span class="token key atrule">name</span><span class="token punctuation">:</span> string
              <span class="token key atrule">value</span><span class="token punctuation">:</span> string
          <span class="token key atrule">tcpSocket</span><span class="token punctuation">:</span>     <span class="token comment">#对Pod内个容器健康检查方式设置为tcpSocket方式</span>
             <span class="token key atrule">port</span><span class="token punctuation">:</span> number
           <span class="token key atrule">initialDelaySeconds</span><span class="token punctuation">:</span> <span class="token number">0</span>       <span class="token comment">#容器启动完成后首次探测的时间,单位为秒</span>
           <span class="token key atrule">timeoutSeconds</span><span class="token punctuation">:</span> 0          <span class="token comment">#对容器健康检查探测等待响应的超时时间,单位秒,默认1秒</span>
           <span class="token key atrule">periodSeconds</span><span class="token punctuation">:</span> 0           <span class="token comment">#对容器监控检查的定期探测时间设置,单位秒,默认10秒一次</span>
           <span class="token key atrule">successThreshold</span><span class="token punctuation">:</span> <span class="token number">0</span>
           <span class="token key atrule">failureThreshold</span><span class="token punctuation">:</span> <span class="token number">0</span>
           <span class="token key atrule">securityContext</span><span class="token punctuation">:</span>
             <span class="token key atrule">privileged</span><span class="token punctuation">:</span> <span class="token boolean important">false</span>
      <span class="token key atrule">restartPolicy</span><span class="token punctuation">:</span> <span class="token punctuation">[</span>Always <span class="token punctuation">|</span> Never <span class="token punctuation">|</span> OnFailure<span class="token punctuation">]</span>  <span class="token comment">#Pod的重启策略</span>
      <span class="token key atrule">nodeName</span><span class="token punctuation">:</span> <string<span class="token punctuation">></span> <span class="token comment">#设置NodeName表示将该Pod调度到指定到名称的node节点上</span>
      <span class="token key atrule">nodeSelector</span><span class="token punctuation">:</span> obeject <span class="token comment">#设置NodeSelector表示将该Pod调度到包含这个label的node上</span>
      <span class="token key atrule">imagePullSecrets</span><span class="token punctuation">:</span> <span class="token comment">#Pull镜像时使用的secret名称,以key:secretkey格式指定</span>
      <span class="token punctuation">-</span> <span class="token key atrule">name</span><span class="token punctuation">:</span> string
      <span class="token key atrule">hostNetwork</span><span class="token punctuation">:</span> <span class="token boolean important">false</span>   <span class="token comment">#是否使用主机网络模式,默认为false,如果设置为true,表示使用宿主机网络</span>
      <span class="token key atrule">volumes</span><span class="token punctuation">:</span>   <span class="token comment">#在该pod上定义共享存储卷列表</span>
      <span class="token punctuation">-</span> <span class="token key atrule">name</span><span class="token punctuation">:</span> string    <span class="token comment">#共享存储卷名称 (volumes类型有很多种)</span>
        <span class="token key atrule">emptyDir</span><span class="token punctuation">:</span> <span class="token punctuation">{<!-- --></span><span class="token punctuation">}</span>       <span class="token comment">#类型为emtyDir的存储卷,与Pod同生命周期的一个临时目录。为空值</span>
        <span class="token key atrule">hostPath</span><span class="token punctuation">:</span> string   <span class="token comment">#类型为hostPath的存储卷,表示挂载Pod所在宿主机的目录</span>
          <span class="token key atrule">path</span><span class="token punctuation">:</span> string                <span class="token comment">#Pod所在宿主机的目录,将被用于同期中mount的目录</span>
        <span class="token key atrule">secret</span><span class="token punctuation">:</span>          <span class="token comment">#类型为secret的存储卷,挂载集群与定义的secret对象到容器内部</span>
          <span class="token key atrule">scretname</span><span class="token punctuation">:</span> string  
          <span class="token key atrule">items</span><span class="token punctuation">:</span>     
          <span class="token punctuation">-</span> <span class="token key atrule">key</span><span class="token punctuation">:</span> string
            <span class="token key atrule">path</span><span class="token punctuation">:</span> string
        <span class="token key atrule">configMap</span><span class="token punctuation">:</span>         <span class="token comment">#类型为configMap的存储卷,挂载预定义的configMap对象到容器内部</span>
          <span class="token key atrule">name</span><span class="token punctuation">:</span> string
          <span class="token key atrule">items</span><span class="token punctuation">:</span>
          <span class="token punctuation">-</span> <span class="token key atrule">key</span><span class="token punctuation">:</span> string
            <span class="token key atrule">path</span><span class="token punctuation">:</span> string
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><div class="hide-preCode-box"><span class="hide-preCode-bt" data-report-view="{"spm":"1001.2101.3001.7365"}"><img class="look-more-preCode contentImg-no-view" src="https://1000bd.com/contentImg/2022/06/27/191644837.png" alt="" title=""></span></div><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li><li style="color: rgb(153, 153, 153);">2</li><li style="color: rgb(153, 153, 153);">3</li><li style="color: rgb(153, 153, 153);">4</li><li style="color: rgb(153, 153, 153);">5</li><li style="color: rgb(153, 153, 153);">6</li><li style="color: rgb(153, 153, 153);">7</li><li style="color: rgb(153, 153, 153);">8</li><li style="color: rgb(153, 153, 153);">9</li><li style="color: rgb(153, 153, 153);">10</li><li style="color: rgb(153, 153, 153);">11</li><li style="color: rgb(153, 153, 153);">12</li><li style="color: rgb(153, 153, 153);">13</li><li style="color: rgb(153, 153, 153);">14</li><li style="color: rgb(153, 153, 153);">15</li><li style="color: rgb(153, 153, 153);">16</li><li style="color: rgb(153, 153, 153);">17</li><li style="color: rgb(153, 153, 153);">18</li><li style="color: rgb(153, 153, 153);">19</li><li style="color: rgb(153, 153, 153);">20</li><li style="color: rgb(153, 153, 153);">21</li><li style="color: rgb(153, 153, 153);">22</li><li style="color: rgb(153, 153, 153);">23</li><li style="color: rgb(153, 153, 153);">24</li><li style="color: rgb(153, 153, 153);">25</li><li style="color: rgb(153, 153, 153);">26</li><li style="color: rgb(153, 153, 153);">27</li><li style="color: rgb(153, 153, 153);">28</li><li style="color: rgb(153, 153, 153);">29</li><li style="color: rgb(153, 153, 153);">30</li><li style="color: rgb(153, 153, 153);">31</li><li style="color: rgb(153, 153, 153);">32</li><li style="color: rgb(153, 153, 153);">33</li><li style="color: rgb(153, 153, 153);">34</li><li style="color: rgb(153, 153, 153);">35</li><li style="color: rgb(153, 153, 153);">36</li><li style="color: rgb(153, 153, 153);">37</li><li style="color: rgb(153, 153, 153);">38</li><li style="color: rgb(153, 153, 153);">39</li><li style="color: rgb(153, 153, 153);">40</li><li style="color: rgb(153, 153, 153);">41</li><li style="color: rgb(153, 153, 153);">42</li><li style="color: rgb(153, 153, 153);">43</li><li style="color: rgb(153, 153, 153);">44</li><li style="color: rgb(153, 153, 153);">45</li><li style="color: rgb(153, 153, 153);">46</li><li style="color: rgb(153, 153, 153);">47</li><li style="color: rgb(153, 153, 153);">48</li><li style="color: rgb(153, 153, 153);">49</li><li style="color: rgb(153, 153, 153);">50</li><li style="color: rgb(153, 153, 153);">51</li><li style="color: rgb(153, 153, 153);">52</li><li style="color: rgb(153, 153, 153);">53</li><li style="color: rgb(153, 153, 153);">54</li><li style="color: rgb(153, 153, 153);">55</li><li style="color: rgb(153, 153, 153);">56</li><li style="color: rgb(153, 153, 153);">57</li><li style="color: rgb(153, 153, 153);">58</li><li style="color: rgb(153, 153, 153);">59</li><li style="color: rgb(153, 153, 153);">60</li><li style="color: rgb(153, 153, 153);">61</li><li style="color: rgb(153, 153, 153);">62</li><li style="color: rgb(153, 153, 153);">63</li><li style="color: rgb(153, 153, 153);">64</li><li style="color: rgb(153, 153, 153);">65</li><li style="color: rgb(153, 153, 153);">66</li><li style="color: rgb(153, 153, 153);">67</li><li style="color: rgb(153, 153, 153);">68</li><li style="color: rgb(153, 153, 153);">69</li><li style="color: rgb(153, 153, 153);">70</li><li style="color: rgb(153, 153, 153);">71</li><li style="color: rgb(153, 153, 153);">72</li><li style="color: rgb(153, 153, 153);">73</li><li style="color: rgb(153, 153, 153);">74</li><li style="color: rgb(153, 153, 153);">75</li><li style="color: rgb(153, 153, 153);">76</li><li style="color: rgb(153, 153, 153);">77</li><li style="color: rgb(153, 153, 153);">78</li></ul></pre> 
    <pre data-index="57" class="set-code-hide prettyprint"><code class="prism language-powershell has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token comment">#小提示:</span>
    <span class="token comment">#	在这里,可通过一个命令来查看每种资源的可配置项</span>
    <span class="token comment">#   kubectl explain 资源类型         查看某种资源可以配置的一级属性</span>
    <span class="token comment">#	kubectl explain 资源类型.属性     查看属性的子属性</span>
    <span class="token namespace">[root@master ~]</span><span class="token comment"># kubectl explain pod</span>
    KIND:     Pod
    VERSION:  v1
    FIELDS:
       apiVersion   <string>
       kind <string>
       metadata     <Object>
       spec <Object>
       status       <Object>
    
    <span class="token namespace">[root@master ~]</span><span class="token comment"># kubectl explain pod.metadata</span>
    KIND:     Pod
    VERSION:  v1
    RESOURCE: metadata <Object>
    FIELDS:
       annotations  <map<span class="token namespace">[string]</span>string>
       clusterName  <string>
       creationTimestamp    <string>
       deletionGracePeriodSeconds   <integer>
       deletionTimestamp    <string>
       finalizers   <<span class="token punctuation">[</span><span class="token punctuation">]</span>string>
       generateName <string>
       generation   <integer>
       labels       <map<span class="token namespace">[string]</span>string>
       managedFields        <<span class="token punctuation">[</span><span class="token punctuation">]</span>Object>
       name <string>
       namespace    <string>
       ownerReferences      <<span class="token punctuation">[</span><span class="token punctuation">]</span>Object>
       resourceVersion      <string>
       selfLink     <string>
       uid  <string>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><div class="hide-preCode-box"><span class="hide-preCode-bt" data-report-view="{"spm":"1001.2101.3001.7365"}"><img class="look-more-preCode contentImg-no-view" src="https://1000bd.com/contentImg/2022/06/27/191644837.png" alt="" title=""></span></div><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li><li style="color: rgb(153, 153, 153);">2</li><li style="color: rgb(153, 153, 153);">3</li><li style="color: rgb(153, 153, 153);">4</li><li style="color: rgb(153, 153, 153);">5</li><li style="color: rgb(153, 153, 153);">6</li><li style="color: rgb(153, 153, 153);">7</li><li style="color: rgb(153, 153, 153);">8</li><li style="color: rgb(153, 153, 153);">9</li><li style="color: rgb(153, 153, 153);">10</li><li style="color: rgb(153, 153, 153);">11</li><li style="color: rgb(153, 153, 153);">12</li><li style="color: rgb(153, 153, 153);">13</li><li style="color: rgb(153, 153, 153);">14</li><li style="color: rgb(153, 153, 153);">15</li><li style="color: rgb(153, 153, 153);">16</li><li style="color: rgb(153, 153, 153);">17</li><li style="color: rgb(153, 153, 153);">18</li><li style="color: rgb(153, 153, 153);">19</li><li style="color: rgb(153, 153, 153);">20</li><li style="color: rgb(153, 153, 153);">21</li><li style="color: rgb(153, 153, 153);">22</li><li style="color: rgb(153, 153, 153);">23</li><li style="color: rgb(153, 153, 153);">24</li><li style="color: rgb(153, 153, 153);">25</li><li style="color: rgb(153, 153, 153);">26</li><li style="color: rgb(153, 153, 153);">27</li><li style="color: rgb(153, 153, 153);">28</li><li style="color: rgb(153, 153, 153);">29</li><li style="color: rgb(153, 153, 153);">30</li><li style="color: rgb(153, 153, 153);">31</li><li style="color: rgb(153, 153, 153);">32</li><li style="color: rgb(153, 153, 153);">33</li><li style="color: rgb(153, 153, 153);">34</li><li style="color: rgb(153, 153, 153);">35</li></ul></pre> 
    <p>在kubernetes中基本所有资源的一级属性都是一样的,主要包含5部分:</p> 
    <ul><li> <p>apiVersion <string> 版本,由kubernetes内部定义,版本号必须可以用 kubectl api-versions 查询到</p> </li><li> <p>kind <string> 类型,由kubernetes内部定义,版本号必须可以用 kubectl api-resources 查询到</p> </li><li> <p>metadata <Object> 元数据,主要是资源标识和说明,常用的有name、namespace、labels等</p> </li><li> <p>spec <Object> 描述,这是配置中最重要的一部分,里面是对各种资源配置的详细描述</p> </li><li> <p>status <Object> 状态信息,里面的内容不需要定义,由kubernetes自动生成</p> </li></ul> 
    <p>在上面的属性中,spec是接下来研究的重点,继续看下它的常见子属性:</p> 
    <ul><li>containers <[]Object> 容器列表,用于定义容器的详细信息</li><li>nodeName <String> 根据nodeName的值将pod调度到指定的Node节点上</li><li>nodeSelector <map[]> 根据NodeSelector中定义的信息选择将该Pod调度到包含这些label的Node 上</li><li>hostNetwork <boolean> 是否使用主机网络模式,默认为false,如果设置为true,表示使用宿主机网络</li><li>volumes <[]Object> 存储卷,用于定义Pod上面挂在的存储信息</li><li>restartPolicy <string> 重启策略,表示Pod在遇到故障的时候的处理策略</li></ul> 
    <h3><a name="t37"></a><a id="Pod_1719"></a>Pod配置</h3> 
    <p>本小节主要来研究<code>pod.spec.containers</code>属性,这也是pod配置中最为关键的一项配置。</p> 
    <pre data-index="58" class="set-code-show prettyprint"><code class="prism language-powershell has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token namespace">[root@master ~]</span><span class="token comment"># kubectl explain pod.spec.containersKIND:     PodVERSION:  v1RESOURCE: containers <[]Object>   # 数组,代表可以有多个容器FIELDS:   name  <string>     # 容器名称   image <string>     # 容器需要的镜像地址   imagePullPolicy  <string> # 镜像拉取策略    command  <[]string> # 容器的启动命令列表,如不指定,使用打包时使用的启动命令   args     <[]string> # 容器的启动命令需要的参数列表   env      <[]Object> # 容器环境变量的配置   ports    <[]Object>     # 容器需要暴露的端口号列表   resources <Object>      # 资源限制和资源请求的设置</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <h4><a name="t38"></a><a id="_1727"></a>基本配置</h4> 
    <p>创建pod-base.yaml文件,内容如下:</p> 
    <pre data-index="59" class="set-code-show prettyprint"><code class="prism language-yaml has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token key atrule">apiVersion</span><span class="token punctuation">:</span> <span class="token key atrule">v1kind</span><span class="token punctuation">:</span> <span class="token key atrule">Podmetadata</span><span class="token punctuation">:</span>  <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">pod-base  namespace</span><span class="token punctuation">:</span> <span class="token key atrule">dev  labels</span><span class="token punctuation">:</span>    <span class="token key atrule">user</span><span class="token punctuation">:</span> <span class="token key atrule">heimaspec</span><span class="token punctuation">:</span>  <span class="token key atrule">containers</span><span class="token punctuation">:</span>  <span class="token punctuation">-</span> <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">nginx    image</span><span class="token punctuation">:</span> <span class="token key atrule">nginx:1.17.1  - name</span><span class="token punctuation">:</span> <span class="token key atrule">busybox    image</span><span class="token punctuation">:</span> busybox<span class="token punctuation">:</span><span class="token number">1.30</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <p>上面定义了一个比较简单Pod的配置,里面有两个容器:</p> 
    <ul><li>nginx:用1.17.1版本的nginx镜像创建,(nginx是一个轻量级web容器)</li><li>busybox:用1.30版本的busybox镜像创建,(busybox是一个小巧的linux命令集合)</li></ul> 
    <pre data-index="60" class="set-code-show prettyprint"><code class="prism language-powershell has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token comment"># 创建Pod[root@master pod]# kubectl apply -f pod-base.yamlpod/pod-base created# 查看Pod状况# READY 1/2 : 表示当前Pod中有2个容器,其中1个准备就绪,1个未就绪# RESTARTS  : 重启次数,因为有1个容器故障了,Pod一直在重启试图恢复它[root@master pod]# kubectl get pod -n devNAME       READY   STATUS    RESTARTS   AGEpod-base   1/2     Running   4          95s# 可以通过describe查看内部的详情# 此时已经运行起来了一个基本的Pod,虽然它暂时有问题[root@master pod]# kubectl describe pod pod-base -n dev</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <h4><a name="t39"></a><a id="_1744"></a>镜像拉取</h4> 
    <p>创建pod-imagepullpolicy.yaml文件,内容如下:</p> 
    <pre data-index="61" class="set-code-show prettyprint"><code class="prism language-yaml has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token key atrule">apiVersion</span><span class="token punctuation">:</span> <span class="token key atrule">v1kind</span><span class="token punctuation">:</span> <span class="token key atrule">Podmetadata</span><span class="token punctuation">:</span>  <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">pod-imagepullpolicy  namespace</span><span class="token punctuation">:</span> <span class="token key atrule">devspec</span><span class="token punctuation">:</span>  <span class="token key atrule">containers</span><span class="token punctuation">:</span>  <span class="token punctuation">-</span> <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">nginx    image</span><span class="token punctuation">:</span> <span class="token key atrule">nginx:1.17.1    imagePullPolicy</span><span class="token punctuation">:</span> Always <span class="token comment"># 用于设置镜像拉取策略  - name: busybox    image: busybox:1.30</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <p>imagePullPolicy,用于设置镜像拉取策略,kubernetes支持配置三种拉取策略:</p> 
    <ul><li>Always:总是从远程仓库拉取镜像(一直远程下载)</li><li>IfNotPresent:本地有则使用本地镜像,本地没有则从远程仓库拉取镜像(本地有就本地 本地没远程下载)</li><li>Never:只使用本地镜像,从不去远程仓库拉取,本地没有就报错 (一直使用本地)</li></ul> 
    <blockquote> 
     <p>默认值说明:</p> 
     <p>​ 如果镜像tag为具体版本号, 默认策略是:IfNotPresent</p> 
     <p>​ 如果镜像tag为:latest(最终版本) ,默认策略是always</p> 
    </blockquote> 
    <pre data-index="62" class="set-code-show prettyprint"><code class="prism language-powershell has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token comment"># 创建Pod[root@master pod]# kubectl create -f pod-imagepullpolicy.yamlpod/pod-imagepullpolicy created# 查看Pod详情# 此时明显可以看到nginx镜像有一步Pulling image "nginx:1.17.1"的过程[root@master pod]# kubectl describe pod pod-imagepullpolicy -n dev......Events:  Type     Reason     Age               From               Message  ----     ------     ----              ----               -------  Normal   Scheduled  <unknown>         default-scheduler  Successfully assigned dev/pod-imagePullPolicy to node1  Normal   Pulling    32s               kubelet, node1     Pulling image "nginx:1.17.1"  Normal   Pulled     26s               kubelet, node1     Successfully pulled image "nginx:1.17.1"  Normal   Created    26s               kubelet, node1     Created container nginx  Normal   Started    25s               kubelet, node1     Started container nginx  Normal   Pulled     7s (x3 over 25s)  kubelet, node1     Container image "busybox:1.30" already present on machine  Normal   Created    7s (x3 over 25s)  kubelet, node1     Created container busybox  Normal   Started    7s (x3 over 25s)  kubelet, node1     Started container busybox</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <h4><a name="t40"></a><a id="_1768"></a>启动命令</h4> 
    <p>​ 在前面的案例中,一直有一个问题没有解决,就是的busybox容器一直没有成功运行,那么到底是什么原因导致这个容器的故障呢?</p> 
    <p>​ 原来busybox并不是一个程序,而是类似于一个工具类的集合,kubernetes集群启动管理后,它会自动关闭。解决方法就是让其一直在运行,这就用到了command配置。</p> 
    <p>创建pod-command.yaml文件,内容如下:</p> 
    <pre data-index="63" class="set-code-show prettyprint"><code class="prism language-yaml has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token key atrule">apiVersion</span><span class="token punctuation">:</span> <span class="token key atrule">v1kind</span><span class="token punctuation">:</span> <span class="token key atrule">Podmetadata</span><span class="token punctuation">:</span>  <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">pod-command  namespace</span><span class="token punctuation">:</span> <span class="token key atrule">devspec</span><span class="token punctuation">:</span>  <span class="token key atrule">containers</span><span class="token punctuation">:</span>  <span class="token punctuation">-</span> <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">nginx    image</span><span class="token punctuation">:</span> <span class="token key atrule">nginx:1.17.1  - name</span><span class="token punctuation">:</span> <span class="token key atrule">busybox    image</span><span class="token punctuation">:</span> <span class="token key atrule">busybox:1.30    command</span><span class="token punctuation">:</span> <span class="token punctuation">[</span><span class="token string">"/bin/sh"</span><span class="token punctuation">,</span><span class="token string">"-c"</span><span class="token punctuation">,</span><span class="token string">"touch /tmp/hello.txt;while true;do /bin/echo $(date +%T) >> /tmp/hello.txt; sleep 3; done;"</span><span class="token punctuation">]</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <p>command,用于在pod中的容器初始化完毕之后运行一个命令。</p> 
    <blockquote> 
     <p>稍微解释下上面命令的意思:</p> 
     <p>​ “/bin/sh”,“-c”, 使用sh执行命令</p> 
     <p>​ touch /tmp/hello.txt; 创建一个/tmp/hello.txt 文件</p> 
     <p>​ while true;do /bin/echo $(date +%T) >> /tmp/hello.txt; sleep 3; done; 每隔3秒向文件中写入当前时间</p> 
    </blockquote> 
    <pre data-index="64" class="set-code-hide prettyprint"><code class="prism language-powershell has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token comment"># 创建Pod</span>
    <span class="token namespace">[root@master pod]</span><span class="token comment"># kubectl create  -f pod-command.yaml</span>
    pod/pod-command created
    
    <span class="token comment"># 查看Pod状态</span>
    <span class="token comment"># 此时发现两个pod都正常运行了</span>
    <span class="token namespace">[root@master pod]</span><span class="token comment"># kubectl get pods pod-command -n dev</span>
    NAME          READY   STATUS   RESTARTS   AGE
    pod-command   2/2     Runing   0          2s
    
    <span class="token comment"># 进入pod中的busybox容器,查看文件内容</span>
    <span class="token comment"># 补充一个命令: kubectl exec  pod名称 -n 命名空间 -it -c 容器名称 /bin/sh  在容器内部执行命令</span>
    <span class="token comment"># 使用这个命令就可以进入某个容器的内部,然后进行相关操作了</span>
    <span class="token comment"># 比如,可以查看txt文件的内容</span>
    <span class="token namespace">[root@master pod]</span><span class="token comment"># kubectl exec pod-command -n dev -it -c busybox /bin/sh</span>
    <span class="token operator">/</span> <span class="token comment"># tail -f /tmp/hello.txt</span>
    13:35:35
    13:35:38
    13:35:41
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><div class="hide-preCode-box"><span class="hide-preCode-bt" data-report-view="{"spm":"1001.2101.3001.7365"}"><img class="look-more-preCode contentImg-no-view" src="https://1000bd.com/contentImg/2022/06/27/191644837.png" alt="" title=""></span></div><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li><li style="color: rgb(153, 153, 153);">2</li><li style="color: rgb(153, 153, 153);">3</li><li style="color: rgb(153, 153, 153);">4</li><li style="color: rgb(153, 153, 153);">5</li><li style="color: rgb(153, 153, 153);">6</li><li style="color: rgb(153, 153, 153);">7</li><li style="color: rgb(153, 153, 153);">8</li><li style="color: rgb(153, 153, 153);">9</li><li style="color: rgb(153, 153, 153);">10</li><li style="color: rgb(153, 153, 153);">11</li><li style="color: rgb(153, 153, 153);">12</li><li style="color: rgb(153, 153, 153);">13</li><li style="color: rgb(153, 153, 153);">14</li><li style="color: rgb(153, 153, 153);">15</li><li style="color: rgb(153, 153, 153);">16</li><li style="color: rgb(153, 153, 153);">17</li><li style="color: rgb(153, 153, 153);">18</li><li style="color: rgb(153, 153, 153);">19</li></ul></pre> 
    <pre data-index="65" class="set-code-show prettyprint"><code class="prism language-md has-numbering" onclick="mdcp.signin(event)" style="position: unset;">特别说明:
        通过上面发现command已经可以完成启动命令和传递参数的功能,为什么这里还要提供一个args选项,用于传递参数呢?这其实跟docker有点关系,kubernetes中的command、args两项其实是实现覆盖Dockerfile中ENTRYPOINT的功能。
     1 如果command和args均没有写,那么用Dockerfile的配置。
     2 如果command写了,但args没有写,那么Dockerfile默认的配置会被忽略,执行输入的command
     3 如果command没写,但args写了,那么Dockerfile中配置的ENTRYPOINT的命令会被执行,使用当前args的参数
     4 如果command和args都写了,那么Dockerfile的配置被忽略,执行command并追加上args参数
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li><li style="color: rgb(153, 153, 153);">2</li><li style="color: rgb(153, 153, 153);">3</li><li style="color: rgb(153, 153, 153);">4</li><li style="color: rgb(153, 153, 153);">5</li><li style="color: rgb(153, 153, 153);">6</li></ul></pre> 
    <h4><a name="t41"></a><a id="_1821"></a>环境变量</h4> 
    <p>创建pod-env.yaml文件,内容如下:</p> 
    <pre data-index="66" class="set-code-show prettyprint"><code class="prism language-yaml has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token key atrule">apiVersion</span><span class="token punctuation">:</span> <span class="token key atrule">v1kind</span><span class="token punctuation">:</span> <span class="token key atrule">Podmetadata</span><span class="token punctuation">:</span>  <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">pod-env  namespace</span><span class="token punctuation">:</span> <span class="token key atrule">devspec</span><span class="token punctuation">:</span>  <span class="token key atrule">containers</span><span class="token punctuation">:</span>  <span class="token punctuation">-</span> <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">busybox    image</span><span class="token punctuation">:</span> <span class="token key atrule">busybox:1.30    command</span><span class="token punctuation">:</span> <span class="token punctuation">[</span><span class="token string">"/bin/sh"</span><span class="token punctuation">,</span><span class="token string">"-c"</span><span class="token punctuation">,</span><span class="token string">"while true;do /bin/echo $(date +%T);sleep 60; done;"</span><span class="token punctuation">]</span>    env<span class="token punctuation">:</span> <span class="token comment"># 设置环境变量列表    - name: "username"      value: "admin"    - name: "password"      value: "123456"</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <p>env,环境变量,用于在pod中的容器设置环境变量。</p> 
    <pre data-index="67" class="set-code-show prettyprint"><code class="prism language-powershell has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token comment"># 创建Pod[root@master ~]# kubectl create -f pod-env.yamlpod/pod-env created# 进入容器,输出环境变量[root@master ~]# kubectl exec pod-env -n dev -c busybox -it /bin/sh/ # echo $usernameadmin/ # echo $password123456</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <p>这种方式不是很推荐,推荐将这些配置单独存储在配置文件中,这种方式将在后面介绍。</p> 
    <h4><a name="t42"></a><a id="_1837"></a>端口设置</h4> 
    <p>本小节来介绍容器的端口设置,也就是containers的ports选项。</p> 
    <p>首先看下ports支持的子选项:</p> 
    <pre data-index="68" class="set-code-show prettyprint"><code class="prism language-powershell has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token namespace">[root@master ~]</span><span class="token comment"># kubectl explain pod.spec.containers.portsKIND:     PodVERSION:  v1RESOURCE: ports <[]Object>FIELDS:   name         <string>  # 端口名称,如果指定,必须保证name在pod中是唯一的		   containerPort<integer> # 容器要监听的端口(0<x<65536)   hostPort     <integer> # 容器要在主机上公开的端口,如果设置,主机上只能运行容器的一个副本(一般省略)    hostIP       <string>  # 要将外部端口绑定到的主机IP(一般省略)   protocol     <string>  # 端口协议。必须是UDP、TCP或SCTP。默认为“TCP”。</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <p>接下来,编写一个测试案例,创建pod-ports.yaml</p> 
    <pre data-index="69" class="set-code-show prettyprint"><code class="prism language-yaml has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token key atrule">apiVersion</span><span class="token punctuation">:</span> <span class="token key atrule">v1kind</span><span class="token punctuation">:</span> <span class="token key atrule">Podmetadata</span><span class="token punctuation">:</span>  <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">pod-ports  namespace</span><span class="token punctuation">:</span> <span class="token key atrule">devspec</span><span class="token punctuation">:</span>  <span class="token key atrule">containers</span><span class="token punctuation">:</span>  <span class="token punctuation">-</span> <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">nginx    image</span><span class="token punctuation">:</span> <span class="token key atrule">nginx:1.17.1    ports</span><span class="token punctuation">:</span> <span class="token comment"># 设置容器暴露的端口列表    - name: nginx-port      containerPort: 80      protocol: TCP</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <pre data-index="70" class="set-code-show prettyprint"><code class="prism language-powershell has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token comment"># 创建Pod[root@master ~]# kubectl create -f pod-ports.yamlpod/pod-ports created# 查看pod# 在下面可以明显看到配置信息[root@master ~]# kubectl get pod pod-ports -n dev -o yaml......spec:  containers:  - image: nginx:1.17.1    imagePullPolicy: IfNotPresent    name: nginx    ports:    - containerPort: 80      name: nginx-port      protocol: TCP......</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <p>访问容器中的程序需要使用的是<code>podIp:containerPort</code></p> 
    <h4><a name="t43"></a><a id="_1859"></a>资源配额</h4> 
    <p>​ 容器中的程序要运行,肯定是要占用一定资源的,比如cpu和内存等,如果不对某个容器的资源做限制,那么它就可能吃掉大量资源,导致其它容器无法运行。针对这种情况,kubernetes提供了对内存和cpu的资源进行配额的机制,这种机制主要通过resources选项实现,他有两个子选项:</p> 
    <ul><li> <p>limits:用于限制运行时容器的最大占用资源,当容器占用资源超过limits时会被终止,并进行重启</p> </li><li> <p>requests :用于设置容器需要的最小资源,如果环境资源不够,容器将无法启动</p> </li></ul> 
    <p>可以通过上面两个选项设置资源的上下限。</p> 
    <p>接下来,编写一个测试案例,创建pod-resources.yaml</p> 
    <pre data-index="71" class="set-code-show prettyprint"><code class="prism language-yaml has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token key atrule">apiVersion</span><span class="token punctuation">:</span> <span class="token key atrule">v1kind</span><span class="token punctuation">:</span> <span class="token key atrule">Podmetadata</span><span class="token punctuation">:</span>  <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">pod-resources  namespace</span><span class="token punctuation">:</span> <span class="token key atrule">devspec</span><span class="token punctuation">:</span>  <span class="token key atrule">containers</span><span class="token punctuation">:</span>  <span class="token punctuation">-</span> <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">nginx    image</span><span class="token punctuation">:</span> <span class="token key atrule">nginx:1.17.1    resources</span><span class="token punctuation">:</span> <span class="token comment"># 资源配额      limits:  # 限制资源(上限)        cpu: "2" # CPU限制,单位是core数        memory: "10Gi" # 内存限制      requests: # 请求资源(下限)        cpu: "1"  # CPU限制,单位是core数        memory: "10Mi"  # 内存限制</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <p>在这对cpu和memory的单位做一个说明:</p> 
    <ul><li> <p>cpu:core数,可以为整数或小数</p> </li><li> <p>memory: 内存大小,可以使用Gi、Mi、G、M等形式</p> </li></ul> 
    <pre data-index="72" class="set-code-show prettyprint"><code class="prism language-powershell has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token comment"># 运行Pod[root@master ~]# kubectl create  -f pod-resources.yamlpod/pod-resources created# 查看发现pod运行正常[root@master ~]# kubectl get pod pod-resources -n devNAME            READY   STATUS    RESTARTS   AGE  pod-resources   1/1     Running   0          39s   # 接下来,停止Pod[root@master ~]# kubectl delete  -f pod-resources.yamlpod "pod-resources" deleted# 编辑pod,修改resources.requests.memory的值为10Gi[root@master ~]# vim pod-resources.yaml# 再次启动pod[root@master ~]# kubectl create  -f pod-resources.yamlpod/pod-resources created# 查看Pod状态,发现Pod启动失败[root@master ~]# kubectl get pod pod-resources -n dev -o wideNAME            READY   STATUS    RESTARTS   AGE          pod-resources   0/2     Pending   0          20s    # 查看pod详情会发现,如下提示[root@master ~]# kubectl describe pod pod-resources -n dev......Warning  FailedScheduling  <unknown>  default-scheduler  0/2 nodes are available: 2 Insufficient memory.(内存不足)</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <h3><a name="t44"></a><a id="Pod_1885"></a>Pod生命周期</h3> 
    <p>我们一般将pod对象从创建至终的这段时间范围称为pod的生命周期,它主要包含下面的过程:</p> 
    <ul><li> <p>pod创建过程</p> </li><li> <p>运行初始化容器(init container)过程</p> </li><li> <p>运行主容器(main container)</p> 
      <ul><li> <p>容器启动后钩子(post start)、容器终止前钩子(pre stop)</p> </li><li> <p>容器的存活性探测(liveness probe)、就绪性探测(readiness probe)</p> </li></ul> </li><li> <p>pod终止过程</p> </li></ul> 
    <img src="https://1000bd.com/contentImg/2023/10/27/000132547.png" alt="image-20200412111402706"> 
    <p>在整个生命周期中,Pod会出现5种<strong>状态</strong>(<strong>相位</strong>),分别如下:</p> 
    <ul><li>挂起(Pending):apiserver已经创建了pod资源对象,但它尚未被调度完成或者仍处于下载镜像的过程中</li><li>运行中(Running):pod已经被调度至某节点,并且所有容器都已经被kubelet创建完成</li><li>成功(Succeeded):pod中的所有容器都已经成功终止并且不会被重启</li><li>失败(Failed):所有容器都已经终止,但至少有一个容器终止失败,即容器返回了非0值的退出状态</li><li>未知(Unknown):apiserver无法正常获取到pod对象的状态信息,通常由网络通信失败所导致</li></ul> 
    <h4><a name="t45"></a><a id="_1912"></a>创建和终止</h4> 
    <p><strong>pod的创建过程</strong></p> 
    <ol><li> <p>用户通过kubectl或其他api客户端提交需要创建的pod信息给apiServer</p> </li><li> <p>apiServer开始生成pod对象的信息,并将信息存入etcd,然后返回确认信息至客户端</p> </li><li> <p>apiServer开始反映etcd中的pod对象的变化,其它组件使用watch机制来跟踪检查apiServer上的变动</p> </li><li> <p>scheduler发现有新的pod对象要创建,开始为Pod分配主机并将结果信息更新至apiServer</p> </li><li> <p>node节点上的kubelet发现有pod调度过来,尝试调用docker启动容器,并将结果回送至apiServer</p> </li><li> <p>apiServer将接收到的pod状态信息存入etcd中</p> <img src="https://1000bd.com/contentImg/2023/10/27/000132601.png" alt="image-20200406184656917"> </li></ol> 
    <p><strong>pod的终止过程</strong></p> 
    <ol><li>用户向apiServer发送删除pod对象的命令</li><li>apiServcer中的pod对象信息会随着时间的推移而更新,在宽限期内(默认30s),pod被视为dead</li><li>将pod标记为terminating状态</li><li>kubelet在监控到pod对象转为terminating状态的同时启动pod关闭过程</li><li>端点控制器监控到pod对象的关闭行为时将其从所有匹配到此端点的service资源的端点列表中移除</li><li>如果当前pod对象定义了preStop钩子处理器,则在其标记为terminating后即会以同步的方式启动执行</li><li>pod对象中的容器进程收到停止信号</li><li>宽限期结束后,若pod中还存在仍在运行的进程,那么pod对象会收到立即终止的信号</li><li>kubelet请求apiServer将此pod资源的宽限期设置为0从而完成删除操作,此时pod对于用户已不可见</li></ol> 
    <h4><a name="t46"></a><a id="_1943"></a>初始化容器</h4> 
    <p>初始化容器是在pod的主容器启动之前要运行的容器,主要是做一些主容器的前置工作,它具有两大特征:</p> 
    <ol><li>初始化容器必须运行完成直至结束,若某初始化容器运行失败,那么kubernetes需要重启它直到成功完成</li><li>初始化容器必须按照定义的顺序执行,当且仅当前一个成功之后,后面的一个才能运行</li></ol> 
    <p>初始化容器有很多的应用场景,下面列出的是最常见的几个:</p> 
    <ul><li>提供主容器镜像中不具备的工具程序或自定义代码</li><li>初始化容器要先于应用容器串行启动并运行完成,因此可用于延后应用容器的启动直至其依赖的条件得到满足</li></ul> 
    <p>接下来做一个案例,模拟下面这个需求:</p> 
    <p>​ 假设要以主容器来运行nginx,但是要求在运行nginx之前先要能够连接上mysql和redis所在服务器</p> 
    <p>​ 为了简化测试,事先规定好mysql<code>(192.168.109.201)</code>和redis<code>(192.168.109.202)</code>服务器的地址</p> 
    <p>创建pod-initcontainer.yaml,内容如下:</p> 
    <pre data-index="73" class="set-code-show prettyprint"><code class="prism language-yaml has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token key atrule">apiVersion</span><span class="token punctuation">:</span> <span class="token key atrule">v1kind</span><span class="token punctuation">:</span> <span class="token key atrule">Podmetadata</span><span class="token punctuation">:</span>  <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">pod-initcontainer  namespace</span><span class="token punctuation">:</span> <span class="token key atrule">devspec</span><span class="token punctuation">:</span>  <span class="token key atrule">containers</span><span class="token punctuation">:</span>  <span class="token punctuation">-</span> <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">main-container    image</span><span class="token punctuation">:</span> <span class="token key atrule">nginx:1.17.1    ports</span><span class="token punctuation">:</span>     <span class="token punctuation">-</span> <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">nginx-port      containerPort</span><span class="token punctuation">:</span> <span class="token key atrule">80  initContainers</span><span class="token punctuation">:</span>  <span class="token punctuation">-</span> <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">test-mysql    image</span><span class="token punctuation">:</span> <span class="token key atrule">busybox:1.30    command</span><span class="token punctuation">:</span> <span class="token punctuation">[</span><span class="token string">'sh'</span><span class="token punctuation">,</span> <span class="token string">'-c'</span><span class="token punctuation">,</span> <span class="token string">'until ping 192.168.109.201 -c 1 ; do echo waiting for mysql...; sleep 2; done;'</span><span class="token punctuation">]</span>  <span class="token punctuation">-</span> <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">test-redis    image</span><span class="token punctuation">:</span> <span class="token key atrule">busybox:1.30    command</span><span class="token punctuation">:</span> <span class="token punctuation">[</span><span class="token string">'sh'</span><span class="token punctuation">,</span> <span class="token string">'-c'</span><span class="token punctuation">,</span> <span class="token string">'until ping 192.168.109.202 -c 1 ; do echo waiting for reids...; sleep 2; done;'</span><span class="token punctuation">]</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <pre data-index="74" class="set-code-show prettyprint"><code class="prism language-powershell has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token comment"># 创建pod[root@master ~]# kubectl create -f pod-initcontainer.yamlpod/pod-initcontainer created# 查看pod状态# 发现pod卡在启动第一个初始化容器过程中,后面的容器不会运行root@master ~]# kubectl describe pod  pod-initcontainer -n dev........Events:  Type    Reason     Age   From               Message  ----    ------     ----  ----               -------  Normal  Scheduled  49s   default-scheduler  Successfully assigned dev/pod-initcontainer to node1  Normal  Pulled     48s   kubelet, node1     Container image "busybox:1.30" already present on machine  Normal  Created    48s   kubelet, node1     Created container test-mysql  Normal  Started    48s   kubelet, node1     Started container test-mysql# 动态查看pod[root@master ~]# kubectl get pods pod-initcontainer -n dev -wNAME                             READY   STATUS     RESTARTS   AGEpod-initcontainer                0/1     Init:0/2   0          15spod-initcontainer                0/1     Init:1/2   0          52spod-initcontainer                0/1     Init:1/2   0          53spod-initcontainer                0/1     PodInitializing   0          89spod-initcontainer                1/1     Running           0          90s# 接下来新开一个shell,为当前服务器新增两个ip,观察pod的变化[root@master ~]# ifconfig ens33:1 192.168.109.201 netmask 255.255.255.0 up[root@master ~]# ifconfig ens33:2 192.168.109.202 netmask 255.255.255.0 up</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <h4><a name="t47"></a><a id="_1971"></a>钩子函数</h4> 
    <p>钩子函数能够感知自身生命周期中的事件,并在相应的时刻到来时运行用户指定的程序代码。</p> 
    <p>kubernetes在主容器的启动之后和停止之前提供了两个钩子函数:</p> 
    <ul><li>post start:容器创建之后执行,如果失败了会重启容器</li><li>pre stop :容器终止之前执行,执行完成之后容器将成功终止,在其完成之前会阻塞删除容器的操作</li></ul> 
    <p>钩子处理器支持使用下面三种方式定义动作:</p> 
    <ul><li> <p>Exec命令:在容器内执行一次命令</p> <pre data-index="75" class="set-code-show prettyprint"><code class="prism language-yaml has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token key atrule">……  lifecycle</span><span class="token punctuation">:</span>    <span class="token key atrule">postStart</span><span class="token punctuation">:</span>       <span class="token key atrule">exec</span><span class="token punctuation">:</span>        <span class="token key atrule">command</span><span class="token punctuation">:</span>        <span class="token punctuation">-</span> cat        <span class="token punctuation">-</span> /tmp/healthy……
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> </li><li> <p>TCPSocket:在当前容器尝试访问指定的socket</p> <pre data-index="76" class="set-code-show prettyprint"><code class="prism language-yaml has-numbering" onclick="mdcp.signin(event)" style="position: unset;">……      
      <span class="token key atrule">lifecycle</span><span class="token punctuation">:</span>
        <span class="token key atrule">postStart</span><span class="token punctuation">:</span>
          <span class="token key atrule">tcpSocket</span><span class="token punctuation">:</span>
            <span class="token key atrule">port</span><span class="token punctuation">:</span> <span class="token number">8080</span>
    ……
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li><li style="color: rgb(153, 153, 153);">2</li><li style="color: rgb(153, 153, 153);">3</li><li style="color: rgb(153, 153, 153);">4</li><li style="color: rgb(153, 153, 153);">5</li><li style="color: rgb(153, 153, 153);">6</li></ul></pre> </li><li> <p>HTTPGet:在当前容器中向某url发起http请求</p> <pre data-index="77" class="set-code-show prettyprint"><code class="prism language-yaml has-numbering" onclick="mdcp.signin(event)" style="position: unset;">……
      <span class="token key atrule">lifecycle</span><span class="token punctuation">:</span>
        <span class="token key atrule">postStart</span><span class="token punctuation">:</span>
          <span class="token key atrule">httpGet</span><span class="token punctuation">:</span>
            <span class="token key atrule">path</span><span class="token punctuation">:</span> / <span class="token comment">#URI地址</span>
            <span class="token key atrule">port</span><span class="token punctuation">:</span> <span class="token number">80</span> <span class="token comment">#端口号</span>
            <span class="token key atrule">host</span><span class="token punctuation">:</span> 192.168.109.100 <span class="token comment">#主机地址</span>
            <span class="token key atrule">scheme</span><span class="token punctuation">:</span> HTTP <span class="token comment">#支持的协议,http或者https</span>
    ……
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li><li style="color: rgb(153, 153, 153);">2</li><li style="color: rgb(153, 153, 153);">3</li><li style="color: rgb(153, 153, 153);">4</li><li style="color: rgb(153, 153, 153);">5</li><li style="color: rgb(153, 153, 153);">6</li><li style="color: rgb(153, 153, 153);">7</li><li style="color: rgb(153, 153, 153);">8</li><li style="color: rgb(153, 153, 153);">9</li></ul></pre> </li></ul> 
    <p>接下来,以exec方式为例,演示下钩子函数的使用,创建pod-hook-exec.yaml文件,内容如下:</p> 
    <pre data-index="78" class="set-code-hide prettyprint"><code class="prism language-yaml has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token key atrule">apiVersion</span><span class="token punctuation">:</span> v1
    <span class="token key atrule">kind</span><span class="token punctuation">:</span> Pod
    <span class="token key atrule">metadata</span><span class="token punctuation">:</span>
      <span class="token key atrule">name</span><span class="token punctuation">:</span> pod<span class="token punctuation">-</span>hook<span class="token punctuation">-</span>exec
      <span class="token key atrule">namespace</span><span class="token punctuation">:</span> dev
    <span class="token key atrule">spec</span><span class="token punctuation">:</span>
      <span class="token key atrule">containers</span><span class="token punctuation">:</span>
      <span class="token punctuation">-</span> <span class="token key atrule">name</span><span class="token punctuation">:</span> main<span class="token punctuation">-</span>container
        <span class="token key atrule">image</span><span class="token punctuation">:</span> nginx<span class="token punctuation">:</span>1.17.1
        <span class="token key atrule">ports</span><span class="token punctuation">:</span>
        <span class="token punctuation">-</span> <span class="token key atrule">name</span><span class="token punctuation">:</span> nginx<span class="token punctuation">-</span>port
          <span class="token key atrule">containerPort</span><span class="token punctuation">:</span> <span class="token number">80</span>
        <span class="token key atrule">lifecycle</span><span class="token punctuation">:</span>
          <span class="token key atrule">postStart</span><span class="token punctuation">:</span> 
            <span class="token key atrule">exec</span><span class="token punctuation">:</span> <span class="token comment"># 在容器启动的时候执行一个命令,修改掉nginx的默认首页内容</span>
              <span class="token key atrule">command</span><span class="token punctuation">:</span> <span class="token punctuation">[</span><span class="token string">"/bin/sh"</span><span class="token punctuation">,</span> <span class="token string">"-c"</span><span class="token punctuation">,</span> <span class="token string">"echo postStart... > /usr/share/nginx/html/index.html"</span><span class="token punctuation">]</span>
          <span class="token key atrule">preStop</span><span class="token punctuation">:</span>
            <span class="token key atrule">exec</span><span class="token punctuation">:</span> <span class="token comment"># 在容器停止之前停止nginx服务</span>
              <span class="token key atrule">command</span><span class="token punctuation">:</span> <span class="token punctuation">[</span><span class="token string">"/usr/sbin/nginx"</span><span class="token punctuation">,</span><span class="token string">"-s"</span><span class="token punctuation">,</span><span class="token string">"quit"</span><span class="token punctuation">]</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><div class="hide-preCode-box"><span class="hide-preCode-bt" data-report-view="{"spm":"1001.2101.3001.7365"}"><img class="look-more-preCode contentImg-no-view" src="https://1000bd.com/contentImg/2022/06/27/191644837.png" alt="" title=""></span></div><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li><li style="color: rgb(153, 153, 153);">2</li><li style="color: rgb(153, 153, 153);">3</li><li style="color: rgb(153, 153, 153);">4</li><li style="color: rgb(153, 153, 153);">5</li><li style="color: rgb(153, 153, 153);">6</li><li style="color: rgb(153, 153, 153);">7</li><li style="color: rgb(153, 153, 153);">8</li><li style="color: rgb(153, 153, 153);">9</li><li style="color: rgb(153, 153, 153);">10</li><li style="color: rgb(153, 153, 153);">11</li><li style="color: rgb(153, 153, 153);">12</li><li style="color: rgb(153, 153, 153);">13</li><li style="color: rgb(153, 153, 153);">14</li><li style="color: rgb(153, 153, 153);">15</li><li style="color: rgb(153, 153, 153);">16</li><li style="color: rgb(153, 153, 153);">17</li><li style="color: rgb(153, 153, 153);">18</li><li style="color: rgb(153, 153, 153);">19</li></ul></pre> 
    <pre data-index="79" class="set-code-show prettyprint"><code class="prism language-powershell has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token comment"># 创建pod[root@master ~]# kubectl create -f pod-hook-exec.yamlpod/pod-hook-exec created# 查看pod[root@master ~]# kubectl get pods  pod-hook-exec -n dev -o wideNAME           READY   STATUS     RESTARTS   AGE    IP            NODE    pod-hook-exec  1/1     Running    0          29s    10.244.2.48   node2   # 访问pod[root@master ~]# curl 10.244.2.48postStart...</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <h4><a name="t48"></a><a id="_2041"></a>容器探测</h4> 
    <p>​ 容器探测用于检测容器中的应用实例是否正常工作,是保障业务可用性的一种传统机制。如果经过探测,实例的状态不符合预期,那么kubernetes就会把该问题实例" 摘除 ",不承担业务流量。kubernetes提供了两种探针来实现容器探测,分别是:</p> 
    <ul><li> <p>liveness probes:存活性探针,用于检测应用实例当前是否处于正常运行状态,如果不是,k8s会重启容器</p> </li><li> <p>readiness probes:就绪性探针,用于检测应用实例当前是否可以接收请求,如果不能,k8s不会转发流量</p> </li></ul> 
    <blockquote> 
     <p>livenessProbe 决定是否重启容器,readinessProbe 决定是否将请求转发给容器。</p> 
    </blockquote> 
    <p>上面两种探针目前均支持三种探测方式:</p> 
    <ul><li> <p>Exec命令:在容器内执行一次命令,如果命令执行的退出码为0,则认为程序正常,否则不正常</p> <pre data-index="80" class="set-code-show prettyprint"><code class="prism language-yaml has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token key atrule">……  livenessProbe</span><span class="token punctuation">:</span>    <span class="token key atrule">exec</span><span class="token punctuation">:</span>      <span class="token key atrule">command</span><span class="token punctuation">:</span>      <span class="token punctuation">-</span> cat      <span class="token punctuation">-</span> /tmp/healthy……
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> </li><li> <p>TCPSocket:将会尝试访问一个用户容器的端口,如果能够建立这条连接,则认为程序正常,否则不正常</p> <pre data-index="81" class="set-code-show prettyprint"><code class="prism language-yaml has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token key atrule">……        livenessProbe</span><span class="token punctuation">:</span>    <span class="token key atrule">tcpSocket</span><span class="token punctuation">:</span>      <span class="token key atrule">port</span><span class="token punctuation">:</span> 8080……
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> </li><li> <p>HTTPGet:调用容器内Web应用的URL,如果返回的状态码在200和399之间,则认为程序正常,否则不正常</p> <pre data-index="82" class="set-code-show prettyprint"><code class="prism language-yaml has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token key atrule">……  livenessProbe</span><span class="token punctuation">:</span>    <span class="token key atrule">httpGet</span><span class="token punctuation">:</span>      <span class="token key atrule">path</span><span class="token punctuation">:</span> / <span class="token comment">#URI地址      port: 80 #端口号      host: 127.0.0.1 #主机地址      scheme: HTTP #支持的协议,http或者https……</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> </li></ul> 
    <p>下面以liveness probes为例,做几个演示:</p> 
    <p><strong>方式一:Exec</strong></p> 
    <p>创建pod-liveness-exec.yaml</p> 
    <pre data-index="83" class="set-code-show prettyprint"><code class="prism language-yaml has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token key atrule">apiVersion</span><span class="token punctuation">:</span> <span class="token key atrule">v1kind</span><span class="token punctuation">:</span> <span class="token key atrule">Podmetadata</span><span class="token punctuation">:</span>  <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">pod-liveness-exec  namespace</span><span class="token punctuation">:</span> <span class="token key atrule">devspec</span><span class="token punctuation">:</span>  <span class="token key atrule">containers</span><span class="token punctuation">:</span>  <span class="token punctuation">-</span> <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">nginx    image</span><span class="token punctuation">:</span> <span class="token key atrule">nginx:1.17.1    ports</span><span class="token punctuation">:</span>     <span class="token punctuation">-</span> <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">nginx-port      containerPort</span><span class="token punctuation">:</span> <span class="token key atrule">80    livenessProbe</span><span class="token punctuation">:</span>      <span class="token key atrule">exec</span><span class="token punctuation">:</span>        <span class="token key atrule">command</span><span class="token punctuation">:</span> <span class="token punctuation">[</span><span class="token string">"/bin/cat"</span><span class="token punctuation">,</span><span class="token string">"/tmp/hello.txt"</span><span class="token punctuation">]</span> <span class="token comment"># 执行一个查看文件的命令</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <p>创建pod,观察效果</p> 
    <pre data-index="84" class="set-code-show prettyprint"><code class="prism language-powershell has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token comment"># 创建Pod[root@master ~]# kubectl create -f pod-liveness-exec.yamlpod/pod-liveness-exec created# 查看Pod详情[root@master ~]# kubectl describe pods pod-liveness-exec -n dev......  Normal   Created    20s (x2 over 50s)  kubelet, node1     Created container nginx  Normal   Started    20s (x2 over 50s)  kubelet, node1     Started container nginx  Normal   Killing    20s                kubelet, node1     Container nginx failed liveness probe, will be restarted  Warning  Unhealthy  0s (x5 over 40s)   kubelet, node1     Liveness probe failed: cat: can't open '/tmp/hello11.txt': No such file or directory  # 观察上面的信息就会发现nginx容器启动之后就进行了健康检查# 检查失败之后,容器被kill掉,然后尝试进行重启(这是重启策略的作用,后面讲解)# 稍等一会之后,再观察pod信息,就可以看到RESTARTS不再是0,而是一直增长[root@master ~]# kubectl get pods pod-liveness-exec -n devNAME                READY   STATUS             RESTARTS   AGEpod-liveness-exec   0/1     CrashLoopBackOff   2          3m19s# 当然接下来,可以修改成一个存在的文件,比如/tmp/hello.txt,再试,结果就正常了......</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <p><strong>方式二:TCPSocket</strong></p> 
    <p>创建pod-liveness-tcpsocket.yaml</p> 
    <pre data-index="85" class="set-code-show prettyprint"><code class="prism language-yaml has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token key atrule">apiVersion</span><span class="token punctuation">:</span> <span class="token key atrule">v1kind</span><span class="token punctuation">:</span> <span class="token key atrule">Podmetadata</span><span class="token punctuation">:</span>  <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">pod-liveness-tcpsocket  namespace</span><span class="token punctuation">:</span> <span class="token key atrule">devspec</span><span class="token punctuation">:</span>  <span class="token key atrule">containers</span><span class="token punctuation">:</span>  <span class="token punctuation">-</span> <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">nginx    image</span><span class="token punctuation">:</span> <span class="token key atrule">nginx:1.17.1    ports</span><span class="token punctuation">:</span>     <span class="token punctuation">-</span> <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">nginx-port      containerPort</span><span class="token punctuation">:</span> <span class="token key atrule">80    livenessProbe</span><span class="token punctuation">:</span>      <span class="token key atrule">tcpSocket</span><span class="token punctuation">:</span>        <span class="token key atrule">port</span><span class="token punctuation">:</span> <span class="token number">8080</span> <span class="token comment"># 尝试访问8080端口</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <p>创建pod,观察效果</p> 
    <pre data-index="86" class="set-code-show prettyprint"><code class="prism language-powershell has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token comment"># 创建Pod[root@master ~]# kubectl create -f pod-liveness-tcpsocket.yamlpod/pod-liveness-tcpsocket created# 查看Pod详情[root@master ~]# kubectl describe pods pod-liveness-tcpsocket -n dev......  Normal   Scheduled  31s                            default-scheduler  Successfully assigned dev/pod-liveness-tcpsocket to node2  Normal   Pulled     <invalid>                      kubelet, node2     Container image "nginx:1.17.1" already present on machine  Normal   Created    <invalid>                      kubelet, node2     Created container nginx  Normal   Started    <invalid>                      kubelet, node2     Started container nginx  Warning  Unhealthy  <invalid> (x2 over <invalid>)  kubelet, node2     Liveness probe failed: dial tcp 10.244.2.44:8080: connect: connection refused  # 观察上面的信息,发现尝试访问8080端口,但是失败了# 稍等一会之后,再观察pod信息,就可以看到RESTARTS不再是0,而是一直增长[root@master ~]# kubectl get pods pod-liveness-tcpsocket  -n devNAME                     READY   STATUS             RESTARTS   AGEpod-liveness-tcpsocket   0/1     CrashLoopBackOff   2          3m19s# 当然接下来,可以修改成一个可以访问的端口,比如80,再试,结果就正常了......</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <p><strong>方式三:HTTPGet</strong></p> 
    <p>创建pod-liveness-httpget.yaml</p> 
    <pre data-index="87" class="set-code-show prettyprint"><code class="prism language-yaml has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token key atrule">apiVersion</span><span class="token punctuation">:</span> <span class="token key atrule">v1kind</span><span class="token punctuation">:</span> <span class="token key atrule">Podmetadata</span><span class="token punctuation">:</span>  <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">pod-liveness-httpget  namespace</span><span class="token punctuation">:</span> <span class="token key atrule">devspec</span><span class="token punctuation">:</span>  <span class="token key atrule">containers</span><span class="token punctuation">:</span>  <span class="token punctuation">-</span> <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">nginx    image</span><span class="token punctuation">:</span> <span class="token key atrule">nginx:1.17.1    ports</span><span class="token punctuation">:</span>    <span class="token punctuation">-</span> <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">nginx-port      containerPort</span><span class="token punctuation">:</span> <span class="token key atrule">80    livenessProbe</span><span class="token punctuation">:</span>      <span class="token key atrule">httpGet</span><span class="token punctuation">:</span>  <span class="token comment"># 其实就是访问http://127.0.0.1:80/hello          scheme: HTTP #支持的协议,http或者https        port: 80 #端口号        path: /hello #URI地址</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <p>创建pod,观察效果</p> 
    <pre data-index="88" class="set-code-show prettyprint"><code class="prism language-powershell has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token comment"># 创建Pod[root@master ~]# kubectl create -f pod-liveness-httpget.yamlpod/pod-liveness-httpget created# 查看Pod详情[root@master ~]# kubectl describe pod pod-liveness-httpget -n dev.......  Normal   Pulled     6s (x3 over 64s)  kubelet, node1     Container image "nginx:1.17.1" already present on machine  Normal   Created    6s (x3 over 64s)  kubelet, node1     Created container nginx  Normal   Started    6s (x3 over 63s)  kubelet, node1     Started container nginx  Warning  Unhealthy  6s (x6 over 56s)  kubelet, node1     Liveness probe failed: HTTP probe failed with statuscode: 404  Normal   Killing    6s (x2 over 36s)  kubelet, node1     Container nginx failed liveness probe, will be restarted  # 观察上面信息,尝试访问路径,但是未找到,出现404错误# 稍等一会之后,再观察pod信息,就可以看到RESTARTS不再是0,而是一直增长[root@master ~]# kubectl get pod pod-liveness-httpget -n devNAME                   READY   STATUS    RESTARTS   AGEpod-liveness-httpget   1/1     Running   5          3m17s# 当然接下来,可以修改成一个可以访问的路径path,比如/,再试,结果就正常了......</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <p>​ 至此,已经使用liveness Probe演示了三种探测方式,但是查看livenessProbe的子属性,会发现除了这三种方式,还有一些其他的配置,在这里一并解释下:</p> 
    <pre data-index="89" class="set-code-show prettyprint"><code class="prism language-powershell has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token namespace">[root@master ~]</span><span class="token comment"># kubectl explain pod.spec.containers.livenessProbeFIELDS:   exec <Object>     tcpSocket    <Object>   httpGet      <Object>   initialDelaySeconds  <integer>  # 容器启动后等待多少秒执行第一次探测   timeoutSeconds       <integer>  # 探测超时时间。默认1秒,最小1秒   periodSeconds        <integer>  # 执行探测的频率。默认是10秒,最小1秒   failureThreshold     <integer>  # 连续探测失败多少次才被认定为失败。默认是3。最小值是1   successThreshold     <integer>  # 连续探测成功多少次才被认定为成功。默认是1</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <p>下面稍微配置两个,演示下效果即可:</p> 
    <pre data-index="90" class="set-code-hide prettyprint"><code class="prism language-yaml has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token punctuation">[</span>root@master ~<span class="token punctuation">]</span><span class="token comment"># more pod-liveness-httpget.yaml</span>
    <span class="token key atrule">apiVersion</span><span class="token punctuation">:</span> v1
    <span class="token key atrule">kind</span><span class="token punctuation">:</span> Pod
    <span class="token key atrule">metadata</span><span class="token punctuation">:</span>
      <span class="token key atrule">name</span><span class="token punctuation">:</span> pod<span class="token punctuation">-</span>liveness<span class="token punctuation">-</span>httpget
      <span class="token key atrule">namespace</span><span class="token punctuation">:</span> dev
    <span class="token key atrule">spec</span><span class="token punctuation">:</span>
      <span class="token key atrule">containers</span><span class="token punctuation">:</span>
      <span class="token punctuation">-</span> <span class="token key atrule">name</span><span class="token punctuation">:</span> nginx
        <span class="token key atrule">image</span><span class="token punctuation">:</span> nginx<span class="token punctuation">:</span>1.17.1
        <span class="token key atrule">ports</span><span class="token punctuation">:</span>
        <span class="token punctuation">-</span> <span class="token key atrule">name</span><span class="token punctuation">:</span> nginx<span class="token punctuation">-</span>port
          <span class="token key atrule">containerPort</span><span class="token punctuation">:</span> <span class="token number">80</span>
        <span class="token key atrule">livenessProbe</span><span class="token punctuation">:</span>
          <span class="token key atrule">httpGet</span><span class="token punctuation">:</span>
            <span class="token key atrule">scheme</span><span class="token punctuation">:</span> HTTP
            <span class="token key atrule">port</span><span class="token punctuation">:</span> <span class="token number">80</span> 
            <span class="token key atrule">path</span><span class="token punctuation">:</span> /
          <span class="token key atrule">initialDelaySeconds</span><span class="token punctuation">:</span> <span class="token number">30</span> <span class="token comment"># 容器启动后30s开始探测</span>
          <span class="token key atrule">timeoutSeconds</span><span class="token punctuation">:</span> <span class="token number">5</span> <span class="token comment"># 探测超时时间为5s</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><div class="hide-preCode-box"><span class="hide-preCode-bt" data-report-view="{"spm":"1001.2101.3001.7365"}"><img class="look-more-preCode contentImg-no-view" src="https://1000bd.com/contentImg/2022/06/27/191644837.png" alt="" title=""></span></div><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li><li style="color: rgb(153, 153, 153);">2</li><li style="color: rgb(153, 153, 153);">3</li><li style="color: rgb(153, 153, 153);">4</li><li style="color: rgb(153, 153, 153);">5</li><li style="color: rgb(153, 153, 153);">6</li><li style="color: rgb(153, 153, 153);">7</li><li style="color: rgb(153, 153, 153);">8</li><li style="color: rgb(153, 153, 153);">9</li><li style="color: rgb(153, 153, 153);">10</li><li style="color: rgb(153, 153, 153);">11</li><li style="color: rgb(153, 153, 153);">12</li><li style="color: rgb(153, 153, 153);">13</li><li style="color: rgb(153, 153, 153);">14</li><li style="color: rgb(153, 153, 153);">15</li><li style="color: rgb(153, 153, 153);">16</li><li style="color: rgb(153, 153, 153);">17</li><li style="color: rgb(153, 153, 153);">18</li><li style="color: rgb(153, 153, 153);">19</li><li style="color: rgb(153, 153, 153);">20</li></ul></pre> 
    <h4><a name="t49"></a><a id="_2146"></a>重启策略</h4> 
    <p>​ 在上一节中,一旦容器探测出现了问题,kubernetes就会对容器所在的Pod进行重启,其实这是由pod的重启策略决定的,pod的重启策略有 3 种,分别如下:</p> 
    <ul><li>Always :容器失效时,自动重启该容器,这也是默认值。</li><li>OnFailure : 容器终止运行且退出码不为0时重启</li><li>Never : 不论状态为何,都不重启该容器</li></ul> 
    <p>​ 重启策略适用于pod对象中的所有容器,首次需要重启的容器,将在其需要时立即进行重启,随后再次需要重启的操作将由kubelet延迟一段时间后进行,且反复的重启操作的延迟时长以此为10s、20s、40s、80s、160s和300s,300s是最大延迟时长。</p> 
    <p>创建pod-restartpolicy.yaml:</p> 
    <pre data-index="91" class="set-code-hide prettyprint"><code class="prism language-yaml has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token key atrule">apiVersion</span><span class="token punctuation">:</span> v1
    <span class="token key atrule">kind</span><span class="token punctuation">:</span> Pod
    <span class="token key atrule">metadata</span><span class="token punctuation">:</span>
      <span class="token key atrule">name</span><span class="token punctuation">:</span> pod<span class="token punctuation">-</span>restartpolicy
      <span class="token key atrule">namespace</span><span class="token punctuation">:</span> dev
    <span class="token key atrule">spec</span><span class="token punctuation">:</span>
      <span class="token key atrule">containers</span><span class="token punctuation">:</span>
      <span class="token punctuation">-</span> <span class="token key atrule">name</span><span class="token punctuation">:</span> nginx
        <span class="token key atrule">image</span><span class="token punctuation">:</span> nginx<span class="token punctuation">:</span>1.17.1
        <span class="token key atrule">ports</span><span class="token punctuation">:</span>
        <span class="token punctuation">-</span> <span class="token key atrule">name</span><span class="token punctuation">:</span> nginx<span class="token punctuation">-</span>port
          <span class="token key atrule">containerPort</span><span class="token punctuation">:</span> <span class="token number">80</span>
        <span class="token key atrule">livenessProbe</span><span class="token punctuation">:</span>
          <span class="token key atrule">httpGet</span><span class="token punctuation">:</span>
            <span class="token key atrule">scheme</span><span class="token punctuation">:</span> HTTP
            <span class="token key atrule">port</span><span class="token punctuation">:</span> <span class="token number">80</span>
            <span class="token key atrule">path</span><span class="token punctuation">:</span> /hello
      <span class="token key atrule">restartPolicy</span><span class="token punctuation">:</span> Never <span class="token comment"># 设置重启策略为Never</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><div class="hide-preCode-box"><span class="hide-preCode-bt" data-report-view="{"spm":"1001.2101.3001.7365"}"><img class="look-more-preCode contentImg-no-view" src="https://1000bd.com/contentImg/2022/06/27/191644837.png" alt="" title=""></span></div><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li><li style="color: rgb(153, 153, 153);">2</li><li style="color: rgb(153, 153, 153);">3</li><li style="color: rgb(153, 153, 153);">4</li><li style="color: rgb(153, 153, 153);">5</li><li style="color: rgb(153, 153, 153);">6</li><li style="color: rgb(153, 153, 153);">7</li><li style="color: rgb(153, 153, 153);">8</li><li style="color: rgb(153, 153, 153);">9</li><li style="color: rgb(153, 153, 153);">10</li><li style="color: rgb(153, 153, 153);">11</li><li style="color: rgb(153, 153, 153);">12</li><li style="color: rgb(153, 153, 153);">13</li><li style="color: rgb(153, 153, 153);">14</li><li style="color: rgb(153, 153, 153);">15</li><li style="color: rgb(153, 153, 153);">16</li><li style="color: rgb(153, 153, 153);">17</li><li style="color: rgb(153, 153, 153);">18</li></ul></pre> 
    <p>运行Pod测试</p> 
    <pre data-index="92" class="set-code-show prettyprint"><code class="prism language-powershell has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token comment"># 创建Pod</span>
    <span class="token namespace">[root@master ~]</span><span class="token comment"># kubectl create -f pod-restartpolicy.yaml</span>
    pod/pod-restartpolicy created
    
    <span class="token comment"># 查看Pod详情,发现nginx容器失败</span>
    <span class="token namespace">[root@master ~]</span><span class="token comment"># kubectl  describe pods pod-restartpolicy  -n dev</span>
    <span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span>
      Warning  Unhealthy  15s <span class="token punctuation">(</span>x3 over 35s<span class="token punctuation">)</span>  kubelet<span class="token punctuation">,</span> node1     Liveness probe failed: HTTP probe failed with statuscode: 404
      Normal   Killing    15s                kubelet<span class="token punctuation">,</span> node1     Container nginx failed liveness probe
      
    <span class="token comment"># 多等一会,再观察pod的重启次数,发现一直是0,并未重启   </span>
    <span class="token namespace">[root@master ~]</span><span class="token comment"># kubectl  get pods pod-restartpolicy -n dev</span>
    NAME                   READY   STATUS    RESTARTS   AGE
    pod-restartpolicy      0/1     Running   0          5min42s
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li><li style="color: rgb(153, 153, 153);">2</li><li style="color: rgb(153, 153, 153);">3</li><li style="color: rgb(153, 153, 153);">4</li><li style="color: rgb(153, 153, 153);">5</li><li style="color: rgb(153, 153, 153);">6</li><li style="color: rgb(153, 153, 153);">7</li><li style="color: rgb(153, 153, 153);">8</li><li style="color: rgb(153, 153, 153);">9</li><li style="color: rgb(153, 153, 153);">10</li><li style="color: rgb(153, 153, 153);">11</li><li style="color: rgb(153, 153, 153);">12</li><li style="color: rgb(153, 153, 153);">13</li><li style="color: rgb(153, 153, 153);">14</li></ul></pre> 
    <h3><a name="t50"></a><a id="Pod_2198"></a>Pod调度</h3> 
    <p>​ 在默认情况下,一个Pod在哪个Node节点上运行,是由Scheduler组件采用相应的算法计算出来的,这个过程是不受人工控制的。但是在实际使用中,这并不满足的需求,因为很多情况下,我们想控制某些Pod到达某些节点上,那么应该怎么做呢?这就要求了解kubernetes对Pod的调度规则,kubernetes提供了四大类调度方式:</p> 
    <ul><li>自动调度:运行在哪个节点上完全由Scheduler经过一系列的算法计算得出</li><li>定向调度:NodeName、NodeSelector</li><li>亲和性调度:NodeAffinity、PodAffinity、PodAntiAffinity</li><li>污点(容忍)调度:Taints、Toleration</li></ul> 
    <h4><a name="t51"></a><a id="_2207"></a>定向调度</h4> 
    <p>​ 定向调度,指的是利用在pod上声明nodeName或者nodeSelector,以此将Pod调度到期望的node节点上。注意,这里的调度是强制的,这就意味着即使要调度的目标Node不存在,也会向上面进行调度,只不过pod运行失败而已。</p> 
    <p><strong>NodeName</strong></p> 
    <p>​ NodeName用于强制约束将Pod调度到指定的Name的Node节点上。这种方式,其实是直接跳过Scheduler的调度逻辑,直接将Pod调度到指定名称的节点。</p> 
    <p>接下来,实验一下:创建一个pod-nodename.yaml文件</p> 
    <pre data-index="93" class="set-code-show prettyprint"><code class="prism language-yaml has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token key atrule">apiVersion</span><span class="token punctuation">:</span> v1
    <span class="token key atrule">kind</span><span class="token punctuation">:</span> Pod
    <span class="token key atrule">metadata</span><span class="token punctuation">:</span>
      <span class="token key atrule">name</span><span class="token punctuation">:</span> pod<span class="token punctuation">-</span>nodename
      <span class="token key atrule">namespace</span><span class="token punctuation">:</span> dev
    <span class="token key atrule">spec</span><span class="token punctuation">:</span>
      <span class="token key atrule">containers</span><span class="token punctuation">:</span>
      <span class="token punctuation">-</span> <span class="token key atrule">name</span><span class="token punctuation">:</span> nginx
        <span class="token key atrule">image</span><span class="token punctuation">:</span> nginx<span class="token punctuation">:</span>1.17.1
      <span class="token key atrule">nodeName</span><span class="token punctuation">:</span> node1 <span class="token comment"># 指定调度到node1节点上</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li><li style="color: rgb(153, 153, 153);">2</li><li style="color: rgb(153, 153, 153);">3</li><li style="color: rgb(153, 153, 153);">4</li><li style="color: rgb(153, 153, 153);">5</li><li style="color: rgb(153, 153, 153);">6</li><li style="color: rgb(153, 153, 153);">7</li><li style="color: rgb(153, 153, 153);">8</li><li style="color: rgb(153, 153, 153);">9</li><li style="color: rgb(153, 153, 153);">10</li></ul></pre> 
    <pre data-index="94" class="set-code-hide prettyprint"><code class="prism language-powershell has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token comment">#创建Pod</span>
    <span class="token namespace">[root@master ~]</span><span class="token comment"># kubectl create -f pod-nodename.yaml</span>
    pod/pod-nodename created
    
    <span class="token comment">#查看Pod调度到NODE属性,确实是调度到了node1节点上</span>
    <span class="token namespace">[root@master ~]</span><span class="token comment"># kubectl get pods pod-nodename -n dev -o wide</span>
    NAME           READY   STATUS    RESTARTS   AGE   IP            NODE      <span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span>
    pod-nodename   1/1     Running   0          56s   10<span class="token punctuation">.</span>244<span class="token punctuation">.</span>1<span class="token punctuation">.</span>87   node1     <span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span>   
    
    <span class="token comment"># 接下来,删除pod,修改nodeName的值为node3(并没有node3节点)</span>
    <span class="token namespace">[root@master ~]</span><span class="token comment"># kubectl delete -f pod-nodename.yaml</span>
    pod <span class="token string">"pod-nodename"</span> deleted
    <span class="token namespace">[root@master ~]</span><span class="token comment"># vim pod-nodename.yaml</span>
    <span class="token namespace">[root@master ~]</span><span class="token comment"># kubectl create -f pod-nodename.yaml</span>
    pod/pod-nodename created
    
    <span class="token comment">#再次查看,发现已经向Node3节点调度,但是由于不存在node3节点,所以pod无法正常运行</span>
    <span class="token namespace">[root@master ~]</span><span class="token comment"># kubectl get pods pod-nodename -n dev -o wide</span>
    NAME           READY   STATUS    RESTARTS   AGE   IP       NODE    <span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span>
    pod-nodename   0/1     Pending   0          6s    <none>   node3   <span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span>           
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><div class="hide-preCode-box"><span class="hide-preCode-bt" data-report-view="{"spm":"1001.2101.3001.7365"}"><img class="look-more-preCode contentImg-no-view" src="https://1000bd.com/contentImg/2022/06/27/191644837.png" alt="" title=""></span></div><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li><li style="color: rgb(153, 153, 153);">2</li><li style="color: rgb(153, 153, 153);">3</li><li style="color: rgb(153, 153, 153);">4</li><li style="color: rgb(153, 153, 153);">5</li><li style="color: rgb(153, 153, 153);">6</li><li style="color: rgb(153, 153, 153);">7</li><li style="color: rgb(153, 153, 153);">8</li><li style="color: rgb(153, 153, 153);">9</li><li style="color: rgb(153, 153, 153);">10</li><li style="color: rgb(153, 153, 153);">11</li><li style="color: rgb(153, 153, 153);">12</li><li style="color: rgb(153, 153, 153);">13</li><li style="color: rgb(153, 153, 153);">14</li><li style="color: rgb(153, 153, 153);">15</li><li style="color: rgb(153, 153, 153);">16</li><li style="color: rgb(153, 153, 153);">17</li><li style="color: rgb(153, 153, 153);">18</li><li style="color: rgb(153, 153, 153);">19</li><li style="color: rgb(153, 153, 153);">20</li></ul></pre> 
    <p><strong>NodeSelector</strong></p> 
    <p>​ NodeSelector用于将pod调度到添加了指定标签的node节点上。它是通过kubernetes的label-selector机制实现的,也就是说,在pod创建之前,会由scheduler使用MatchNodeSelector调度策略进行label匹配,找出目标node,然后将pod调度到目标节点,该匹配规则是强制约束。</p> 
    <p>接下来,实验一下:</p> 
    <p>1 首先分别为node节点添加标签</p> 
    <pre data-index="95" class="set-code-show prettyprint"><code class="prism language-powershell has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token namespace">[root@master ~]</span><span class="token comment"># kubectl label nodes node1 nodeenv=pro</span>
    node/node2 labeled
    <span class="token namespace">[root@master ~]</span><span class="token comment"># kubectl label nodes node2 nodeenv=test</span>
    node/node2 labeled
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li><li style="color: rgb(153, 153, 153);">2</li><li style="color: rgb(153, 153, 153);">3</li><li style="color: rgb(153, 153, 153);">4</li></ul></pre> 
    <p>2 创建一个pod-nodeselector.yaml文件,并使用它创建Pod</p> 
    <pre data-index="96" class="set-code-show prettyprint"><code class="prism language-yaml has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token key atrule">apiVersion</span><span class="token punctuation">:</span> v1
    <span class="token key atrule">kind</span><span class="token punctuation">:</span> Pod
    <span class="token key atrule">metadata</span><span class="token punctuation">:</span>
      <span class="token key atrule">name</span><span class="token punctuation">:</span> pod<span class="token punctuation">-</span>nodeselector
      <span class="token key atrule">namespace</span><span class="token punctuation">:</span> dev
    <span class="token key atrule">spec</span><span class="token punctuation">:</span>
      <span class="token key atrule">containers</span><span class="token punctuation">:</span>
      <span class="token punctuation">-</span> <span class="token key atrule">name</span><span class="token punctuation">:</span> nginx
        <span class="token key atrule">image</span><span class="token punctuation">:</span> nginx<span class="token punctuation">:</span>1.17.1
      <span class="token key atrule">nodeSelector</span><span class="token punctuation">:</span> 
        <span class="token key atrule">nodeenv</span><span class="token punctuation">:</span> pro <span class="token comment"># 指定调度到具有nodeenv=pro标签的节点上</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li><li style="color: rgb(153, 153, 153);">2</li><li style="color: rgb(153, 153, 153);">3</li><li style="color: rgb(153, 153, 153);">4</li><li style="color: rgb(153, 153, 153);">5</li><li style="color: rgb(153, 153, 153);">6</li><li style="color: rgb(153, 153, 153);">7</li><li style="color: rgb(153, 153, 153);">8</li><li style="color: rgb(153, 153, 153);">9</li><li style="color: rgb(153, 153, 153);">10</li><li style="color: rgb(153, 153, 153);">11</li></ul></pre> 
    <pre data-index="97" class="set-code-show prettyprint"><code class="prism language-powershell has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token comment">#创建Pod[root@master ~]# kubectl create -f pod-nodeselector.yamlpod/pod-nodeselector created#查看Pod调度到NODE属性,确实是调度到了node1节点上[root@master ~]# kubectl get pods pod-nodeselector -n dev -o wideNAME               READY   STATUS    RESTARTS   AGE     IP          NODE    ......pod-nodeselector   1/1     Running   0          47s   10.244.1.87   node1   ......# 接下来,删除pod,修改nodeSelector的值为nodeenv: xxxx(不存在打有此标签的节点)[root@master ~]# kubectl delete -f pod-nodeselector.yamlpod "pod-nodeselector" deleted[root@master ~]# vim pod-nodeselector.yaml[root@master ~]# kubectl create -f pod-nodeselector.yamlpod/pod-nodeselector created#再次查看,发现pod无法正常运行,Node的值为none[root@master ~]# kubectl get pods -n dev -o wideNAME               READY   STATUS    RESTARTS   AGE     IP       NODE    pod-nodeselector   0/1     Pending   0          2m20s   <none>   <none># 查看详情,发现node selector匹配失败的提示[root@master ~]# kubectl describe pods pod-nodeselector -n dev.......Events:  Type     Reason            Age        From               Message  ----     ------            ----       ----               -------  Warning  FailedScheduling  <unknown>  default-scheduler  0/3 nodes are available: 3 node(s) didn't match node selector.  Warning  FailedScheduling  <unknown>  default-scheduler  0/3 nodes are available: 3 node(s) didn't match node selector.</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <h4><a name="t52"></a><a id="_2288"></a>亲和性调度</h4> 
    <p>​ 上一节,介绍了两种定向调度的方式,使用起来非常方便,但是也有一定的问题,那就是如果没有满足条件的Node,那么Pod将不会被运行,即使在集群中还有可用Node列表也不行,这就限制了它的使用场景。</p> 
    <p>​ 基于上面的问题,kubernetes还提供了一种亲和性调度(Affinity)。它在NodeSelector的基础之上的进行了扩展,可以通过配置的形式,实现优先选择满足条件的Node进行调度,如果没有,也可以调度到不满足条件的节点上,使调度更加灵活。</p> 
    <p>Affinity主要分为三类:</p> 
    <ul><li> <p>nodeAffinity(node亲和性): 以node为目标,解决pod可以调度到哪些node的问题</p> </li><li> <p>podAffinity(pod亲和性) : 以pod为目标,解决pod可以和哪些已存在的pod部署在同一个拓扑域中的问题</p> </li><li> <p>podAntiAffinity(pod反亲和性) : 以pod为目标,解决pod不能和哪些已存在pod部署在同一个拓扑域中的问题</p> </li></ul> 
    <blockquote> 
     <p>关于亲和性(反亲和性)使用场景的说明:</p> 
     <p><strong>亲和性</strong>:如果两个应用频繁交互,那就有必要利用亲和性让两个应用的尽可能的靠近,这样可以减少因网络通信而带来的性能损耗。</p> 
     <p><strong>反亲和性</strong>:当应用的采用多副本部署时,有必要采用反亲和性让各个应用实例打散分布在各个node上,这样可以提高服务的高可用性。</p> 
    </blockquote> 
    <p><strong>NodeAffinity</strong></p> 
    <p>首先来看一下<code>NodeAffinity</code>的可配置项:</p> 
    <pre data-index="98" class="set-code-show prettyprint"><code class="prism language-markdown has-numbering" onclick="mdcp.signin(event)" style="position: unset;">pod.spec.affinity.nodeAffinity  requiredDuringSchedulingIgnoredDuringExecution  Node节点必须满足指定的所有规则才可以,相当于硬限制    nodeSelectorTerms  节点选择列表      matchFields   按节点字段列出的节点选择器要求列表      matchExpressions   按节点标签列出的节点选择器要求列表(推荐)        key    键        values 值        operator 关系符 支持Exists, DoesNotExist, In, NotIn, Gt, Lt  preferredDuringSchedulingIgnoredDuringExecution 优先调度到满足指定的规则的Node,相当于软限制 (倾向)    preference   一个节点选择器项,与相应的权重相关联      matchFields   按节点字段列出的节点选择器要求列表      matchExpressions   按节点标签列出的节点选择器要求列表(推荐)        key    键        values 值        operator 关系符 支持In, NotIn, Exists, DoesNotExist, Gt, Lt	weight 倾向权重,在范围1-100。
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <pre data-index="99" class="set-code-show prettyprint"><code class="prism language-markdown has-numbering" onclick="mdcp.signin(event)" style="position: unset;">关系符的使用说明:- matchExpressions:  - key: nodeenv              # 匹配存在标签的key为nodeenv的节点    operator: Exists  - key: nodeenv              # 匹配标签的key为nodeenv,且value是"xxx"或"yyy"的节点    operator: In    values: ["xxx","yyy"]  - key: nodeenv              # 匹配标签的key为nodeenv,且value大于"xxx"的节点    operator: Gt    values: "xxx"
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <p>接下来首先演示一下<code>requiredDuringSchedulingIgnoredDuringExecution</code> ,</p> 
    <p>创建pod-nodeaffinity-required.yaml</p> 
    <pre data-index="100" class="set-code-show prettyprint"><code class="prism language-yaml has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token key atrule">apiVersion</span><span class="token punctuation">:</span> <span class="token key atrule">v1kind</span><span class="token punctuation">:</span> <span class="token key atrule">Podmetadata</span><span class="token punctuation">:</span>  <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">pod-nodeaffinity-required  namespace</span><span class="token punctuation">:</span> <span class="token key atrule">devspec</span><span class="token punctuation">:</span>  <span class="token key atrule">containers</span><span class="token punctuation">:</span>  <span class="token punctuation">-</span> <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">nginx    image</span><span class="token punctuation">:</span> <span class="token key atrule">nginx:1.17.1  affinity</span><span class="token punctuation">:</span>  <span class="token comment">#亲和性设置    nodeAffinity: #设置node亲和性      requiredDuringSchedulingIgnoredDuringExecution: # 硬限制        nodeSelectorTerms:        - matchExpressions: # 匹配env的值在["xxx","yyy"]中的标签          - key: nodeenv            operator: In            values: ["xxx","yyy"]</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <pre data-index="101" class="set-code-show prettyprint"><code class="prism language-powershell has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token comment"># 创建pod[root@master ~]# kubectl create -f pod-nodeaffinity-required.yamlpod/pod-nodeaffinity-required created# 查看pod状态 (运行失败)[root@master ~]# kubectl get pods pod-nodeaffinity-required -n dev -o wideNAME                        READY   STATUS    RESTARTS   AGE   IP       NODE    ...... pod-nodeaffinity-required   0/1     Pending   0          16s   <none>   <none>  ......# 查看Pod的详情# 发现调度失败,提示node选择失败[root@master ~]# kubectl describe pod pod-nodeaffinity-required -n dev......  Warning  FailedScheduling  <unknown>  default-scheduler  0/3 nodes are available: 3 node(s) didn't match node selector.  Warning  FailedScheduling  <unknown>  default-scheduler  0/3 nodes are available: 3 node(s) didn't match node selector.#接下来,停止pod[root@master ~]# kubectl delete -f pod-nodeaffinity-required.yamlpod "pod-nodeaffinity-required" deleted# 修改文件,将values: ["xxx","yyy"]------> ["pro","yyy"][root@master ~]# vim pod-nodeaffinity-required.yaml# 再次启动[root@master ~]# kubectl create -f pod-nodeaffinity-required.yamlpod/pod-nodeaffinity-required created# 此时查看,发现调度成功,已经将pod调度到了node1上[root@master ~]# kubectl get pods pod-nodeaffinity-required -n dev -o wideNAME                        READY   STATUS    RESTARTS   AGE   IP            NODE  ...... pod-nodeaffinity-required   1/1     Running   0          11s   10.244.1.89   node1 ......</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <p>接下来再演示一下<code>requiredDuringSchedulingIgnoredDuringExecution</code> ,</p> 
    <p>创建pod-nodeaffinity-preferred.yaml</p> 
    <pre data-index="102" class="set-code-show prettyprint"><code class="prism language-yaml has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token key atrule">apiVersion</span><span class="token punctuation">:</span> <span class="token key atrule">v1kind</span><span class="token punctuation">:</span> <span class="token key atrule">Podmetadata</span><span class="token punctuation">:</span>  <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">pod-nodeaffinity-preferred  namespace</span><span class="token punctuation">:</span> <span class="token key atrule">devspec</span><span class="token punctuation">:</span>  <span class="token key atrule">containers</span><span class="token punctuation">:</span>  <span class="token punctuation">-</span> <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">nginx    image</span><span class="token punctuation">:</span> <span class="token key atrule">nginx:1.17.1  affinity</span><span class="token punctuation">:</span>  <span class="token comment">#亲和性设置    nodeAffinity: #设置node亲和性      preferredDuringSchedulingIgnoredDuringExecution: # 软限制      - weight: 1        preference:          matchExpressions: # 匹配env的值在["xxx","yyy"]中的标签(当前环境没有)          - key: nodeenv            operator: In            values: ["xxx","yyy"]</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <pre data-index="103" class="set-code-show prettyprint"><code class="prism language-powershell has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token comment"># 创建pod[root@master ~]# kubectl create -f pod-nodeaffinity-preferred.yamlpod/pod-nodeaffinity-preferred created# 查看pod状态 (运行成功)[root@master ~]# kubectl get pod pod-nodeaffinity-preferred -n devNAME                         READY   STATUS    RESTARTS   AGEpod-nodeaffinity-preferred   1/1     Running   0          40s</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <pre data-index="104" class="set-code-show prettyprint"><code class="prism language-markdown has-numbering" onclick="mdcp.signin(event)" style="position: unset;">NodeAffinity规则设置的注意事项:    1 如果同时定义了nodeSelector和nodeAffinity,那么必须两个条件都得到满足,Pod才能运行在指定的Node上    2 如果nodeAffinity指定了多个nodeSelectorTerms,那么只需要其中一个能够匹配成功即可    3 如果一个nodeSelectorTerms中有多个matchExpressions ,则一个节点必须满足所有的才能匹配成功    4 如果一个pod所在的Node在Pod运行期间其标签发生了改变,不再符合该Pod的节点亲和性需求,则系统将忽略此变化
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <p><strong>PodAffinity</strong></p> 
    <p>PodAffinity主要实现以运行的Pod为参照,实现让新创建的Pod跟参照pod在一个区域的功能。</p> 
    <p>首先来看一下<code>PodAffinity</code>的可配置项:</p> 
    <pre data-index="105" class="set-code-show prettyprint"><code class="prism language-markdown has-numbering" onclick="mdcp.signin(event)" style="position: unset;">pod.spec.affinity.podAffinity  requiredDuringSchedulingIgnoredDuringExecution  硬限制    namespaces       指定参照pod的namespace    topologyKey      指定调度作用域    labelSelector    标签选择器      matchExpressions  按节点标签列出的节点选择器要求列表(推荐)        key    键        values 值        operator 关系符 支持In, NotIn, Exists, DoesNotExist.      matchLabels    指多个matchExpressions映射的内容  preferredDuringSchedulingIgnoredDuringExecution 软限制    podAffinityTerm  选项      namespaces            topologyKey      labelSelector        matchExpressions            key    键          values 值          operator        matchLabels     weight 倾向权重,在范围1-100
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <pre data-index="106" class="set-code-show prettyprint"><code class="prism language-markdown has-numbering" onclick="mdcp.signin(event)" style="position: unset;">topologyKey用于指定调度时作用域,例如:    如果指定为kubernetes.io/hostname,那就是以Node节点为区分范围	如果指定为beta.kubernetes.io/os,则以Node节点的操作系统类型来区分
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <p>接下来,演示下<code>requiredDuringSchedulingIgnoredDuringExecution</code>,</p> 
    <p>1)首先创建一个参照Pod,pod-podaffinity-target.yaml:</p> 
    <pre data-index="107" class="set-code-show prettyprint"><code class="prism language-yaml has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token key atrule">apiVersion</span><span class="token punctuation">:</span> <span class="token key atrule">v1kind</span><span class="token punctuation">:</span> <span class="token key atrule">Podmetadata</span><span class="token punctuation">:</span>  <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">pod-podaffinity-target  namespace</span><span class="token punctuation">:</span> <span class="token key atrule">dev  labels</span><span class="token punctuation">:</span>    <span class="token key atrule">podenv</span><span class="token punctuation">:</span> pro <span class="token comment">#设置标签spec:  containers:  - name: nginx    image: nginx:1.17.1  nodeName: node1 # 将目标pod名确指定到node1上</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <pre data-index="108" class="set-code-show prettyprint"><code class="prism language-powershell has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token comment"># 启动目标pod[root@master ~]# kubectl create -f pod-podaffinity-target.yamlpod/pod-podaffinity-target created# 查看pod状况[root@master ~]# kubectl get pods  pod-podaffinity-target -n devNAME                     READY   STATUS    RESTARTS   AGEpod-podaffinity-target   1/1     Running   0          4s</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <p>2)创建pod-podaffinity-required.yaml,内容如下:</p> 
    <pre data-index="109" class="set-code-show prettyprint"><code class="prism language-yaml has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token key atrule">apiVersion</span><span class="token punctuation">:</span> <span class="token key atrule">v1kind</span><span class="token punctuation">:</span> <span class="token key atrule">Podmetadata</span><span class="token punctuation">:</span>  <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">pod-podaffinity-required  namespace</span><span class="token punctuation">:</span> <span class="token key atrule">devspec</span><span class="token punctuation">:</span>  <span class="token key atrule">containers</span><span class="token punctuation">:</span>  <span class="token punctuation">-</span> <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">nginx    image</span><span class="token punctuation">:</span> <span class="token key atrule">nginx:1.17.1  affinity</span><span class="token punctuation">:</span>  <span class="token comment">#亲和性设置    podAffinity: #设置pod亲和性      requiredDuringSchedulingIgnoredDuringExecution: # 硬限制      - labelSelector:          matchExpressions: # 匹配env的值在["xxx","yyy"]中的标签          - key: podenv            operator: In            values: ["xxx","yyy"]        topologyKey: kubernetes.io/hostname</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <p>上面配置表达的意思是:新Pod必须要与拥有标签nodeenv=xxx或者nodeenv=yyy的pod在同一Node上,显然现在没有这样pod,接下来,运行测试一下。</p> 
    <pre data-index="110" class="set-code-show prettyprint"><code class="prism language-powershell has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token comment"># 启动pod[root@master ~]# kubectl create -f pod-podaffinity-required.yamlpod/pod-podaffinity-required created# 查看pod状态,发现未运行[root@master ~]# kubectl get pods pod-podaffinity-required -n devNAME                       READY   STATUS    RESTARTS   AGEpod-podaffinity-required   0/1     Pending   0          9s# 查看详细信息[root@master ~]# kubectl describe pods pod-podaffinity-required  -n dev......Events:  Type     Reason            Age        From               Message  ----     ------            ----       ----               -------  Warning  FailedScheduling  <unknown>  default-scheduler  0/3 nodes are available: 2 node(s) didn't match pod affinity rules, 1 node(s) had taints that the pod didn't tolerate.# 接下来修改  values: ["xxx","yyy"]----->values:["pro","yyy"]# 意思是:新Pod必须要与拥有标签nodeenv=xxx或者nodeenv=yyy的pod在同一Node上[root@master ~]# vim pod-podaffinity-required.yaml# 然后重新创建pod,查看效果[root@master ~]# kubectl delete -f  pod-podaffinity-required.yamlpod "pod-podaffinity-required" deleted[root@master ~]# kubectl create -f pod-podaffinity-required.yamlpod/pod-podaffinity-required created# 发现此时Pod运行正常[root@master ~]# kubectl get pods pod-podaffinity-required -n devNAME                       READY   STATUS    RESTARTS   AGE   LABELSpod-podaffinity-required   1/1     Running   0          6s    <none></span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <p>关于<code>PodAffinity</code>的 <code>preferredDuringSchedulingIgnoredDuringExecution</code>,这里不再演示。</p> 
    <p><strong>PodAntiAffinity</strong></p> 
    <p>PodAntiAffinity主要实现以运行的Pod为参照,让新创建的Pod跟参照pod不在一个区域中的功能。</p> 
    <p>它的配置方式和选项跟PodAffinty是一样的,这里不再做详细解释,直接做一个测试案例。</p> 
    <p>1)继续使用上个案例中目标pod</p> 
    <pre data-index="111" class="set-code-show prettyprint"><code class="prism language-powershell has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token namespace">[root@master ~]</span><span class="token comment"># kubectl get pods -n dev -o wide --show-labelsNAME                     READY   STATUS    RESTARTS   AGE     IP            NODE    LABELSpod-podaffinity-required 1/1     Running   0          3m29s   10.244.1.38   node1   <none>     pod-podaffinity-target   1/1     Running   0          9m25s   10.244.1.37   node1   podenv=pro</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <p>2)创建pod-podantiaffinity-required.yaml,内容如下:</p> 
    <pre data-index="112" class="set-code-show prettyprint"><code class="prism language-yaml has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token key atrule">apiVersion</span><span class="token punctuation">:</span> <span class="token key atrule">v1kind</span><span class="token punctuation">:</span> <span class="token key atrule">Podmetadata</span><span class="token punctuation">:</span>  <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">pod-podantiaffinity-required  namespace</span><span class="token punctuation">:</span> <span class="token key atrule">devspec</span><span class="token punctuation">:</span>  <span class="token key atrule">containers</span><span class="token punctuation">:</span>  <span class="token punctuation">-</span> <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">nginx    image</span><span class="token punctuation">:</span> <span class="token key atrule">nginx:1.17.1  affinity</span><span class="token punctuation">:</span>  <span class="token comment">#亲和性设置    podAntiAffinity: #设置pod亲和性      requiredDuringSchedulingIgnoredDuringExecution: # 硬限制      - labelSelector:          matchExpressions: # 匹配podenv的值在["pro"]中的标签          - key: podenv            operator: In            values: ["pro"]        topologyKey: kubernetes.io/hostname</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <p>上面配置表达的意思是:新Pod必须要与拥有标签nodeenv=pro的pod不在同一Node上,运行测试一下。</p> 
    <pre data-index="113" class="set-code-show prettyprint"><code class="prism language-powershell has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token comment"># 创建pod[root@master ~]# kubectl create -f pod-podantiaffinity-required.yamlpod/pod-podantiaffinity-required created# 查看pod# 发现调度到了node2上[root@master ~]# kubectl get pods pod-podantiaffinity-required -n dev -o wideNAME                           READY   STATUS    RESTARTS   AGE   IP            NODE   .. pod-podantiaffinity-required   1/1     Running   0          30s   10.244.1.96   node2  ..</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <h4><a name="t53"></a><a id="_2412"></a>污点和容忍</h4> 
    <p><strong>污点(Taints)</strong></p> 
    <p>​ 前面的调度方式都是站在Pod的角度上,通过在Pod上添加属性,来确定Pod是否要调度到指定的Node上,其实我们也可以站在Node的角度上,通过在Node上添加<strong>污点</strong>属性,来决定是否允许Pod调度过来。</p> 
    <p>​ Node被设置上污点之后就和Pod之间存在了一种相斥的关系,进而拒绝Pod调度进来,甚至可以将已经存在的Pod驱逐出去。</p> 
    <p>污点的格式为:<code>key=value:effect</code>, key和value是污点的标签,effect描述污点的作用,支持如下三个选项:</p> 
    <ul><li>PreferNoSchedule:kubernetes将尽量避免把Pod调度到具有该污点的Node上,除非没有其他节点可调度</li><li>NoSchedule:kubernetes将不会把Pod调度到具有该污点的Node上,但不会影响当前Node上已存在的Pod</li><li>NoExecute:kubernetes将不会把Pod调度到具有该污点的Node上,同时也会将Node上已存在的Pod驱离</li></ul> 
    <img src="https://1000bd.com/contentImg/2023/10/27/000132605.png" alt="image-20200605021606508"> 
    <p>使用kubectl设置和去除污点的命令示例如下:</p> 
    <pre data-index="114" class="set-code-show prettyprint"><code class="prism language-powershell has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token comment"># 设置污点kubectl taint nodes node1 key=value:effect# 去除污点kubectl taint nodes node1 key:effect-# 去除所有污点kubectl taint nodes node1 key-</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <p>接下来,演示下污点的效果:</p> 
    <ol><li>准备节点node1(为了演示效果更加明显,暂时停止node2节点)</li><li>为node1节点设置一个污点: <code>tag=heima:PreferNoSchedule</code>;然后创建pod1( pod1 可以 )</li><li>修改为node1节点设置一个污点: <code>tag=heima:NoSchedule</code>;然后创建pod2( pod1 正常 pod2 失败 )</li><li>修改为node1节点设置一个污点: <code>tag=heima:NoExecute</code>;然后创建pod3 ( 3个pod都失败 )</li></ol> 
    <pre data-index="115" class="set-code-show prettyprint"><code class="prism language-powershell has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token comment"># 为node1设置污点(PreferNoSchedule)[root@master ~]# kubectl taint nodes node1 tag=heima:PreferNoSchedule# 创建pod1[root@master ~]# kubectl run taint1 --image=nginx:1.17.1 -n dev[root@master ~]# kubectl get pods -n dev -o wideNAME                      READY   STATUS    RESTARTS   AGE     IP           NODE   taint1-7665f7fd85-574h4   1/1     Running   0          2m24s   10.244.1.59   node1    # 为node1设置污点(取消PreferNoSchedule,设置NoSchedule)[root@master ~]# kubectl taint nodes node1 tag:PreferNoSchedule-[root@master ~]# kubectl taint nodes node1 tag=heima:NoSchedule# 创建pod2[root@master ~]# kubectl run taint2 --image=nginx:1.17.1 -n dev[root@master ~]# kubectl get pods taint2 -n dev -o wideNAME                      READY   STATUS    RESTARTS   AGE     IP            NODEtaint1-7665f7fd85-574h4   1/1     Running   0          2m24s   10.244.1.59   node1 taint2-544694789-6zmlf    0/1     Pending   0          21s     <none>        <none>   # 为node1设置污点(取消NoSchedule,设置NoExecute)[root@master ~]# kubectl taint nodes node1 tag:NoSchedule-[root@master ~]# kubectl taint nodes node1 tag=heima:NoExecute# 创建pod3[root@master ~]# kubectl run taint3 --image=nginx:1.17.1 -n dev[root@master ~]# kubectl get pods -n dev -o wideNAME                      READY   STATUS    RESTARTS   AGE   IP       NODE     NOMINATED taint1-7665f7fd85-htkmp   0/1     Pending   0          35s   <none>   <none>   <none>    taint2-544694789-bn7wb    0/1     Pending   0          35s   <none>   <none>   <none>     taint3-6d78dbd749-tktkq   0/1     Pending   0          6s    <none>   <none>   <none>     </span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <pre data-index="116" class="set-code-show prettyprint"><code class="prism language-markdown has-numbering" onclick="mdcp.signin(event)" style="position: unset;">小提示:    使用kubeadm搭建的集群,默认就会给master节点添加一个污点标记,所以pod就不会调度到master节点上.
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <p><strong>容忍(Toleration)</strong></p> 
    <p>​ 上面介绍了污点的作用,我们可以在node上添加污点用于拒绝pod调度上来,但是如果就是想将一个pod调度到一个有污点的node上去,这时候应该怎么做呢?这就要使用到<strong>容忍</strong>。</p> 
    <p><img src="https://1000bd.com/contentImg/2023/10/27/000132484.png" alt="image-20200514095913741"></p> 
    <blockquote> 
     <p>污点就是拒绝,容忍就是忽略,Node通过污点拒绝pod调度上去,Pod通过容忍忽略拒绝</p> 
    </blockquote> 
    <p>下面先通过一个案例看下效果:</p> 
    <ol><li>上一小节,已经在node1节点上打上了<code>NoExecute</code>的污点,此时pod是调度不上去的</li><li>本小节,可以通过给pod添加容忍,然后将其调度上去</li></ol> 
    <p>创建pod-toleration.yaml,内容如下</p> 
    <pre data-index="117" class="set-code-show prettyprint"><code class="prism language-yaml has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token key atrule">apiVersion</span><span class="token punctuation">:</span> <span class="token key atrule">v1kind</span><span class="token punctuation">:</span> <span class="token key atrule">Podmetadata</span><span class="token punctuation">:</span>  <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">pod-toleration  namespace</span><span class="token punctuation">:</span> <span class="token key atrule">devspec</span><span class="token punctuation">:</span>  <span class="token key atrule">containers</span><span class="token punctuation">:</span>  <span class="token punctuation">-</span> <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">nginx    image</span><span class="token punctuation">:</span> <span class="token key atrule">nginx:1.17.1  tolerations</span><span class="token punctuation">:</span>      <span class="token comment"># 添加容忍  - key: "tag"        # 要容忍的污点的key    operator: "Equal" # 操作符    value: "heima"    # 容忍的污点的value    effect: "NoExecute"   # 添加容忍的规则,这里必须和标记的污点规则相同</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <pre data-index="118" class="set-code-show prettyprint"><code class="prism language-powershell has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token comment"># 添加容忍之前的pod[root@master ~]# kubectl get pods -n dev -o wideNAME             READY   STATUS    RESTARTS   AGE   IP       NODE     NOMINATED pod-toleration   0/1     Pending   0          3s    <none>   <none>   <none>           # 添加容忍之后的pod[root@master ~]# kubectl get pods -n dev -o wideNAME             READY   STATUS    RESTARTS   AGE   IP            NODE    NOMINATEDpod-toleration   1/1     Running   0          3s    10.244.1.62   node1   <none>        </span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <p>下面看一下容忍的详细配置:</p> 
    <pre data-index="119" class="set-code-show prettyprint"><code class="prism language-powershell has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token namespace">[root@master ~]</span><span class="token comment"># kubectl explain pod.spec.tolerations......FIELDS:   key       # 对应着要容忍的污点的键,空意味着匹配所有的键   value     # 对应着要容忍的污点的值   operator  # key-value的运算符,支持Equal和Exists(默认)   effect    # 对应污点的effect,空意味着匹配所有影响   tolerationSeconds   # 容忍时间, 当effect为NoExecute时生效,表示pod在Node上的停留时间</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <h2><a name="t54"></a><a id="_Pod_2478"></a>第五章 Pod详解</h2> 
    <p>本章节将详细介绍Pod资源的各种配置(yaml)和原理。</p> 
    <h3><a name="t55"></a><a id="Pod_2482"></a>Pod介绍</h3> 
    <h4><a name="t56"></a><a id="Pod_2484"></a>Pod结构</h4> 
    <img src="Kubernetes教程.assets/image-20200407121501907-16338582916261.png" alt="image-20200407121501907"> 
    <p>每个Pod中都可以包含一个或者多个容器,这些容器可以分为两类:</p> 
    <ul><li> <p>用户程序所在的容器,数量可多可少</p> </li><li> <p>Pause容器,这是每个Pod都会有的一个<strong>根容器</strong>,它的作用有两个:</p> 
      <ul><li> <p>可以以它为依据,评估整个Pod的健康状态</p> </li><li> <p>可以在根容器上设置Ip地址,其它容器都此Ip(Pod IP),以实现Pod内部的网路通信</p> <pre data-index="120" class="set-code-show prettyprint"><code class="prism language-md has-numbering" onclick="mdcp.signin(event)" style="position: unset;">这里是Pod内部的通讯,Pod的之间的通讯采用虚拟二层网络技术来实现,我们当前环境用的是Flannel
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> </li></ul> </li></ul> 
    <h4><a name="t57"></a><a id="Pod_2502"></a>Pod定义</h4> 
    <p>下面是Pod的资源清单:</p> 
    <pre data-index="121" class="set-code-show prettyprint"><code class="prism language-yaml has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token key atrule">apiVersion</span><span class="token punctuation">:</span> v1     <span class="token comment">#必选,版本号,例如v1kind: Pod         #必选,资源类型,例如 Podmetadata:         #必选,元数据  name: string     #必选,Pod名称  namespace: string  #Pod所属的命名空间,默认为"default"  labels:           #自定义标签列表    - name: string                 spec:  #必选,Pod中容器的详细定义  containers:  #必选,Pod中容器列表  - name: string   #必选,容器名称    image: string  #必选,容器的镜像名称    imagePullPolicy: [ Always|Never|IfNotPresent ]  #获取镜像的策略     command: [string]   #容器的启动命令列表,如不指定,使用打包时使用的启动命令    args: [string]      #容器的启动命令参数列表    workingDir: string  #容器的工作目录    volumeMounts:       #挂载到容器内部的存储卷配置    - name: string      #引用pod定义的共享存储卷的名称,需用volumes[]部分定义的的卷名      mountPath: string #存储卷在容器内mount的绝对路径,应少于512字符      readOnly: boolean #是否为只读模式    ports: #需要暴露的端口库号列表    - name: string        #端口的名称      containerPort: int  #容器需要监听的端口号      hostPort: int       #容器所在主机需要监听的端口号,默认与Container相同      protocol: string    #端口协议,支持TCP和UDP,默认TCP    env:   #容器运行前需设置的环境变量列表    - name: string  #环境变量名称      value: string #环境变量的值    resources: #资源限制和请求的设置      limits:  #资源限制的设置        cpu: string     #Cpu的限制,单位为core数,将用于docker run --cpu-shares参数        memory: string  #内存限制,单位可以为Mib/Gib,将用于docker run --memory参数      requests: #资源请求的设置        cpu: string    #Cpu请求,容器启动的初始可用数量        memory: string #内存请求,容器启动的初始可用数量    lifecycle: #生命周期钩子		postStart: #容器启动后立即执行此钩子,如果执行失败,会根据重启策略进行重启		preStop: #容器终止前执行此钩子,无论结果如何,容器都会终止    livenessProbe:  #对Pod内各容器健康检查的设置,当探测无响应几次后将自动重启该容器      exec:         #对Pod容器内检查方式设置为exec方式        command: [string]  #exec方式需要制定的命令或脚本      httpGet:       #对Pod内个容器健康检查方法设置为HttpGet,需要制定Path、port        path: string        port: number        host: string        scheme: string        HttpHeaders:        - name: string          value: string      tcpSocket:     #对Pod内个容器健康检查方式设置为tcpSocket方式         port: number       initialDelaySeconds: 0       #容器启动完成后首次探测的时间,单位为秒       timeoutSeconds: 0          #对容器健康检查探测等待响应的超时时间,单位秒,默认1秒       periodSeconds: 0           #对容器监控检查的定期探测时间设置,单位秒,默认10秒一次       successThreshold: 0       failureThreshold: 0       securityContext:         privileged: false  restartPolicy: [Always | Never | OnFailure]  #Pod的重启策略  nodeName: <string> #设置NodeName表示将该Pod调度到指定到名称的node节点上  nodeSelector: obeject #设置NodeSelector表示将该Pod调度到包含这个label的node上  imagePullSecrets: #Pull镜像时使用的secret名称,以key:secretkey格式指定  - name: string  hostNetwork: false   #是否使用主机网络模式,默认为false,如果设置为true,表示使用宿主机网络  volumes:   #在该pod上定义共享存储卷列表  - name: string    #共享存储卷名称 (volumes类型有很多种)    emptyDir: {}       #类型为emtyDir的存储卷,与Pod同生命周期的一个临时目录。为空值    hostPath: string   #类型为hostPath的存储卷,表示挂载Pod所在宿主机的目录      path: string                #Pod所在宿主机的目录,将被用于同期中mount的目录    secret:          #类型为secret的存储卷,挂载集群与定义的secret对象到容器内部      scretname: string        items:           - key: string        path: string    configMap:         #类型为configMap的存储卷,挂载预定义的configMap对象到容器内部      name: string      items:      - key: string        path: string</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <pre data-index="122" class="set-code-show prettyprint"><code class="prism language-powershell has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token comment">#小提示:#	在这里,可通过一个命令来查看每种资源的可配置项#   kubectl explain 资源类型         查看某种资源可以配置的一级属性#	kubectl explain 资源类型.属性     查看属性的子属性[root@master ~]# kubectl explain podKIND:     PodVERSION:  v1FIELDS:   apiVersion   <string>   kind <string>   metadata     <Object>   spec <Object>   status       <Object>[root@master ~]# kubectl explain pod.metadataKIND:     PodVERSION:  v1RESOURCE: metadata <Object>FIELDS:   annotations  <map[string]string>   clusterName  <string>   creationTimestamp    <string>   deletionGracePeriodSeconds   <integer>   deletionTimestamp    <string>   finalizers   <[]string>   generateName <string>   generation   <integer>   labels       <map[string]string>   managedFields        <[]Object>   name <string>   namespace    <string>   ownerReferences      <[]Object>   resourceVersion      <string>   selfLink     <string>   uid  <string></span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <p>在kubernetes中基本所有资源的一级属性都是一样的,主要包含5部分:</p> 
    <ul><li> <p>apiVersion <string> 版本,由kubernetes内部定义,版本号必须可以用 kubectl api-versions 查询到</p> </li><li> <p>kind <string> 类型,由kubernetes内部定义,版本号必须可以用 kubectl api-resources 查询到</p> </li><li> <p>metadata <Object> 元数据,主要是资源标识和说明,常用的有name、namespace、labels等</p> </li><li> <p>spec <Object> 描述,这是配置中最重要的一部分,里面是对各种资源配置的详细描述</p> </li><li> <p>status <Object> 状态信息,里面的内容不需要定义,由kubernetes自动生成</p> </li></ul> 
    <p>在上面的属性中,spec是接下来研究的重点,继续看下它的常见子属性:</p> 
    <ul><li>containers <[]Object> 容器列表,用于定义容器的详细信息</li><li>nodeName <String> 根据nodeName的值将pod调度到指定的Node节点上</li><li>nodeSelector <map[]> 根据NodeSelector中定义的信息选择将该Pod调度到包含这些label的Node 上</li><li>hostNetwork <boolean> 是否使用主机网络模式,默认为false,如果设置为true,表示使用宿主机网络</li><li>volumes <[]Object> 存储卷,用于定义Pod上面挂在的存储信息</li><li>restartPolicy <string> 重启策略,表示Pod在遇到故障的时候的处理策略</li></ul> 
    <h3><a name="t58"></a><a id="Pod_2536"></a>Pod配置</h3> 
    <p>本小节主要来研究<code>pod.spec.containers</code>属性,这也是pod配置中最为关键的一项配置。</p> 
    <pre data-index="123" class="set-code-show prettyprint"><code class="prism language-powershell has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token namespace">[root@master ~]</span><span class="token comment"># kubectl explain pod.spec.containersKIND:     PodVERSION:  v1RESOURCE: containers <[]Object>   # 数组,代表可以有多个容器FIELDS:   name  <string>     # 容器名称   image <string>     # 容器需要的镜像地址   imagePullPolicy  <string> # 镜像拉取策略    command  <[]string> # 容器的启动命令列表,如不指定,使用打包时使用的启动命令   args     <[]string> # 容器的启动命令需要的参数列表   env      <[]Object> # 容器环境变量的配置   ports    <[]Object>     # 容器需要暴露的端口号列表   resources <Object>      # 资源限制和资源请求的设置</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <h4><a name="t59"></a><a id="_2544"></a>基本配置</h4> 
    <p>创建pod-base.yaml文件,内容如下:</p> 
    <pre data-index="124" class="set-code-show prettyprint"><code class="prism language-yaml has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token key atrule">apiVersion</span><span class="token punctuation">:</span> <span class="token key atrule">v1kind</span><span class="token punctuation">:</span> <span class="token key atrule">Podmetadata</span><span class="token punctuation">:</span>  <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">pod-base  namespace</span><span class="token punctuation">:</span> <span class="token key atrule">dev  labels</span><span class="token punctuation">:</span>    <span class="token key atrule">user</span><span class="token punctuation">:</span> <span class="token key atrule">heimaspec</span><span class="token punctuation">:</span>  <span class="token key atrule">containers</span><span class="token punctuation">:</span>  <span class="token punctuation">-</span> <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">nginx    image</span><span class="token punctuation">:</span> <span class="token key atrule">nginx:1.17.1  - name</span><span class="token punctuation">:</span> <span class="token key atrule">busybox    image</span><span class="token punctuation">:</span> busybox<span class="token punctuation">:</span><span class="token number">1.30</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <p>上面定义了一个比较简单Pod的配置,里面有两个容器:</p> 
    <ul><li>nginx:用1.17.1版本的nginx镜像创建,(nginx是一个轻量级web容器)</li><li>busybox:用1.30版本的busybox镜像创建,(busybox是一个小巧的linux命令集合)</li></ul> 
    <pre data-index="125" class="set-code-show prettyprint"><code class="prism language-powershell has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token comment"># 创建Pod[root@master pod]# kubectl apply -f pod-base.yamlpod/pod-base created# 查看Pod状况# READY 1/2 : 表示当前Pod中有2个容器,其中1个准备就绪,1个未就绪# RESTARTS  : 重启次数,因为有1个容器故障了,Pod一直在重启试图恢复它[root@master pod]# kubectl get pod -n devNAME       READY   STATUS    RESTARTS   AGEpod-base   1/2     Running   4          95s# 可以通过describe查看内部的详情# 此时已经运行起来了一个基本的Pod,虽然它暂时有问题[root@master pod]# kubectl describe pod pod-base -n dev</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <h4><a name="t60"></a><a id="_2561"></a>镜像拉取</h4> 
    <p>创建pod-imagepullpolicy.yaml文件,内容如下:</p> 
    <pre data-index="126" class="set-code-show prettyprint"><code class="prism language-yaml has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token key atrule">apiVersion</span><span class="token punctuation">:</span> <span class="token key atrule">v1kind</span><span class="token punctuation">:</span> <span class="token key atrule">Podmetadata</span><span class="token punctuation">:</span>  <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">pod-imagepullpolicy  namespace</span><span class="token punctuation">:</span> <span class="token key atrule">devspec</span><span class="token punctuation">:</span>  <span class="token key atrule">containers</span><span class="token punctuation">:</span>  <span class="token punctuation">-</span> <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">nginx    image</span><span class="token punctuation">:</span> <span class="token key atrule">nginx:1.17.1    imagePullPolicy</span><span class="token punctuation">:</span> Always <span class="token comment"># 用于设置镜像拉取策略  - name: busybox    image: busybox:1.30</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <p>imagePullPolicy,用于设置镜像拉取策略,kubernetes支持配置三种拉取策略:</p> 
    <ul><li>Always:总是从远程仓库拉取镜像(一直远程下载)</li><li>IfNotPresent:本地有则使用本地镜像,本地没有则从远程仓库拉取镜像(本地有就本地 本地没远程下载)</li><li>Never:只使用本地镜像,从不去远程仓库拉取,本地没有就报错 (一直使用本地)</li></ul> 
    <blockquote> 
     <p>默认值说明:</p> 
     <p>​ 如果镜像tag为具体版本号, 默认策略是:IfNotPresent</p> 
     <p>​ 如果镜像tag为:latest(最终版本) ,默认策略是always</p> 
    </blockquote> 
    <pre data-index="127" class="set-code-show prettyprint"><code class="prism language-powershell has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token comment"># 创建Pod[root@master pod]# kubectl create -f pod-imagepullpolicy.yamlpod/pod-imagepullpolicy created# 查看Pod详情# 此时明显可以看到nginx镜像有一步Pulling image "nginx:1.17.1"的过程[root@master pod]# kubectl describe pod pod-imagepullpolicy -n dev......Events:  Type     Reason     Age               From               Message  ----     ------     ----              ----               -------  Normal   Scheduled  <unknown>         default-scheduler  Successfully assigned dev/pod-imagePullPolicy to node1  Normal   Pulling    32s               kubelet, node1     Pulling image "nginx:1.17.1"  Normal   Pulled     26s               kubelet, node1     Successfully pulled image "nginx:1.17.1"  Normal   Created    26s               kubelet, node1     Created container nginx  Normal   Started    25s               kubelet, node1     Started container nginx  Normal   Pulled     7s (x3 over 25s)  kubelet, node1     Container image "busybox:1.30" already present on machine  Normal   Created    7s (x3 over 25s)  kubelet, node1     Created container busybox  Normal   Started    7s (x3 over 25s)  kubelet, node1     Started container busybox</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <h4><a name="t61"></a><a id="_2585"></a>启动命令</h4> 
    <p>​ 在前面的案例中,一直有一个问题没有解决,就是的busybox容器一直没有成功运行,那么到底是什么原因导致这个容器的故障呢?</p> 
    <p>​ 原来busybox并不是一个程序,而是类似于一个工具类的集合,kubernetes集群启动管理后,它会自动关闭。解决方法就是让其一直在运行,这就用到了command配置。</p> 
    <p>创建pod-command.yaml文件,内容如下:</p> 
    <pre data-index="128" class="set-code-show prettyprint"><code class="prism language-yaml has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token key atrule">apiVersion</span><span class="token punctuation">:</span> <span class="token key atrule">v1kind</span><span class="token punctuation">:</span> <span class="token key atrule">Podmetadata</span><span class="token punctuation">:</span>  <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">pod-command  namespace</span><span class="token punctuation">:</span> <span class="token key atrule">devspec</span><span class="token punctuation">:</span>  <span class="token key atrule">containers</span><span class="token punctuation">:</span>  <span class="token punctuation">-</span> <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">nginx    image</span><span class="token punctuation">:</span> <span class="token key atrule">nginx:1.17.1  - name</span><span class="token punctuation">:</span> <span class="token key atrule">busybox    image</span><span class="token punctuation">:</span> <span class="token key atrule">busybox:1.30    command</span><span class="token punctuation">:</span> <span class="token punctuation">[</span><span class="token string">"/bin/sh"</span><span class="token punctuation">,</span><span class="token string">"-c"</span><span class="token punctuation">,</span><span class="token string">"touch /tmp/hello.txt;while true;do /bin/echo $(date +%T) >> /tmp/hello.txt; sleep 3; done;"</span><span class="token punctuation">]</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <p>command,用于在pod中的容器初始化完毕之后运行一个命令。</p> 
    <blockquote> 
     <p>稍微解释下上面命令的意思:</p> 
     <p>​ “/bin/sh”,“-c”, 使用sh执行命令</p> 
     <p>​ touch /tmp/hello.txt; 创建一个/tmp/hello.txt 文件</p> 
     <p>​ while true;do /bin/echo $(date +%T) >> /tmp/hello.txt; sleep 3; done; 每隔3秒向文件中写入当前时间</p> 
    </blockquote> 
    <pre data-index="129" class="set-code-show prettyprint"><code class="prism language-powershell has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token comment"># 创建Pod[root@master pod]# kubectl create  -f pod-command.yamlpod/pod-command created# 查看Pod状态# 此时发现两个pod都正常运行了[root@master pod]# kubectl get pods pod-command -n devNAME          READY   STATUS   RESTARTS   AGEpod-command   2/2     Runing   0          2s# 进入pod中的busybox容器,查看文件内容# 补充一个命令: kubectl exec  pod名称 -n 命名空间 -it -c 容器名称 /bin/sh  在容器内部执行命令# 使用这个命令就可以进入某个容器的内部,然后进行相关操作了# 比如,可以查看txt文件的内容[root@master pod]# kubectl exec pod-command -n dev -it -c busybox /bin/sh/ # tail -f /tmp/hello.txt13:35:3513:35:3813:35:41</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <pre data-index="130" class="set-code-show prettyprint"><code class="prism language-md has-numbering" onclick="mdcp.signin(event)" style="position: unset;">特别说明:    通过上面发现command已经可以完成启动命令和传递参数的功能,为什么这里还要提供一个args选项,用于传递参数呢?这其实跟docker有点关系,kubernetes中的command、args两项其实是实现覆盖Dockerfile中ENTRYPOINT的功能。 1 如果command和args均没有写,那么用Dockerfile的配置。 2 如果command写了,但args没有写,那么Dockerfile默认的配置会被忽略,执行输入的command 3 如果command没写,但args写了,那么Dockerfile中配置的ENTRYPOINT的命令会被执行,使用当前args的参数 4 如果command和args都写了,那么Dockerfile的配置被忽略,执行command并追加上args参数
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <h4><a name="t62"></a><a id="_2615"></a>环境变量</h4> 
    <p>创建pod-env.yaml文件,内容如下:</p> 
    <pre data-index="131" class="set-code-show prettyprint"><code class="prism language-yaml has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token key atrule">apiVersion</span><span class="token punctuation">:</span> <span class="token key atrule">v1kind</span><span class="token punctuation">:</span> <span class="token key atrule">Podmetadata</span><span class="token punctuation">:</span>  <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">pod-env  namespace</span><span class="token punctuation">:</span> <span class="token key atrule">devspec</span><span class="token punctuation">:</span>  <span class="token key atrule">containers</span><span class="token punctuation">:</span>  <span class="token punctuation">-</span> <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">busybox    image</span><span class="token punctuation">:</span> <span class="token key atrule">busybox:1.30    command</span><span class="token punctuation">:</span> <span class="token punctuation">[</span><span class="token string">"/bin/sh"</span><span class="token punctuation">,</span><span class="token string">"-c"</span><span class="token punctuation">,</span><span class="token string">"while true;do /bin/echo $(date +%T);sleep 60; done;"</span><span class="token punctuation">]</span>    env<span class="token punctuation">:</span> <span class="token comment"># 设置环境变量列表    - name: "username"      value: "admin"    - name: "password"      value: "123456"</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <p>env,环境变量,用于在pod中的容器设置环境变量。</p> 
    <pre data-index="132" class="set-code-show prettyprint"><code class="prism language-powershell has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token comment"># 创建Pod[root@master ~]# kubectl create -f pod-env.yamlpod/pod-env created# 进入容器,输出环境变量[root@master ~]# kubectl exec pod-env -n dev -c busybox -it /bin/sh/ # echo $usernameadmin/ # echo $password123456</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <p>这种方式不是很推荐,推荐将这些配置单独存储在配置文件中,这种方式将在后面介绍。</p> 
    <h4><a name="t63"></a><a id="_2631"></a>端口设置</h4> 
    <p>本小节来介绍容器的端口设置,也就是containers的ports选项。</p> 
    <p>首先看下ports支持的子选项:</p> 
    <pre data-index="133" class="set-code-show prettyprint"><code class="prism language-powershell has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token namespace">[root@master ~]</span><span class="token comment"># kubectl explain pod.spec.containers.portsKIND:     PodVERSION:  v1RESOURCE: ports <[]Object>FIELDS:   name         <string>  # 端口名称,如果指定,必须保证name在pod中是唯一的		   containerPort<integer> # 容器要监听的端口(0<x<65536)   hostPort     <integer> # 容器要在主机上公开的端口,如果设置,主机上只能运行容器的一个副本(一般省略)    hostIP       <string>  # 要将外部端口绑定到的主机IP(一般省略)   protocol     <string>  # 端口协议。必须是UDP、TCP或SCTP。默认为“TCP”。</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <p>接下来,编写一个测试案例,创建pod-ports.yaml</p> 
    <pre data-index="134" class="set-code-show prettyprint"><code class="prism language-yaml has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token key atrule">apiVersion</span><span class="token punctuation">:</span> <span class="token key atrule">v1kind</span><span class="token punctuation">:</span> <span class="token key atrule">Podmetadata</span><span class="token punctuation">:</span>  <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">pod-ports  namespace</span><span class="token punctuation">:</span> <span class="token key atrule">devspec</span><span class="token punctuation">:</span>  <span class="token key atrule">containers</span><span class="token punctuation">:</span>  <span class="token punctuation">-</span> <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">nginx    image</span><span class="token punctuation">:</span> <span class="token key atrule">nginx:1.17.1    ports</span><span class="token punctuation">:</span> <span class="token comment"># 设置容器暴露的端口列表    - name: nginx-port      containerPort: 80      protocol: TCP</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <pre data-index="135" class="set-code-show prettyprint"><code class="prism language-powershell has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token comment"># 创建Pod[root@master ~]# kubectl create -f pod-ports.yamlpod/pod-ports created# 查看pod# 在下面可以明显看到配置信息[root@master ~]# kubectl get pod pod-ports -n dev -o yaml......spec:  containers:  - image: nginx:1.17.1    imagePullPolicy: IfNotPresent    name: nginx    ports:    - containerPort: 80      name: nginx-port      protocol: TCP......</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <p>访问容器中的程序需要使用的是<code>podIp:containerPort</code></p> 
    <h4><a name="t64"></a><a id="_2653"></a>资源配额</h4> 
    <p>​ 容器中的程序要运行,肯定是要占用一定资源的,比如cpu和内存等,如果不对某个容器的资源做限制,那么它就可能吃掉大量资源,导致其它容器无法运行。针对这种情况,kubernetes提供了对内存和cpu的资源进行配额的机制,这种机制主要通过resources选项实现,他有两个子选项:</p> 
    <ul><li> <p>limits:用于限制运行时容器的最大占用资源,当容器占用资源超过limits时会被终止,并进行重启</p> </li><li> <p>requests :用于设置容器需要的最小资源,如果环境资源不够,容器将无法启动</p> </li></ul> 
    <p>可以通过上面两个选项设置资源的上下限。</p> 
    <p>接下来,编写一个测试案例,创建pod-resources.yaml</p> 
    <pre data-index="136" class="set-code-show prettyprint"><code class="prism language-yaml has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token key atrule">apiVersion</span><span class="token punctuation">:</span> <span class="token key atrule">v1kind</span><span class="token punctuation">:</span> <span class="token key atrule">Podmetadata</span><span class="token punctuation">:</span>  <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">pod-resources  namespace</span><span class="token punctuation">:</span> <span class="token key atrule">devspec</span><span class="token punctuation">:</span>  <span class="token key atrule">containers</span><span class="token punctuation">:</span>  <span class="token punctuation">-</span> <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">nginx    image</span><span class="token punctuation">:</span> <span class="token key atrule">nginx:1.17.1    resources</span><span class="token punctuation">:</span> <span class="token comment"># 资源配额      limits:  # 限制资源(上限)        cpu: "2" # CPU限制,单位是core数        memory: "10Gi" # 内存限制      requests: # 请求资源(下限)        cpu: "1"  # CPU限制,单位是core数        memory: "10Mi"  # 内存限制</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <p>在这对cpu和memory的单位做一个说明:</p> 
    <ul><li> <p>cpu:core数,可以为整数或小数</p> </li><li> <p>memory: 内存大小,可以使用Gi、Mi、G、M等形式</p> </li></ul> 
    <pre data-index="137" class="set-code-show prettyprint"><code class="prism language-powershell has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token comment"># 运行Pod[root@master ~]# kubectl create  -f pod-resources.yamlpod/pod-resources created# 查看发现pod运行正常[root@master ~]# kubectl get pod pod-resources -n devNAME            READY   STATUS    RESTARTS   AGE  pod-resources   1/1     Running   0          39s   # 接下来,停止Pod[root@master ~]# kubectl delete  -f pod-resources.yamlpod "pod-resources" deleted# 编辑pod,修改resources.requests.memory的值为10Gi[root@master ~]# vim pod-resources.yaml# 再次启动pod[root@master ~]# kubectl create  -f pod-resources.yamlpod/pod-resources created# 查看Pod状态,发现Pod启动失败[root@master ~]# kubectl get pod pod-resources -n dev -o wideNAME            READY   STATUS    RESTARTS   AGE          pod-resources   0/2     Pending   0          20s    # 查看pod详情会发现,如下提示[root@master ~]# kubectl describe pod pod-resources -n dev......Warning  FailedScheduling  <unknown>  default-scheduler  0/2 nodes are available: 2 Insufficient memory.(内存不足)</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <h3><a name="t65"></a><a id="Pod_2679"></a>Pod生命周期</h3> 
    <p>我们一般将pod对象从创建至终的这段时间范围称为pod的生命周期,它主要包含下面的过程:</p> 
    <ul><li> <p>pod创建过程</p> </li><li> <p>运行初始化容器(init container)过程</p> </li><li> <p>运行主容器(main container)</p> 
      <ul><li> <p>容器启动后钩子(post start)、容器终止前钩子(pre stop)</p> </li><li> <p>容器的存活性探测(liveness probe)、就绪性探测(readiness probe)</p> </li></ul> </li><li> <p>pod终止过程</p> </li></ul> 
    <img src="Kubernetes教程.assets/image-20200412111402706-16338582916262.png" alt="image-20200412111402706"> 
    <p>在整个生命周期中,Pod会出现5种<strong>状态</strong>(<strong>相位</strong>),分别如下:</p> 
    <ul><li>挂起(Pending):apiserver已经创建了pod资源对象,但它尚未被调度完成或者仍处于下载镜像的过程中</li><li>运行中(Running):pod已经被调度至某节点,并且所有容器都已经被kubelet创建完成</li><li>成功(Succeeded):pod中的所有容器都已经成功终止并且不会被重启</li><li>失败(Failed):所有容器都已经终止,但至少有一个容器终止失败,即容器返回了非0值的退出状态</li><li>未知(Unknown):apiserver无法正常获取到pod对象的状态信息,通常由网络通信失败所导致</li></ul> 
    <h4><a name="t66"></a><a id="_2706"></a>创建和终止</h4> 
    <p><strong>pod的创建过程</strong></p> 
    <ol><li> <p>用户通过kubectl或其他api客户端提交需要创建的pod信息给apiServer</p> </li><li> <p>apiServer开始生成pod对象的信息,并将信息存入etcd,然后返回确认信息至客户端</p> </li><li> <p>apiServer开始反映etcd中的pod对象的变化,其它组件使用watch机制来跟踪检查apiServer上的变动</p> </li><li> <p>scheduler发现有新的pod对象要创建,开始为Pod分配主机并将结果信息更新至apiServer</p> </li><li> <p>node节点上的kubelet发现有pod调度过来,尝试调用docker启动容器,并将结果回送至apiServer</p> </li><li> <p>apiServer将接收到的pod状态信息存入etcd中</p> <img src="Kubernetes教程.assets/image-20200406184656917-16338582916264.png" alt="image-20200406184656917"> </li></ol> 
    <p><strong>pod的终止过程</strong></p> 
    <ol><li>用户向apiServer发送删除pod对象的命令</li><li>apiServcer中的pod对象信息会随着时间的推移而更新,在宽限期内(默认30s),pod被视为dead</li><li>将pod标记为terminating状态</li><li>kubelet在监控到pod对象转为terminating状态的同时启动pod关闭过程</li><li>端点控制器监控到pod对象的关闭行为时将其从所有匹配到此端点的service资源的端点列表中移除</li><li>如果当前pod对象定义了preStop钩子处理器,则在其标记为terminating后即会以同步的方式启动执行</li><li>pod对象中的容器进程收到停止信号</li><li>宽限期结束后,若pod中还存在仍在运行的进程,那么pod对象会收到立即终止的信号</li><li>kubelet请求apiServer将此pod资源的宽限期设置为0从而完成删除操作,此时pod对于用户已不可见</li></ol> 
    <h4><a name="t67"></a><a id="_2737"></a>初始化容器</h4> 
    <p>初始化容器是在pod的主容器启动之前要运行的容器,主要是做一些主容器的前置工作,它具有两大特征:</p> 
    <ol><li>初始化容器必须运行完成直至结束,若某初始化容器运行失败,那么kubernetes需要重启它直到成功完成</li><li>初始化容器必须按照定义的顺序执行,当且仅当前一个成功之后,后面的一个才能运行</li></ol> 
    <p>初始化容器有很多的应用场景,下面列出的是最常见的几个:</p> 
    <ul><li>提供主容器镜像中不具备的工具程序或自定义代码</li><li>初始化容器要先于应用容器串行启动并运行完成,因此可用于延后应用容器的启动直至其依赖的条件得到满足</li></ul> 
    <p>接下来做一个案例,模拟下面这个需求:</p> 
    <p>​ 假设要以主容器来运行nginx,但是要求在运行nginx之前先要能够连接上mysql和redis所在服务器</p> 
    <p>​ 为了简化测试,事先规定好mysql<code>(192.168.109.201)</code>和redis<code>(192.168.109.202)</code>服务器的地址</p> 
    <p>创建pod-initcontainer.yaml,内容如下:</p> 
    <pre data-index="138" class="set-code-show prettyprint"><code class="prism language-yaml has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token key atrule">apiVersion</span><span class="token punctuation">:</span> <span class="token key atrule">v1kind</span><span class="token punctuation">:</span> <span class="token key atrule">Podmetadata</span><span class="token punctuation">:</span>  <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">pod-initcontainer  namespace</span><span class="token punctuation">:</span> <span class="token key atrule">devspec</span><span class="token punctuation">:</span>  <span class="token key atrule">containers</span><span class="token punctuation">:</span>  <span class="token punctuation">-</span> <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">main-container    image</span><span class="token punctuation">:</span> <span class="token key atrule">nginx:1.17.1    ports</span><span class="token punctuation">:</span>     <span class="token punctuation">-</span> <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">nginx-port      containerPort</span><span class="token punctuation">:</span> <span class="token key atrule">80  initContainers</span><span class="token punctuation">:</span>  <span class="token punctuation">-</span> <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">test-mysql    image</span><span class="token punctuation">:</span> <span class="token key atrule">busybox:1.30    command</span><span class="token punctuation">:</span> <span class="token punctuation">[</span><span class="token string">'sh'</span><span class="token punctuation">,</span> <span class="token string">'-c'</span><span class="token punctuation">,</span> <span class="token string">'until ping 192.168.109.201 -c 1 ; do echo waiting for mysql...; sleep 2; done;'</span><span class="token punctuation">]</span>  <span class="token punctuation">-</span> <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">test-redis    image</span><span class="token punctuation">:</span> <span class="token key atrule">busybox:1.30    command</span><span class="token punctuation">:</span> <span class="token punctuation">[</span><span class="token string">'sh'</span><span class="token punctuation">,</span> <span class="token string">'-c'</span><span class="token punctuation">,</span> <span class="token string">'until ping 192.168.109.202 -c 1 ; do echo waiting for reids...; sleep 2; done;'</span><span class="token punctuation">]</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <pre data-index="139" class="set-code-show prettyprint"><code class="prism language-powershell has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token comment"># 创建pod[root@master ~]# kubectl create -f pod-initcontainer.yamlpod/pod-initcontainer created# 查看pod状态# 发现pod卡在启动第一个初始化容器过程中,后面的容器不会运行root@master ~]# kubectl describe pod  pod-initcontainer -n dev........Events:  Type    Reason     Age   From               Message  ----    ------     ----  ----               -------  Normal  Scheduled  49s   default-scheduler  Successfully assigned dev/pod-initcontainer to node1  Normal  Pulled     48s   kubelet, node1     Container image "busybox:1.30" already present on machine  Normal  Created    48s   kubelet, node1     Created container test-mysql  Normal  Started    48s   kubelet, node1     Started container test-mysql# 动态查看pod[root@master ~]# kubectl get pods pod-initcontainer -n dev -wNAME                             READY   STATUS     RESTARTS   AGEpod-initcontainer                0/1     Init:0/2   0          15spod-initcontainer                0/1     Init:1/2   0          52spod-initcontainer                0/1     Init:1/2   0          53spod-initcontainer                0/1     PodInitializing   0          89spod-initcontainer                1/1     Running           0          90s# 接下来新开一个shell,为当前服务器新增两个ip,观察pod的变化[root@master ~]# ifconfig ens33:1 192.168.109.201 netmask 255.255.255.0 up[root@master ~]# ifconfig ens33:2 192.168.109.202 netmask 255.255.255.0 up</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <h4><a name="t68"></a><a id="_2765"></a>钩子函数</h4> 
    <p>钩子函数能够感知自身生命周期中的事件,并在相应的时刻到来时运行用户指定的程序代码。</p> 
    <p>kubernetes在主容器的启动之后和停止之前提供了两个钩子函数:</p> 
    <ul><li>post start:容器创建之后执行,如果失败了会重启容器</li><li>pre stop :容器终止之前执行,执行完成之后容器将成功终止,在其完成之前会阻塞删除容器的操作</li></ul> 
    <p>钩子处理器支持使用下面三种方式定义动作:</p> 
    <ul><li> <p>Exec命令:在容器内执行一次命令</p> <pre data-index="140" class="set-code-show prettyprint"><code class="prism language-yaml has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token key atrule">……  lifecycle</span><span class="token punctuation">:</span>    <span class="token key atrule">postStart</span><span class="token punctuation">:</span>       <span class="token key atrule">exec</span><span class="token punctuation">:</span>        <span class="token key atrule">command</span><span class="token punctuation">:</span>        <span class="token punctuation">-</span> cat        <span class="token punctuation">-</span> /tmp/healthy……
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> </li><li> <p>TCPSocket:在当前容器尝试访问指定的socket</p> <pre data-index="141" class="set-code-show prettyprint"><code class="prism language-yaml has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token key atrule">……        lifecycle</span><span class="token punctuation">:</span>    <span class="token key atrule">postStart</span><span class="token punctuation">:</span>      <span class="token key atrule">tcpSocket</span><span class="token punctuation">:</span>        <span class="token key atrule">port</span><span class="token punctuation">:</span> 8080……
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> </li><li> <p>HTTPGet:在当前容器中向某url发起http请求</p> <pre data-index="142" class="set-code-show prettyprint"><code class="prism language-yaml has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token key atrule">……  lifecycle</span><span class="token punctuation">:</span>    <span class="token key atrule">postStart</span><span class="token punctuation">:</span>      <span class="token key atrule">httpGet</span><span class="token punctuation">:</span>        <span class="token key atrule">path</span><span class="token punctuation">:</span> / <span class="token comment">#URI地址        port: 80 #端口号        host: 192.168.109.100 #主机地址        scheme: HTTP #支持的协议,http或者https……</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> </li></ul> 
    <p>接下来,以exec方式为例,演示下钩子函数的使用,创建pod-hook-exec.yaml文件,内容如下:</p> 
    <pre data-index="143" class="set-code-show prettyprint"><code class="prism language-yaml has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token key atrule">apiVersion</span><span class="token punctuation">:</span> <span class="token key atrule">v1kind</span><span class="token punctuation">:</span> <span class="token key atrule">Podmetadata</span><span class="token punctuation">:</span>  <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">pod-hook-exec  namespace</span><span class="token punctuation">:</span> <span class="token key atrule">devspec</span><span class="token punctuation">:</span>  <span class="token key atrule">containers</span><span class="token punctuation">:</span>  <span class="token punctuation">-</span> <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">main-container    image</span><span class="token punctuation">:</span> <span class="token key atrule">nginx:1.17.1    ports</span><span class="token punctuation">:</span>    <span class="token punctuation">-</span> <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">nginx-port      containerPort</span><span class="token punctuation">:</span> <span class="token key atrule">80    lifecycle</span><span class="token punctuation">:</span>      <span class="token key atrule">postStart</span><span class="token punctuation">:</span>         <span class="token key atrule">exec</span><span class="token punctuation">:</span> <span class="token comment"># 在容器启动的时候执行一个命令,修改掉nginx的默认首页内容          command: ["/bin/sh", "-c", "echo postStart... > /usr/share/nginx/html/index.html"]      preStop:        exec: # 在容器停止之前停止nginx服务          command: ["/usr/sbin/nginx","-s","quit"]</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <pre data-index="144" class="set-code-show prettyprint"><code class="prism language-powershell has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token comment"># 创建pod[root@master ~]# kubectl create -f pod-hook-exec.yamlpod/pod-hook-exec created# 查看pod[root@master ~]# kubectl get pods  pod-hook-exec -n dev -o wideNAME           READY   STATUS     RESTARTS   AGE    IP            NODE    pod-hook-exec  1/1     Running    0          29s    10.244.2.48   node2   # 访问pod[root@master ~]# curl 10.244.2.48postStart...</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <h4><a name="t69"></a><a id="_2804"></a>容器探测</h4> 
    <p>​ 容器探测用于检测容器中的应用实例是否正常工作,是保障业务可用性的一种传统机制。如果经过探测,实例的状态不符合预期,那么kubernetes就会把该问题实例" 摘除 ",不承担业务流量。kubernetes提供了两种探针来实现容器探测,分别是:</p> 
    <ul><li> <p>liveness probes:存活性探针,用于检测应用实例当前是否处于正常运行状态,如果不是,k8s会重启容器</p> </li><li> <p>readiness probes:就绪性探针,用于检测应用实例当前是否可以接收请求,如果不能,k8s不会转发流量</p> </li></ul> 
    <blockquote> 
     <p>livenessProbe 决定是否重启容器,readinessProbe 决定是否将请求转发给容器。</p> 
    </blockquote> 
    <p>上面两种探针目前均支持三种探测方式:</p> 
    <ul><li> <p>Exec命令:在容器内执行一次命令,如果命令执行的退出码为0,则认为程序正常,否则不正常</p> <pre data-index="145" class="set-code-show prettyprint"><code class="prism language-yaml has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token key atrule">……  livenessProbe</span><span class="token punctuation">:</span>    <span class="token key atrule">exec</span><span class="token punctuation">:</span>      <span class="token key atrule">command</span><span class="token punctuation">:</span>      <span class="token punctuation">-</span> cat      <span class="token punctuation">-</span> /tmp/healthy……
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> </li><li> <p>TCPSocket:将会尝试访问一个用户容器的端口,如果能够建立这条连接,则认为程序正常,否则不正常</p> <pre data-index="146" class="set-code-show prettyprint"><code class="prism language-yaml has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token key atrule">……        livenessProbe</span><span class="token punctuation">:</span>    <span class="token key atrule">tcpSocket</span><span class="token punctuation">:</span>      <span class="token key atrule">port</span><span class="token punctuation">:</span> 8080……
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> </li><li> <p>HTTPGet:调用容器内Web应用的URL,如果返回的状态码在200和399之间,则认为程序正常,否则不正常</p> <pre data-index="147" class="set-code-show prettyprint"><code class="prism language-yaml has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token key atrule">……  livenessProbe</span><span class="token punctuation">:</span>    <span class="token key atrule">httpGet</span><span class="token punctuation">:</span>      <span class="token key atrule">path</span><span class="token punctuation">:</span> / <span class="token comment">#URI地址      port: 80 #端口号      host: 127.0.0.1 #主机地址      scheme: HTTP #支持的协议,http或者https……</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> </li></ul> 
    <p>下面以liveness probes为例,做几个演示:</p> 
    <p><strong>方式一:Exec</strong></p> 
    <p>创建pod-liveness-exec.yaml</p> 
    <pre data-index="148" class="set-code-show prettyprint"><code class="prism language-yaml has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token key atrule">apiVersion</span><span class="token punctuation">:</span> <span class="token key atrule">v1kind</span><span class="token punctuation">:</span> <span class="token key atrule">Podmetadata</span><span class="token punctuation">:</span>  <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">pod-liveness-exec  namespace</span><span class="token punctuation">:</span> <span class="token key atrule">devspec</span><span class="token punctuation">:</span>  <span class="token key atrule">containers</span><span class="token punctuation">:</span>  <span class="token punctuation">-</span> <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">nginx    image</span><span class="token punctuation">:</span> <span class="token key atrule">nginx:1.17.1    ports</span><span class="token punctuation">:</span>     <span class="token punctuation">-</span> <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">nginx-port      containerPort</span><span class="token punctuation">:</span> <span class="token key atrule">80    livenessProbe</span><span class="token punctuation">:</span>      <span class="token key atrule">exec</span><span class="token punctuation">:</span>        <span class="token key atrule">command</span><span class="token punctuation">:</span> <span class="token punctuation">[</span><span class="token string">"/bin/cat"</span><span class="token punctuation">,</span><span class="token string">"/tmp/hello.txt"</span><span class="token punctuation">]</span> <span class="token comment"># 执行一个查看文件的命令</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <p>创建pod,观察效果</p> 
    <pre data-index="149" class="set-code-show prettyprint"><code class="prism language-powershell has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token comment"># 创建Pod[root@master ~]# kubectl create -f pod-liveness-exec.yamlpod/pod-liveness-exec created# 查看Pod详情[root@master ~]# kubectl describe pods pod-liveness-exec -n dev......  Normal   Created    20s (x2 over 50s)  kubelet, node1     Created container nginx  Normal   Started    20s (x2 over 50s)  kubelet, node1     Started container nginx  Normal   Killing    20s                kubelet, node1     Container nginx failed liveness probe, will be restarted  Warning  Unhealthy  0s (x5 over 40s)   kubelet, node1     Liveness probe failed: cat: can't open '/tmp/hello11.txt': No such file or directory  # 观察上面的信息就会发现nginx容器启动之后就进行了健康检查# 检查失败之后,容器被kill掉,然后尝试进行重启(这是重启策略的作用,后面讲解)# 稍等一会之后,再观察pod信息,就可以看到RESTARTS不再是0,而是一直增长[root@master ~]# kubectl get pods pod-liveness-exec -n devNAME                READY   STATUS             RESTARTS   AGEpod-liveness-exec   0/1     CrashLoopBackOff   2          3m19s# 当然接下来,可以修改成一个存在的文件,比如/tmp/hello.txt,再试,结果就正常了......</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <p><strong>方式二:TCPSocket</strong></p> 
    <p>创建pod-liveness-tcpsocket.yaml</p> 
    <pre data-index="150" class="set-code-show prettyprint"><code class="prism language-yaml has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token key atrule">apiVersion</span><span class="token punctuation">:</span> <span class="token key atrule">v1kind</span><span class="token punctuation">:</span> <span class="token key atrule">Podmetadata</span><span class="token punctuation">:</span>  <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">pod-liveness-tcpsocket  namespace</span><span class="token punctuation">:</span> <span class="token key atrule">devspec</span><span class="token punctuation">:</span>  <span class="token key atrule">containers</span><span class="token punctuation">:</span>  <span class="token punctuation">-</span> <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">nginx    image</span><span class="token punctuation">:</span> <span class="token key atrule">nginx:1.17.1    ports</span><span class="token punctuation">:</span>     <span class="token punctuation">-</span> <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">nginx-port      containerPort</span><span class="token punctuation">:</span> <span class="token key atrule">80    livenessProbe</span><span class="token punctuation">:</span>      <span class="token key atrule">tcpSocket</span><span class="token punctuation">:</span>        <span class="token key atrule">port</span><span class="token punctuation">:</span> <span class="token number">8080</span> <span class="token comment"># 尝试访问8080端口</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <p>创建pod,观察效果</p> 
    <pre data-index="151" class="set-code-show prettyprint"><code class="prism language-powershell has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token comment"># 创建Pod[root@master ~]# kubectl create -f pod-liveness-tcpsocket.yamlpod/pod-liveness-tcpsocket created# 查看Pod详情[root@master ~]# kubectl describe pods pod-liveness-tcpsocket -n dev......  Normal   Scheduled  31s                            default-scheduler  Successfully assigned dev/pod-liveness-tcpsocket to node2  Normal   Pulled     <invalid>                      kubelet, node2     Container image "nginx:1.17.1" already present on machine  Normal   Created    <invalid>                      kubelet, node2     Created container nginx  Normal   Started    <invalid>                      kubelet, node2     Started container nginx  Warning  Unhealthy  <invalid> (x2 over <invalid>)  kubelet, node2     Liveness probe failed: dial tcp 10.244.2.44:8080: connect: connection refused  # 观察上面的信息,发现尝试访问8080端口,但是失败了# 稍等一会之后,再观察pod信息,就可以看到RESTARTS不再是0,而是一直增长[root@master ~]# kubectl get pods pod-liveness-tcpsocket  -n devNAME                     READY   STATUS             RESTARTS   AGEpod-liveness-tcpsocket   0/1     CrashLoopBackOff   2          3m19s# 当然接下来,可以修改成一个可以访问的端口,比如80,再试,结果就正常了......</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <p><strong>方式三:HTTPGet</strong></p> 
    <p>创建pod-liveness-httpget.yaml</p> 
    <pre data-index="152" class="set-code-show prettyprint"><code class="prism language-yaml has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token key atrule">apiVersion</span><span class="token punctuation">:</span> <span class="token key atrule">v1kind</span><span class="token punctuation">:</span> <span class="token key atrule">Podmetadata</span><span class="token punctuation">:</span>  <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">pod-liveness-httpget  namespace</span><span class="token punctuation">:</span> <span class="token key atrule">devspec</span><span class="token punctuation">:</span>  <span class="token key atrule">containers</span><span class="token punctuation">:</span>  <span class="token punctuation">-</span> <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">nginx    image</span><span class="token punctuation">:</span> <span class="token key atrule">nginx:1.17.1    ports</span><span class="token punctuation">:</span>    <span class="token punctuation">-</span> <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">nginx-port      containerPort</span><span class="token punctuation">:</span> <span class="token key atrule">80    livenessProbe</span><span class="token punctuation">:</span>      <span class="token key atrule">httpGet</span><span class="token punctuation">:</span>  <span class="token comment"># 其实就是访问http://127.0.0.1:80/hello          scheme: HTTP #支持的协议,http或者https        port: 80 #端口号        path: /hello #URI地址</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <p>创建pod,观察效果</p> 
    <pre data-index="153" class="set-code-show prettyprint"><code class="prism language-powershell has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token comment"># 创建Pod[root@master ~]# kubectl create -f pod-liveness-httpget.yamlpod/pod-liveness-httpget created# 查看Pod详情[root@master ~]# kubectl describe pod pod-liveness-httpget -n dev.......  Normal   Pulled     6s (x3 over 64s)  kubelet, node1     Container image "nginx:1.17.1" already present on machine  Normal   Created    6s (x3 over 64s)  kubelet, node1     Created container nginx  Normal   Started    6s (x3 over 63s)  kubelet, node1     Started container nginx  Warning  Unhealthy  6s (x6 over 56s)  kubelet, node1     Liveness probe failed: HTTP probe failed with statuscode: 404  Normal   Killing    6s (x2 over 36s)  kubelet, node1     Container nginx failed liveness probe, will be restarted  # 观察上面信息,尝试访问路径,但是未找到,出现404错误# 稍等一会之后,再观察pod信息,就可以看到RESTARTS不再是0,而是一直增长[root@master ~]# kubectl get pod pod-liveness-httpget -n devNAME                   READY   STATUS    RESTARTS   AGEpod-liveness-httpget   1/1     Running   5          3m17s# 当然接下来,可以修改成一个可以访问的路径path,比如/,再试,结果就正常了......</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <p>​ 至此,已经使用liveness Probe演示了三种探测方式,但是查看livenessProbe的子属性,会发现除了这三种方式,还有一些其他的配置,在这里一并解释下:</p> 
    <pre data-index="154" class="set-code-show prettyprint"><code class="prism language-powershell has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token namespace">[root@master ~]</span><span class="token comment"># kubectl explain pod.spec.containers.livenessProbeFIELDS:   exec <Object>     tcpSocket    <Object>   httpGet      <Object>   initialDelaySeconds  <integer>  # 容器启动后等待多少秒执行第一次探测   timeoutSeconds       <integer>  # 探测超时时间。默认1秒,最小1秒   periodSeconds        <integer>  # 执行探测的频率。默认是10秒,最小1秒   failureThreshold     <integer>  # 连续探测失败多少次才被认定为失败。默认是3。最小值是1   successThreshold     <integer>  # 连续探测成功多少次才被认定为成功。默认是1</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <p>下面稍微配置两个,演示下效果即可:</p> 
    <pre data-index="155" class="set-code-show prettyprint"><code class="prism language-yaml has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token punctuation">[</span>root@master ~<span class="token punctuation">]</span><span class="token comment"># more pod-liveness-httpget.yamlapiVersion: v1kind: Podmetadata:  name: pod-liveness-httpget  namespace: devspec:  containers:  - name: nginx    image: nginx:1.17.1    ports:    - name: nginx-port      containerPort: 80    livenessProbe:      httpGet:        scheme: HTTP        port: 80         path: /      initialDelaySeconds: 30 # 容器启动后30s开始探测      timeoutSeconds: 5 # 探测超时时间为5s</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <h4><a name="t70"></a><a id="_2890"></a>重启策略</h4> 
    <p>​ 在上一节中,一旦容器探测出现了问题,kubernetes就会对容器所在的Pod进行重启,其实这是由pod的重启策略决定的,pod的重启策略有 3 种,分别如下:</p> 
    <ul><li>Always :容器失效时,自动重启该容器,这也是默认值。</li><li>OnFailure : 容器终止运行且退出码不为0时重启</li><li>Never : 不论状态为何,都不重启该容器</li></ul> 
    <p>​ 重启策略适用于pod对象中的所有容器,首次需要重启的容器,将在其需要时立即进行重启,随后再次需要重启的操作将由kubelet延迟一段时间后进行,且反复的重启操作的延迟时长以此为10s、20s、40s、80s、160s和300s,300s是最大延迟时长。</p> 
    <p>创建pod-restartpolicy.yaml:</p> 
    <pre data-index="156" class="set-code-show prettyprint"><code class="prism language-yaml has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token key atrule">apiVersion</span><span class="token punctuation">:</span> <span class="token key atrule">v1kind</span><span class="token punctuation">:</span> <span class="token key atrule">Podmetadata</span><span class="token punctuation">:</span>  <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">pod-restartpolicy  namespace</span><span class="token punctuation">:</span> <span class="token key atrule">devspec</span><span class="token punctuation">:</span>  <span class="token key atrule">containers</span><span class="token punctuation">:</span>  <span class="token punctuation">-</span> <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">nginx    image</span><span class="token punctuation">:</span> <span class="token key atrule">nginx:1.17.1    ports</span><span class="token punctuation">:</span>    <span class="token punctuation">-</span> <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">nginx-port      containerPort</span><span class="token punctuation">:</span> <span class="token key atrule">80    livenessProbe</span><span class="token punctuation">:</span>      <span class="token key atrule">httpGet</span><span class="token punctuation">:</span>        <span class="token key atrule">scheme</span><span class="token punctuation">:</span> <span class="token key atrule">HTTP        port</span><span class="token punctuation">:</span> <span class="token key atrule">80        path</span><span class="token punctuation">:</span> <span class="token key atrule">/hello  restartPolicy</span><span class="token punctuation">:</span> Never <span class="token comment"># 设置重启策略为Never</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <p>运行Pod测试</p> 
    <pre data-index="157" class="set-code-show prettyprint"><code class="prism language-powershell has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token comment"># 创建Pod[root@master ~]# kubectl create -f pod-restartpolicy.yamlpod/pod-restartpolicy created# 查看Pod详情,发现nginx容器失败[root@master ~]# kubectl  describe pods pod-restartpolicy  -n dev......  Warning  Unhealthy  15s (x3 over 35s)  kubelet, node1     Liveness probe failed: HTTP probe failed with statuscode: 404  Normal   Killing    15s                kubelet, node1     Container nginx failed liveness probe  # 多等一会,再观察pod的重启次数,发现一直是0,并未重启   [root@master ~]# kubectl  get pods pod-restartpolicy -n devNAME                   READY   STATUS    RESTARTS   AGEpod-restartpolicy      0/1     Running   0          5min42s</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <h3><a name="t71"></a><a id="Pod_2912"></a>Pod调度</h3> 
    <p>​ 在默认情况下,一个Pod在哪个Node节点上运行,是由Scheduler组件采用相应的算法计算出来的,这个过程是不受人工控制的。但是在实际使用中,这并不满足的需求,因为很多情况下,我们想控制某些Pod到达某些节点上,那么应该怎么做呢?这就要求了解kubernetes对Pod的调度规则,kubernetes提供了四大类调度方式:</p> 
    <ul><li>自动调度:运行在哪个节点上完全由Scheduler经过一系列的算法计算得出</li><li>定向调度:NodeName、NodeSelector</li><li>亲和性调度:NodeAffinity、PodAffinity、PodAntiAffinity</li><li>污点(容忍)调度:Taints、Toleration</li></ul> 
    <h4><a name="t72"></a><a id="_2921"></a>定向调度</h4> 
    <p>​ 定向调度,指的是利用在pod上声明nodeName或者nodeSelector,以此将Pod调度到期望的node节点上。注意,这里的调度是强制的,这就意味着即使要调度的目标Node不存在,也会向上面进行调度,只不过pod运行失败而已。</p> 
    <p><strong>NodeName</strong></p> 
    <p>​ NodeName用于强制约束将Pod调度到指定的Name的Node节点上。这种方式,其实是直接跳过Scheduler的调度逻辑,直接将Pod调度到指定名称的节点。</p> 
    <p>接下来,实验一下:创建一个pod-nodename.yaml文件</p> 
    <pre data-index="158" class="set-code-show prettyprint"><code class="prism language-yaml has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token key atrule">apiVersion</span><span class="token punctuation">:</span> <span class="token key atrule">v1kind</span><span class="token punctuation">:</span> <span class="token key atrule">Podmetadata</span><span class="token punctuation">:</span>  <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">pod-nodename  namespace</span><span class="token punctuation">:</span> <span class="token key atrule">devspec</span><span class="token punctuation">:</span>  <span class="token key atrule">containers</span><span class="token punctuation">:</span>  <span class="token punctuation">-</span> <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">nginx    image</span><span class="token punctuation">:</span> <span class="token key atrule">nginx:1.17.1  nodeName</span><span class="token punctuation">:</span> node1 <span class="token comment"># 指定调度到node1节点上</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <pre data-index="159" class="set-code-show prettyprint"><code class="prism language-powershell has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token comment">#创建Pod[root@master ~]# kubectl create -f pod-nodename.yamlpod/pod-nodename created#查看Pod调度到NODE属性,确实是调度到了node1节点上[root@master ~]# kubectl get pods pod-nodename -n dev -o wideNAME           READY   STATUS    RESTARTS   AGE   IP            NODE      ......pod-nodename   1/1     Running   0          56s   10.244.1.87   node1     ......   # 接下来,删除pod,修改nodeName的值为node3(并没有node3节点)[root@master ~]# kubectl delete -f pod-nodename.yamlpod "pod-nodename" deleted[root@master ~]# vim pod-nodename.yaml[root@master ~]# kubectl create -f pod-nodename.yamlpod/pod-nodename created#再次查看,发现已经向Node3节点调度,但是由于不存在node3节点,所以pod无法正常运行[root@master ~]# kubectl get pods pod-nodename -n dev -o wideNAME           READY   STATUS    RESTARTS   AGE   IP       NODE    ......pod-nodename   0/1     Pending   0          6s    <none>   node3   ......           </span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <p><strong>NodeSelector</strong></p> 
    <p>​ NodeSelector用于将pod调度到添加了指定标签的node节点上。它是通过kubernetes的label-selector机制实现的,也就是说,在pod创建之前,会由scheduler使用MatchNodeSelector调度策略进行label匹配,找出目标node,然后将pod调度到目标节点,该匹配规则是强制约束。</p> 
    <p>接下来,实验一下:</p> 
    <p>1 首先分别为node节点添加标签</p> 
    <pre data-index="160" class="set-code-show prettyprint"><code class="prism language-powershell has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token namespace">[root@master ~]</span><span class="token comment"># kubectl label nodes node1 nodeenv=pronode/node2 labeled[root@master ~]# kubectl label nodes node2 nodeenv=testnode/node2 labeled</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <p>2 创建一个pod-nodeselector.yaml文件,并使用它创建Pod</p> 
    <pre data-index="161" class="set-code-show prettyprint"><code class="prism language-yaml has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token key atrule">apiVersion</span><span class="token punctuation">:</span> <span class="token key atrule">v1kind</span><span class="token punctuation">:</span> <span class="token key atrule">Podmetadata</span><span class="token punctuation">:</span>  <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">pod-nodeselector  namespace</span><span class="token punctuation">:</span> <span class="token key atrule">devspec</span><span class="token punctuation">:</span>  <span class="token key atrule">containers</span><span class="token punctuation">:</span>  <span class="token punctuation">-</span> <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">nginx    image</span><span class="token punctuation">:</span> <span class="token key atrule">nginx:1.17.1  nodeSelector</span><span class="token punctuation">:</span>     <span class="token key atrule">nodeenv</span><span class="token punctuation">:</span> pro <span class="token comment"># 指定调度到具有nodeenv=pro标签的节点上</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <pre data-index="162" class="set-code-show prettyprint"><code class="prism language-powershell has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token comment">#创建Pod[root@master ~]# kubectl create -f pod-nodeselector.yamlpod/pod-nodeselector created#查看Pod调度到NODE属性,确实是调度到了node1节点上[root@master ~]# kubectl get pods pod-nodeselector -n dev -o wideNAME               READY   STATUS    RESTARTS   AGE     IP          NODE    ......pod-nodeselector   1/1     Running   0          47s   10.244.1.87   node1   ......# 接下来,删除pod,修改nodeSelector的值为nodeenv: xxxx(不存在打有此标签的节点)[root@master ~]# kubectl delete -f pod-nodeselector.yamlpod "pod-nodeselector" deleted[root@master ~]# vim pod-nodeselector.yaml[root@master ~]# kubectl create -f pod-nodeselector.yamlpod/pod-nodeselector created#再次查看,发现pod无法正常运行,Node的值为none[root@master ~]# kubectl get pods -n dev -o wideNAME               READY   STATUS    RESTARTS   AGE     IP       NODE    pod-nodeselector   0/1     Pending   0          2m20s   <none>   <none># 查看详情,发现node selector匹配失败的提示[root@master ~]# kubectl describe pods pod-nodeselector -n dev.......Events:  Type     Reason            Age        From               Message  ----     ------            ----       ----               -------  Warning  FailedScheduling  <unknown>  default-scheduler  0/3 nodes are available: 3 node(s) didn't match node selector.  Warning  FailedScheduling  <unknown>  default-scheduler  0/3 nodes are available: 3 node(s) didn't match node selector.</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <h4><a name="t73"></a><a id="_2961"></a>亲和性调度</h4> 
    <p>​ 上一节,介绍了两种定向调度的方式,使用起来非常方便,但是也有一定的问题,那就是如果没有满足条件的Node,那么Pod将不会被运行,即使在集群中还有可用Node列表也不行,这就限制了它的使用场景。</p> 
    <p>​ 基于上面的问题,kubernetes还提供了一种亲和性调度(Affinity)。它在NodeSelector的基础之上的进行了扩展,可以通过配置的形式,实现优先选择满足条件的Node进行调度,如果没有,也可以调度到不满足条件的节点上,使调度更加灵活。</p> 
    <p>Affinity主要分为三类:</p> 
    <ul><li> <p>nodeAffinity(node亲和性): 以node为目标,解决pod可以调度到哪些node的问题</p> </li><li> <p>podAffinity(pod亲和性) : 以pod为目标,解决pod可以和哪些已存在的pod部署在同一个拓扑域中的问题</p> </li><li> <p>podAntiAffinity(pod反亲和性) : 以pod为目标,解决pod不能和哪些已存在pod部署在同一个拓扑域中的问题</p> </li></ul> 
    <blockquote> 
     <p>关于亲和性(反亲和性)使用场景的说明:</p> 
     <p><strong>亲和性</strong>:如果两个应用频繁交互,那就有必要利用亲和性让两个应用的尽可能的靠近,这样可以减少因网络通信而带来的性能损耗。</p> 
     <p><strong>反亲和性</strong>:当应用的采用多副本部署时,有必要采用反亲和性让各个应用实例打散分布在各个node上,这样可以提高服务的高可用性。</p> 
    </blockquote> 
    <p><strong>NodeAffinity</strong></p> 
    <p>首先来看一下<code>NodeAffinity</code>的可配置项:</p> 
    <pre data-index="163" class="set-code-show prettyprint"><code class="prism language-markdown has-numbering" onclick="mdcp.signin(event)" style="position: unset;">pod.spec.affinity.nodeAffinity  requiredDuringSchedulingIgnoredDuringExecution  Node节点必须满足指定的所有规则才可以,相当于硬限制    nodeSelectorTerms  节点选择列表      matchFields   按节点字段列出的节点选择器要求列表      matchExpressions   按节点标签列出的节点选择器要求列表(推荐)        key    键        values 值        operator 关系符 支持Exists, DoesNotExist, In, NotIn, Gt, Lt  preferredDuringSchedulingIgnoredDuringExecution 优先调度到满足指定的规则的Node,相当于软限制 (倾向)    preference   一个节点选择器项,与相应的权重相关联      matchFields   按节点字段列出的节点选择器要求列表      matchExpressions   按节点标签列出的节点选择器要求列表(推荐)        key    键        values 值        operator 关系符 支持In, NotIn, Exists, DoesNotExist, Gt, Lt	weight 倾向权重,在范围1-100。
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <pre data-index="164" class="set-code-show prettyprint"><code class="prism language-markdown has-numbering" onclick="mdcp.signin(event)" style="position: unset;">关系符的使用说明:- matchExpressions:  - key: nodeenv              # 匹配存在标签的key为nodeenv的节点    operator: Exists  - key: nodeenv              # 匹配标签的key为nodeenv,且value是"xxx"或"yyy"的节点    operator: In    values: ["xxx","yyy"]  - key: nodeenv              # 匹配标签的key为nodeenv,且value大于"xxx"的节点    operator: Gt    values: "xxx"
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <p>接下来首先演示一下<code>requiredDuringSchedulingIgnoredDuringExecution</code> ,</p> 
    <p>创建pod-nodeaffinity-required.yaml</p> 
    <pre data-index="165" class="set-code-show prettyprint"><code class="prism language-yaml has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token key atrule">apiVersion</span><span class="token punctuation">:</span> <span class="token key atrule">v1kind</span><span class="token punctuation">:</span> <span class="token key atrule">Podmetadata</span><span class="token punctuation">:</span>  <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">pod-nodeaffinity-required  namespace</span><span class="token punctuation">:</span> <span class="token key atrule">devspec</span><span class="token punctuation">:</span>  <span class="token key atrule">containers</span><span class="token punctuation">:</span>  <span class="token punctuation">-</span> <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">nginx    image</span><span class="token punctuation">:</span> <span class="token key atrule">nginx:1.17.1  affinity</span><span class="token punctuation">:</span>  <span class="token comment">#亲和性设置    nodeAffinity: #设置node亲和性      requiredDuringSchedulingIgnoredDuringExecution: # 硬限制        nodeSelectorTerms:        - matchExpressions: # 匹配env的值在["xxx","yyy"]中的标签          - key: nodeenv            operator: In            values: ["xxx","yyy"]</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <pre data-index="166" class="set-code-show prettyprint"><code class="prism language-powershell has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token comment"># 创建pod[root@master ~]# kubectl create -f pod-nodeaffinity-required.yamlpod/pod-nodeaffinity-required created# 查看pod状态 (运行失败)[root@master ~]# kubectl get pods pod-nodeaffinity-required -n dev -o wideNAME                        READY   STATUS    RESTARTS   AGE   IP       NODE    ...... pod-nodeaffinity-required   0/1     Pending   0          16s   <none>   <none>  ......# 查看Pod的详情# 发现调度失败,提示node选择失败[root@master ~]# kubectl describe pod pod-nodeaffinity-required -n dev......  Warning  FailedScheduling  <unknown>  default-scheduler  0/3 nodes are available: 3 node(s) didn't match node selector.  Warning  FailedScheduling  <unknown>  default-scheduler  0/3 nodes are available: 3 node(s) didn't match node selector.#接下来,停止pod[root@master ~]# kubectl delete -f pod-nodeaffinity-required.yamlpod "pod-nodeaffinity-required" deleted# 修改文件,将values: ["xxx","yyy"]------> ["pro","yyy"][root@master ~]# vim pod-nodeaffinity-required.yaml# 再次启动[root@master ~]# kubectl create -f pod-nodeaffinity-required.yamlpod/pod-nodeaffinity-required created# 此时查看,发现调度成功,已经将pod调度到了node1上[root@master ~]# kubectl get pods pod-nodeaffinity-required -n dev -o wideNAME                        READY   STATUS    RESTARTS   AGE   IP            NODE  ...... pod-nodeaffinity-required   1/1     Running   0          11s   10.244.1.89   node1 ......</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <p>接下来再演示一下<code>requiredDuringSchedulingIgnoredDuringExecution</code> ,</p> 
    <p>创建pod-nodeaffinity-preferred.yaml</p> 
    <pre data-index="167" class="set-code-show prettyprint"><code class="prism language-yaml has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token key atrule">apiVersion</span><span class="token punctuation">:</span> <span class="token key atrule">v1kind</span><span class="token punctuation">:</span> <span class="token key atrule">Podmetadata</span><span class="token punctuation">:</span>  <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">pod-nodeaffinity-preferred  namespace</span><span class="token punctuation">:</span> <span class="token key atrule">devspec</span><span class="token punctuation">:</span>  <span class="token key atrule">containers</span><span class="token punctuation">:</span>  <span class="token punctuation">-</span> <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">nginx    image</span><span class="token punctuation">:</span> <span class="token key atrule">nginx:1.17.1  affinity</span><span class="token punctuation">:</span>  <span class="token comment">#亲和性设置    nodeAffinity: #设置node亲和性      preferredDuringSchedulingIgnoredDuringExecution: # 软限制      - weight: 1        preference:          matchExpressions: # 匹配env的值在["xxx","yyy"]中的标签(当前环境没有)          - key: nodeenv            operator: In            values: ["xxx","yyy"]</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <pre data-index="168" class="set-code-show prettyprint"><code class="prism language-powershell has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token comment"># 创建pod[root@master ~]# kubectl create -f pod-nodeaffinity-preferred.yamlpod/pod-nodeaffinity-preferred created# 查看pod状态 (运行成功)[root@master ~]# kubectl get pod pod-nodeaffinity-preferred -n devNAME                         READY   STATUS    RESTARTS   AGEpod-nodeaffinity-preferred   1/1     Running   0          40s</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <pre data-index="169" class="set-code-show prettyprint"><code class="prism language-markdown has-numbering" onclick="mdcp.signin(event)" style="position: unset;">NodeAffinity规则设置的注意事项:    1 如果同时定义了nodeSelector和nodeAffinity,那么必须两个条件都得到满足,Pod才能运行在指定的Node上    2 如果nodeAffinity指定了多个nodeSelectorTerms,那么只需要其中一个能够匹配成功即可    3 如果一个nodeSelectorTerms中有多个matchExpressions ,则一个节点必须满足所有的才能匹配成功    4 如果一个pod所在的Node在Pod运行期间其标签发生了改变,不再符合该Pod的节点亲和性需求,则系统将忽略此变化
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <p><strong>PodAffinity</strong></p> 
    <p>PodAffinity主要实现以运行的Pod为参照,实现让新创建的Pod跟参照pod在一个区域的功能。</p> 
    <p>首先来看一下<code>PodAffinity</code>的可配置项:</p> 
    <pre data-index="170" class="set-code-show prettyprint"><code class="prism language-markdown has-numbering" onclick="mdcp.signin(event)" style="position: unset;">pod.spec.affinity.podAffinity  requiredDuringSchedulingIgnoredDuringExecution  硬限制    namespaces       指定参照pod的namespace    topologyKey      指定调度作用域    labelSelector    标签选择器      matchExpressions  按节点标签列出的节点选择器要求列表(推荐)        key    键        values 值        operator 关系符 支持In, NotIn, Exists, DoesNotExist.      matchLabels    指多个matchExpressions映射的内容  preferredDuringSchedulingIgnoredDuringExecution 软限制    podAffinityTerm  选项      namespaces            topologyKey      labelSelector        matchExpressions            key    键          values 值          operator        matchLabels     weight 倾向权重,在范围1-100
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <pre data-index="171" class="set-code-show prettyprint"><code class="prism language-markdown has-numbering" onclick="mdcp.signin(event)" style="position: unset;">topologyKey用于指定调度时作用域,例如:    如果指定为kubernetes.io/hostname,那就是以Node节点为区分范围	如果指定为beta.kubernetes.io/os,则以Node节点的操作系统类型来区分
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <p>接下来,演示下<code>requiredDuringSchedulingIgnoredDuringExecution</code>,</p> 
    <p>1)首先创建一个参照Pod,pod-podaffinity-target.yaml:</p> 
    <pre data-index="172" class="set-code-show prettyprint"><code class="prism language-yaml has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token key atrule">apiVersion</span><span class="token punctuation">:</span> <span class="token key atrule">v1kind</span><span class="token punctuation">:</span> <span class="token key atrule">Podmetadata</span><span class="token punctuation">:</span>  <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">pod-podaffinity-target  namespace</span><span class="token punctuation">:</span> <span class="token key atrule">dev  labels</span><span class="token punctuation">:</span>    <span class="token key atrule">podenv</span><span class="token punctuation">:</span> pro <span class="token comment">#设置标签spec:  containers:  - name: nginx    image: nginx:1.17.1  nodeName: node1 # 将目标pod名确指定到node1上</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <pre data-index="173" class="set-code-show prettyprint"><code class="prism language-powershell has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token comment"># 启动目标pod[root@master ~]# kubectl create -f pod-podaffinity-target.yamlpod/pod-podaffinity-target created# 查看pod状况[root@master ~]# kubectl get pods  pod-podaffinity-target -n devNAME                     READY   STATUS    RESTARTS   AGEpod-podaffinity-target   1/1     Running   0          4s</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <p>2)创建pod-podaffinity-required.yaml,内容如下:</p> 
    <pre data-index="174" class="set-code-show prettyprint"><code class="prism language-yaml has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token key atrule">apiVersion</span><span class="token punctuation">:</span> <span class="token key atrule">v1kind</span><span class="token punctuation">:</span> <span class="token key atrule">Podmetadata</span><span class="token punctuation">:</span>  <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">pod-podaffinity-required  namespace</span><span class="token punctuation">:</span> <span class="token key atrule">devspec</span><span class="token punctuation">:</span>  <span class="token key atrule">containers</span><span class="token punctuation">:</span>  <span class="token punctuation">-</span> <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">nginx    image</span><span class="token punctuation">:</span> <span class="token key atrule">nginx:1.17.1  affinity</span><span class="token punctuation">:</span>  <span class="token comment">#亲和性设置    podAffinity: #设置pod亲和性      requiredDuringSchedulingIgnoredDuringExecution: # 硬限制      - labelSelector:          matchExpressions: # 匹配env的值在["xxx","yyy"]中的标签          - key: podenv            operator: In            values: ["xxx","yyy"]        topologyKey: kubernetes.io/hostname</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <p>上面配置表达的意思是:新Pod必须要与拥有标签nodeenv=xxx或者nodeenv=yyy的pod在同一Node上,显然现在没有这样pod,接下来,运行测试一下。</p> 
    <pre data-index="175" class="set-code-show prettyprint"><code class="prism language-powershell has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token comment"># 启动pod[root@master ~]# kubectl create -f pod-podaffinity-required.yamlpod/pod-podaffinity-required created# 查看pod状态,发现未运行[root@master ~]# kubectl get pods pod-podaffinity-required -n devNAME                       READY   STATUS    RESTARTS   AGEpod-podaffinity-required   0/1     Pending   0          9s# 查看详细信息[root@master ~]# kubectl describe pods pod-podaffinity-required  -n dev......Events:  Type     Reason            Age        From               Message  ----     ------            ----       ----               -------  Warning  FailedScheduling  <unknown>  default-scheduler  0/3 nodes are available: 2 node(s) didn't match pod affinity rules, 1 node(s) had taints that the pod didn't tolerate.# 接下来修改  values: ["xxx","yyy"]----->values:["pro","yyy"]# 意思是:新Pod必须要与拥有标签nodeenv=xxx或者nodeenv=yyy的pod在同一Node上[root@master ~]# vim pod-podaffinity-required.yaml# 然后重新创建pod,查看效果[root@master ~]# kubectl delete -f  pod-podaffinity-required.yamlpod "pod-podaffinity-required" deleted[root@master ~]# kubectl create -f pod-podaffinity-required.yamlpod/pod-podaffinity-required created# 发现此时Pod运行正常[root@master ~]# kubectl get pods pod-podaffinity-required -n devNAME                       READY   STATUS    RESTARTS   AGE   LABELSpod-podaffinity-required   1/1     Running   0          6s    <none></span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <p>关于<code>PodAffinity</code>的 <code>preferredDuringSchedulingIgnoredDuringExecution</code>,这里不再演示。</p> 
    <p><strong>PodAntiAffinity</strong></p> 
    <p>PodAntiAffinity主要实现以运行的Pod为参照,让新创建的Pod跟参照pod不在一个区域中的功能。</p> 
    <p>它的配置方式和选项跟PodAffinty是一样的,这里不再做详细解释,直接做一个测试案例。</p> 
    <p>1)继续使用上个案例中目标pod</p> 
    <pre data-index="176" class="set-code-show prettyprint"><code class="prism language-powershell has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token namespace">[root@master ~]</span><span class="token comment"># kubectl get pods -n dev -o wide --show-labelsNAME                     READY   STATUS    RESTARTS   AGE     IP            NODE    LABELSpod-podaffinity-required 1/1     Running   0          3m29s   10.244.1.38   node1   <none>     pod-podaffinity-target   1/1     Running   0          9m25s   10.244.1.37   node1   podenv=pro</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <p>2)创建pod-podantiaffinity-required.yaml,内容如下:</p> 
    <pre data-index="177" class="set-code-show prettyprint"><code class="prism language-yaml has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token key atrule">apiVersion</span><span class="token punctuation">:</span> <span class="token key atrule">v1kind</span><span class="token punctuation">:</span> <span class="token key atrule">Podmetadata</span><span class="token punctuation">:</span>  <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">pod-podantiaffinity-required  namespace</span><span class="token punctuation">:</span> <span class="token key atrule">devspec</span><span class="token punctuation">:</span>  <span class="token key atrule">containers</span><span class="token punctuation">:</span>  <span class="token punctuation">-</span> <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">nginx    image</span><span class="token punctuation">:</span> <span class="token key atrule">nginx:1.17.1  affinity</span><span class="token punctuation">:</span>  <span class="token comment">#亲和性设置    podAntiAffinity: #设置pod亲和性      requiredDuringSchedulingIgnoredDuringExecution: # 硬限制      - labelSelector:          matchExpressions: # 匹配podenv的值在["pro"]中的标签          - key: podenv            operator: In            values: ["pro"]        topologyKey: kubernetes.io/hostname</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <p>上面配置表达的意思是:新Pod必须要与拥有标签nodeenv=pro的pod不在同一Node上,运行测试一下。</p> 
    <pre data-index="178" class="set-code-show prettyprint"><code class="prism language-powershell has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token comment"># 创建pod[root@master ~]# kubectl create -f pod-podantiaffinity-required.yamlpod/pod-podantiaffinity-required created# 查看pod# 发现调度到了node2上[root@master ~]# kubectl get pods pod-podantiaffinity-required -n dev -o wideNAME                           READY   STATUS    RESTARTS   AGE   IP            NODE   .. pod-podantiaffinity-required   1/1     Running   0          30s   10.244.1.96   node2  ..</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <h4><a name="t74"></a><a id="_3085"></a>污点和容忍</h4> 
    <p><strong>污点(Taints)</strong></p> 
    <p>​ 前面的调度方式都是站在Pod的角度上,通过在Pod上添加属性,来确定Pod是否要调度到指定的Node上,其实我们也可以站在Node的角度上,通过在Node上添加<strong>污点</strong>属性,来决定是否允许Pod调度过来。</p> 
    <p>​ Node被设置上污点之后就和Pod之间存在了一种相斥的关系,进而拒绝Pod调度进来,甚至可以将已经存在的Pod驱逐出去。</p> 
    <p>污点的格式为:<code>key=value:effect</code>, key和value是污点的标签,effect描述污点的作用,支持如下三个选项:</p> 
    <ul><li>PreferNoSchedule:kubernetes将尽量避免把Pod调度到具有该污点的Node上,除非没有其他节点可调度</li><li>NoSchedule:kubernetes将不会把Pod调度到具有该污点的Node上,但不会影响当前Node上已存在的Pod</li><li>NoExecute:kubernetes将不会把Pod调度到具有该污点的Node上,同时也会将Node上已存在的Pod驱离</li></ul> 
    <img src="Kubernetes教程.assets/image-20200605021831545-16338582916265.png" alt="image-20200605021606508"> 
    <p>使用kubectl设置和去除污点的命令示例如下:</p> 
    <pre data-index="179" class="set-code-show prettyprint"><code class="prism language-powershell has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token comment"># 设置污点kubectl taint nodes node1 key=value:effect# 去除污点kubectl taint nodes node1 key:effect-# 去除所有污点kubectl taint nodes node1 key-</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <p>接下来,演示下污点的效果:</p> 
    <ol><li>准备节点node1(为了演示效果更加明显,暂时停止node2节点)</li><li>为node1节点设置一个污点: <code>tag=heima:PreferNoSchedule</code>;然后创建pod1( pod1 可以 )</li><li>修改为node1节点设置一个污点: <code>tag=heima:NoSchedule</code>;然后创建pod2( pod1 正常 pod2 失败 )</li><li>修改为node1节点设置一个污点: <code>tag=heima:NoExecute</code>;然后创建pod3 ( 3个pod都失败 )</li></ol> 
    <pre data-index="180" class="set-code-show prettyprint"><code class="prism language-powershell has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token comment"># 为node1设置污点(PreferNoSchedule)[root@master ~]# kubectl taint nodes node1 tag=heima:PreferNoSchedule# 创建pod1[root@master ~]# kubectl run taint1 --image=nginx:1.17.1 -n dev[root@master ~]# kubectl get pods -n dev -o wideNAME                      READY   STATUS    RESTARTS   AGE     IP           NODE   taint1-7665f7fd85-574h4   1/1     Running   0          2m24s   10.244.1.59   node1    # 为node1设置污点(取消PreferNoSchedule,设置NoSchedule)[root@master ~]# kubectl taint nodes node1 tag:PreferNoSchedule-[root@master ~]# kubectl taint nodes node1 tag=heima:NoSchedule# 创建pod2[root@master ~]# kubectl run taint2 --image=nginx:1.17.1 -n dev[root@master ~]# kubectl get pods taint2 -n dev -o wideNAME                      READY   STATUS    RESTARTS   AGE     IP            NODEtaint1-7665f7fd85-574h4   1/1     Running   0          2m24s   10.244.1.59   node1 taint2-544694789-6zmlf    0/1     Pending   0          21s     <none>        <none>   # 为node1设置污点(取消NoSchedule,设置NoExecute)[root@master ~]# kubectl taint nodes node1 tag:NoSchedule-[root@master ~]# kubectl taint nodes node1 tag=heima:NoExecute# 创建pod3[root@master ~]# kubectl run taint3 --image=nginx:1.17.1 -n dev[root@master ~]# kubectl get pods -n dev -o wideNAME                      READY   STATUS    RESTARTS   AGE   IP       NODE     NOMINATED taint1-7665f7fd85-htkmp   0/1     Pending   0          35s   <none>   <none>   <none>    taint2-544694789-bn7wb    0/1     Pending   0          35s   <none>   <none>   <none>     taint3-6d78dbd749-tktkq   0/1     Pending   0          6s    <none>   <none>   <none>     </span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <pre data-index="181" class="set-code-show prettyprint"><code class="prism language-markdown has-numbering" onclick="mdcp.signin(event)" style="position: unset;">小提示:    使用kubeadm搭建的集群,默认就会给master节点添加一个污点标记,所以pod就不会调度到master节点上.
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <p><strong>容忍(Toleration)</strong></p> 
    <p>​ 上面介绍了污点的作用,我们可以在node上添加污点用于拒绝pod调度上来,但是如果就是想将一个pod调度到一个有污点的node上去,这时候应该怎么做呢?这就要使用到<strong>容忍</strong>。</p> 
    <p>[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-kfb6cuJD-1669974966711)(Kubernetes教程.assets/image-20200514095913741-16338582916263.png)]</p> 
    <blockquote> 
     <p>污点就是拒绝,容忍就是忽略,Node通过污点拒绝pod调度上去,Pod通过容忍忽略拒绝</p> 
    </blockquote> 
    <p>下面先通过一个案例看下效果:</p> 
    <ol><li>上一小节,已经在node1节点上打上了<code>NoExecute</code>的污点,此时pod是调度不上去的</li><li>本小节,可以通过给pod添加容忍,然后将其调度上去</li></ol> 
    <p>创建pod-toleration.yaml,内容如下</p> 
    <pre data-index="182" class="set-code-show prettyprint"><code class="prism language-yaml has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token key atrule">apiVersion</span><span class="token punctuation">:</span> v1
    <span class="token key atrule">kind</span><span class="token punctuation">:</span> Pod
    <span class="token key atrule">metadata</span><span class="token punctuation">:</span>
      <span class="token key atrule">name</span><span class="token punctuation">:</span> pod<span class="token punctuation">-</span>toleration
      <span class="token key atrule">namespace</span><span class="token punctuation">:</span> dev
    <span class="token key atrule">spec</span><span class="token punctuation">:</span>
      <span class="token key atrule">containers</span><span class="token punctuation">:</span>
      <span class="token punctuation">-</span> <span class="token key atrule">name</span><span class="token punctuation">:</span> nginx
        <span class="token key atrule">image</span><span class="token punctuation">:</span> nginx<span class="token punctuation">:</span>1.17.1
      <span class="token key atrule">tolerations</span><span class="token punctuation">:</span>      <span class="token comment"># 添加容忍</span>
      <span class="token punctuation">-</span> <span class="token key atrule">key</span><span class="token punctuation">:</span> <span class="token string">"tag"</span>        <span class="token comment"># 要容忍的污点的key</span>
        <span class="token key atrule">operator</span><span class="token punctuation">:</span> <span class="token string">"Equal"</span> <span class="token comment"># 操作符</span>
        <span class="token key atrule">value</span><span class="token punctuation">:</span> <span class="token string">"heima"</span>    <span class="token comment"># 容忍的污点的value</span>
        <span class="token key atrule">effect</span><span class="token punctuation">:</span> <span class="token string">"NoExecute"</span>   <span class="token comment"># 添加容忍的规则,这里必须和标记的污点规则相同</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li><li style="color: rgb(153, 153, 153);">2</li><li style="color: rgb(153, 153, 153);">3</li><li style="color: rgb(153, 153, 153);">4</li><li style="color: rgb(153, 153, 153);">5</li><li style="color: rgb(153, 153, 153);">6</li><li style="color: rgb(153, 153, 153);">7</li><li style="color: rgb(153, 153, 153);">8</li><li style="color: rgb(153, 153, 153);">9</li><li style="color: rgb(153, 153, 153);">10</li><li style="color: rgb(153, 153, 153);">11</li><li style="color: rgb(153, 153, 153);">12</li><li style="color: rgb(153, 153, 153);">13</li><li style="color: rgb(153, 153, 153);">14</li></ul></pre> 
    <pre data-index="183" class="set-code-show prettyprint"><code class="prism language-powershell has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token comment"># 添加容忍之前的pod</span>
    <span class="token namespace">[root@master ~]</span><span class="token comment"># kubectl get pods -n dev -o wide</span>
    NAME             READY   STATUS    RESTARTS   AGE   IP       NODE     NOMINATED 
    pod-toleration   0/1     Pending   0          3s    <none>   <none>   <none>           
    
    <span class="token comment"># 添加容忍之后的pod</span>
    <span class="token namespace">[root@master ~]</span><span class="token comment"># kubectl get pods -n dev -o wide</span>
    NAME             READY   STATUS    RESTARTS   AGE   IP            NODE    NOMINATED
    pod-toleration   1/1     Running   0          3s    10<span class="token punctuation">.</span>244<span class="token punctuation">.</span>1<span class="token punctuation">.</span>62   node1   <none>        
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li><li style="color: rgb(153, 153, 153);">2</li><li style="color: rgb(153, 153, 153);">3</li><li style="color: rgb(153, 153, 153);">4</li><li style="color: rgb(153, 153, 153);">5</li><li style="color: rgb(153, 153, 153);">6</li><li style="color: rgb(153, 153, 153);">7</li><li style="color: rgb(153, 153, 153);">8</li><li style="color: rgb(153, 153, 153);">9</li></ul></pre> 
    <p>下面看一下容忍的详细配置:</p> 
    <pre data-index="184" class="set-code-show prettyprint"><code class="prism language-powershell has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token namespace">[root@master ~]</span><span class="token comment"># kubectl explain pod.spec.tolerations</span>
    <span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span>
    FIELDS:
       key       <span class="token comment"># 对应着要容忍的污点的键,空意味着匹配所有的键</span>
       value     <span class="token comment"># 对应着要容忍的污点的值</span>
       operator  <span class="token comment"># key-value的运算符,支持Equal和Exists(默认)</span>
       effect    <span class="token comment"># 对应污点的effect,空意味着匹配所有影响</span>
       tolerationSeconds   <span class="token comment"># 容忍时间, 当effect为NoExecute时生效,表示pod在Node上的停留时间</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li><li style="color: rgb(153, 153, 153);">2</li><li style="color: rgb(153, 153, 153);">3</li><li style="color: rgb(153, 153, 153);">4</li><li style="color: rgb(153, 153, 153);">5</li><li style="color: rgb(153, 153, 153);">6</li><li style="color: rgb(153, 153, 153);">7</li><li style="color: rgb(153, 153, 153);">8</li></ul></pre> 
    <h2><a name="t75"></a><a id="_Pod_3179"></a>第六章 Pod控制器详解</h2> 
    <p>本章节主要介绍各种Pod控制器的详细使用。</p> 
    <h3><a name="t76"></a><a id="Pod_3183"></a>Pod控制器介绍</h3> 
    <p>Pod是kubernetes的最小管理单元,在kubernetes中,按照pod的创建方式可以将其分为两类:</p> 
    <ul><li> <p>自主式pod:kubernetes直接创建出来的Pod,这种pod删除后就没有了,也不会重建</p> </li><li> <p>控制器创建的pod:kubernetes通过控制器创建的pod,这种pod删除了之后还会自动重建</p> </li></ul> 
    <blockquote> 
     <p><strong><code>什么是Pod控制器</code></strong></p> 
     <p>​ Pod控制器是管理pod的中间层,使用Pod控制器之后,只需要告诉Pod控制器,想要多少个什么样的Pod就可以了,它会创建出满足条件的Pod并确保每一个Pod资源处于用户期望的目标状态。如果Pod资源在运行中出现故障,它会基于指定策略重新编排Pod。</p> 
    </blockquote> 
    <p>在kubernetes中,有很多类型的pod控制器,每种都有自己的适合的场景,常见的有下面这些:</p> 
    <ul><li> <p>ReplicationController:比较原始的pod控制器,已经被废弃,由ReplicaSet替代</p> </li><li> <p>ReplicaSet:保证副本数量一直维持在期望值,并支持pod数量扩缩容,镜像版本升级</p> </li><li> <p>Deployment:通过控制ReplicaSet来控制Pod,并支持滚动升级、回退版本</p> </li><li> <p>Horizontal Pod Autoscaler:可以根据集群负载自动水平调整Pod的数量,实现削峰填谷</p> </li><li> <p>DaemonSet:在集群中的指定Node上运行且仅运行一个副本,一般用于守护进程类的任务</p> </li><li> <p>Job:它创建出来的pod只要完成任务就立即退出,不需要重启或重建,用于执行一次性任务</p> </li><li> <p>Cronjob:它创建的Pod负责周期性任务控制,不需要持续后台运行</p> </li><li> <p>StatefulSet:管理有状态应用</p> </li></ul> 
    <h3><a name="t77"></a><a id="ReplicaSetRS_3213"></a>ReplicaSet(RS)</h3> 
    <p>​ ReplicaSet的主要作用是<strong>保证一定数量的pod正常运行</strong>,它会持续监听这些Pod的运行状态,一旦Pod发生故障,就会重启或重建。同时它还支持对pod数量的扩缩容和镜像版本的升降级。</p> 
    <p><img src="https://1000bd.com/contentImg/2022/08/09/102147799.png" alt=""></p> 
    <p>ReplicaSet的资源清单文件:</p> 
    <pre data-index="185" class="set-code-show prettyprint"><code class="prism language-yaml has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token key atrule">apiVersion</span><span class="token punctuation">:</span> apps/v1 <span class="token comment"># 版本号kind: ReplicaSet # 类型       metadata: # 元数据  name: # rs名称   namespace: # 所属命名空间   labels: #标签    controller: rsspec: # 详情描述  replicas: 3 # 副本数量  selector: # 选择器,通过它指定该控制器管理哪些pod    matchLabels:      # Labels匹配规则      app: nginx-pod    matchExpressions: # Expressions匹配规则      - {key: app, operator: In, values: [nginx-pod]}  template: # 模板,当副本数量不足时,会根据下面的模板创建pod副本    metadata:      labels:        app: nginx-pod    spec:      containers:      - name: nginx        image: nginx:1.17.1        ports:        - containerPort: 80</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <p>在这里面,需要新了解的配置项就是<code>spec</code>下面几个选项:</p> 
    <ul><li> <p>replicas:指定副本数量,其实就是当前rs创建出来的pod的数量,默认为1</p> </li><li> <p>selector:选择器,它的作用是建立pod控制器和pod之间的关联关系,采用的Label Selector机制</p> <p>​ 在pod模板上定义label,在控制器上定义选择器,就可以表明当前控制器能管理哪些pod了</p> </li><li> <p>template:模板,就是当前控制器创建pod所使用的模板板,里面其实就是前一章学过的pod的定义</p> </li></ul> 
    <p><strong>创建ReplicaSet</strong></p> 
    <p>创建pc-replicaset.yaml文件,内容如下:</p> 
    <pre data-index="186" class="set-code-show prettyprint"><code class="prism language-yaml has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token key atrule">apiVersion</span><span class="token punctuation">:</span> <span class="token key atrule">apps/v1kind</span><span class="token punctuation">:</span> <span class="token key atrule">ReplicaSet   metadata</span><span class="token punctuation">:</span>  <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">pc-replicaset  namespace</span><span class="token punctuation">:</span> <span class="token key atrule">devspec</span><span class="token punctuation">:</span>  <span class="token key atrule">replicas</span><span class="token punctuation">:</span> <span class="token key atrule">3  selector</span><span class="token punctuation">:</span>     <span class="token key atrule">matchLabels</span><span class="token punctuation">:</span>      <span class="token key atrule">app</span><span class="token punctuation">:</span> <span class="token key atrule">nginx-pod  template</span><span class="token punctuation">:</span>    <span class="token key atrule">metadata</span><span class="token punctuation">:</span>      <span class="token key atrule">labels</span><span class="token punctuation">:</span>        <span class="token key atrule">app</span><span class="token punctuation">:</span> <span class="token key atrule">nginx-pod    spec</span><span class="token punctuation">:</span>      <span class="token key atrule">containers</span><span class="token punctuation">:</span>      <span class="token punctuation">-</span> <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">nginx        image</span><span class="token punctuation">:</span> nginx<span class="token punctuation">:</span>1.17.1
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <pre data-index="187" class="set-code-show prettyprint"><code class="prism language-powershell has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token comment"># 创建rs[root@master ~]# kubectl create -f pc-replicaset.yamlreplicaset.apps/pc-replicaset created# 查看rs# DESIRED:期望副本数量  # CURRENT:当前副本数量  # READY:已经准备好提供服务的副本数量[root@master ~]# kubectl get rs pc-replicaset -n dev -o wideNAME          DESIRED   CURRENT READY AGE   CONTAINERS   IMAGES             SELECTORpc-replicaset 3         3       3     22s   nginx        nginx:1.17.1       app=nginx-pod# 查看当前控制器创建出来的pod# 这里发现控制器创建出来的pod的名称是在控制器名称后面拼接了-xxxxx随机码[root@master ~]# kubectl get pod -n devNAME                          READY   STATUS    RESTARTS   AGEpc-replicaset-6vmvt   1/1     Running   0          54spc-replicaset-fmb8f   1/1     Running   0          54spc-replicaset-snrk2   1/1     Running   0          54s</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <p><strong>扩缩容</strong></p> 
    <pre data-index="188" class="set-code-show prettyprint"><code class="prism language-powershell has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token comment"># 编辑rs的副本数量,修改spec:replicas: 6即可[root@master ~]# kubectl edit rs pc-replicaset -n devreplicaset.apps/pc-replicaset edited# 查看pod[root@master ~]# kubectl get pods -n devNAME                          READY   STATUS    RESTARTS   AGEpc-replicaset-6vmvt   1/1     Running   0          114mpc-replicaset-cftnp   1/1     Running   0          10spc-replicaset-fjlm6   1/1     Running   0          10spc-replicaset-fmb8f   1/1     Running   0          114mpc-replicaset-s2whj   1/1     Running   0          10spc-replicaset-snrk2   1/1     Running   0          114m# 当然也可以直接使用命令实现# 使用scale命令实现扩缩容, 后面--replicas=n直接指定目标数量即可[root@master ~]# kubectl scale rs pc-replicaset --replicas=2 -n devreplicaset.apps/pc-replicaset scaled# 命令运行完毕,立即查看,发现已经有4个开始准备退出了[root@master ~]# kubectl get pods -n devNAME                       READY   STATUS        RESTARTS   AGEpc-replicaset-6vmvt   0/1     Terminating   0          118mpc-replicaset-cftnp   0/1     Terminating   0          4m17spc-replicaset-fjlm6   0/1     Terminating   0          4m17spc-replicaset-fmb8f   1/1     Running       0          118mpc-replicaset-s2whj   0/1     Terminating   0          4m17spc-replicaset-snrk2   1/1     Running       0          118m#稍等片刻,就只剩下2个了[root@master ~]# kubectl get pods -n devNAME                       READY   STATUS    RESTARTS   AGEpc-replicaset-fmb8f   1/1     Running   0          119mpc-replicaset-snrk2   1/1     Running   0          119m</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <p><strong>镜像升级</strong></p> 
    <pre data-index="189" class="set-code-show prettyprint"><code class="prism language-powershell has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token comment"># 编辑rs的容器镜像 - image: nginx:1.17.2[root@master ~]# kubectl edit rs pc-replicaset -n devreplicaset.apps/pc-replicaset edited# 再次查看,发现镜像版本已经变更了[root@master ~]# kubectl get rs -n dev -o wideNAME                DESIRED  CURRENT   READY   AGE    CONTAINERS   IMAGES        ...pc-replicaset       2        2         2       140m   nginx         nginx:1.17.2  ...# 同样的道理,也可以使用命令完成这个工作# kubectl set image rs rs名称 容器=镜像版本 -n namespace[root@master ~]# kubectl set image rs pc-replicaset nginx=nginx:1.17.1  -n devreplicaset.apps/pc-replicaset image updated# 再次查看,发现镜像版本已经变更了[root@master ~]# kubectl get rs -n dev -o wideNAME                 DESIRED  CURRENT   READY   AGE    CONTAINERS   IMAGES            ...pc-replicaset        2        2         2       145m   nginx        nginx:1.17.1 ... </span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <p><strong>删除ReplicaSet</strong></p> 
    <pre data-index="190" class="set-code-show prettyprint"><code class="prism language-powershell has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token comment"># 使用kubectl delete命令会删除此RS以及它管理的Pod# 在kubernetes删除RS前,会将RS的replicasclear调整为0,等待所有的Pod被删除后,在执行RS对象的删除[root@master ~]# kubectl delete rs pc-replicaset -n devreplicaset.apps "pc-replicaset" deleted[root@master ~]# kubectl get pod -n dev -o wideNo resources found in dev namespace.# 如果希望仅仅删除RS对象(保留Pod),可以使用kubectl delete命令时添加--cascade=false选项(不推荐)。[root@master ~]# kubectl delete rs pc-replicaset -n dev --cascade=falsereplicaset.apps "pc-replicaset" deleted[root@master ~]# kubectl get pods -n devNAME                  READY   STATUS    RESTARTS   AGEpc-replicaset-cl82j   1/1     Running   0          75spc-replicaset-dslhb   1/1     Running   0          75s# 也可以使用yaml直接删除(推荐)[root@master ~]# kubectl delete -f pc-replicaset.yamlreplicaset.apps "pc-replicaset" deleted</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <h3><a name="t78"></a><a id="DeploymentDeploy_3265"></a>Deployment(Deploy)</h3> 
    <p>​ 为了更好的解决服务编排的问题,kubernetes在V1.2版本开始,引入了Deployment控制器。值得一提的是,这种控制器并不直接管理pod,而是通过管理ReplicaSet来简介管理Pod,即:Deployment管理ReplicaSet,ReplicaSet管理Pod。所以Deployment比ReplicaSet功能更加强大。</p> 
    <p><img src="https://1000bd.com/contentImg/2024/04/15/90e3005a695c4a19.png" alt=""></p> 
    <p>Deployment主要功能有下面几个:</p> 
    <ul><li>支持ReplicaSet的所有功能</li><li>支持发布的停止、继续</li><li>支持滚动升级和回滚版本</li></ul> 
    <p>Deployment的资源清单文件:</p> 
    <pre data-index="191" class="set-code-show prettyprint"><code class="prism language-yaml has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token key atrule">apiVersion</span><span class="token punctuation">:</span> apps/v1 <span class="token comment"># 版本号kind: Deployment # 类型       metadata: # 元数据  name: # rs名称   namespace: # 所属命名空间   labels: #标签    controller: deployspec: # 详情描述  replicas: 3 # 副本数量  revisionHistoryLimit: 3 # 保留历史版本  paused: false # 暂停部署,默认是false  progressDeadlineSeconds: 600 # 部署超时时间(s),默认是600  strategy: # 策略    type: RollingUpdate # 滚动更新策略    rollingUpdate: # 滚动更新      maxSurge: 30% # 最大额外可以存在的副本数,可以为百分比,也可以为整数      maxUnavailable: 30% # 最大不可用状态的 Pod 的最大值,可以为百分比,也可以为整数  selector: # 选择器,通过它指定该控制器管理哪些pod    matchLabels:      # Labels匹配规则      app: nginx-pod    matchExpressions: # Expressions匹配规则      - {key: app, operator: In, values: [nginx-pod]}  template: # 模板,当副本数量不足时,会根据下面的模板创建pod副本    metadata:      labels:        app: nginx-pod    spec:      containers:      - name: nginx        image: nginx:1.17.1        ports:        - containerPort: 80</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <p><strong>创建deployment</strong></p> 
    <p>创建pc-deployment.yaml,内容如下:</p> 
    <pre data-index="192" class="set-code-show prettyprint"><code class="prism language-yaml has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token key atrule">apiVersion</span><span class="token punctuation">:</span> <span class="token key atrule">apps/v1kind</span><span class="token punctuation">:</span> <span class="token key atrule">Deployment      metadata</span><span class="token punctuation">:</span>  <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">pc-deployment  namespace</span><span class="token punctuation">:</span> <span class="token key atrule">devspec</span><span class="token punctuation">:</span>   <span class="token key atrule">replicas</span><span class="token punctuation">:</span> <span class="token key atrule">3  selector</span><span class="token punctuation">:</span>    <span class="token key atrule">matchLabels</span><span class="token punctuation">:</span>      <span class="token key atrule">app</span><span class="token punctuation">:</span> <span class="token key atrule">nginx-pod  template</span><span class="token punctuation">:</span>    <span class="token key atrule">metadata</span><span class="token punctuation">:</span>      <span class="token key atrule">labels</span><span class="token punctuation">:</span>        <span class="token key atrule">app</span><span class="token punctuation">:</span> <span class="token key atrule">nginx-pod    spec</span><span class="token punctuation">:</span>      <span class="token key atrule">containers</span><span class="token punctuation">:</span>      <span class="token punctuation">-</span> <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">nginx        image</span><span class="token punctuation">:</span> nginx<span class="token punctuation">:</span>1.17.1
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <pre data-index="193" class="set-code-show prettyprint"><code class="prism language-powershell has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token comment"># 创建deployment[root@master ~]# kubectl create -f pc-deployment.yaml --record=truedeployment.apps/pc-deployment created# 查看deployment# UP-TO-DATE 最新版本的pod的数量# AVAILABLE  当前可用的pod的数量[root@master ~]# kubectl get deploy pc-deployment -n devNAME            READY   UP-TO-DATE   AVAILABLE   AGEpc-deployment   3/3     3            3           15s# 查看rs# 发现rs的名称是在原来deployment的名字后面添加了一个10位数的随机串[root@master ~]# kubectl get rs -n devNAME                       DESIRED   CURRENT   READY   AGEpc-deployment-6696798b78   3         3         3       23s# 查看pod[root@master ~]# kubectl get pods -n devNAME                             READY   STATUS    RESTARTS   AGEpc-deployment-6696798b78-d2c8n   1/1     Running   0          107spc-deployment-6696798b78-smpvp   1/1     Running   0          107spc-deployment-6696798b78-wvjd8   1/1     Running   0          107s</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <p><strong>扩缩容</strong></p> 
    <pre data-index="194" class="set-code-show prettyprint"><code class="prism language-powershell has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token comment"># 变更副本数量为5个[root@master ~]# kubectl scale deploy pc-deployment --replicas=5  -n devdeployment.apps/pc-deployment scaled# 查看deployment[root@master ~]# kubectl get deploy pc-deployment -n devNAME            READY   UP-TO-DATE   AVAILABLE   AGEpc-deployment   5/5     5            5           2m# 查看pod[root@master ~]#  kubectl get pods -n devNAME                             READY   STATUS    RESTARTS   AGEpc-deployment-6696798b78-d2c8n   1/1     Running   0          4m19spc-deployment-6696798b78-jxmdq   1/1     Running   0          94spc-deployment-6696798b78-mktqv   1/1     Running   0          93spc-deployment-6696798b78-smpvp   1/1     Running   0          4m19spc-deployment-6696798b78-wvjd8   1/1     Running   0          4m19s# 编辑deployment的副本数量,修改spec:replicas: 4即可[root@master ~]# kubectl edit deploy pc-deployment -n devdeployment.apps/pc-deployment edited# 查看pod[root@master ~]# kubectl get pods -n devNAME                             READY   STATUS    RESTARTS   AGEpc-deployment-6696798b78-d2c8n   1/1     Running   0          5m23spc-deployment-6696798b78-jxmdq   1/1     Running   0          2m38spc-deployment-6696798b78-smpvp   1/1     Running   0          5m23spc-deployment-6696798b78-wvjd8   1/1     Running   0          5m23s</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <p><strong>镜像更新</strong></p> 
    <p>deployment支持两种更新策略:<code>重建更新</code>和<code>滚动更新</code>,可以通过<code>strategy</code>指定策略类型,支持两个属性:</p> 
    <pre data-index="195" class="set-code-show prettyprint"><code class="prism language-markdown has-numbering" onclick="mdcp.signin(event)" style="position: unset;">strategy:指定新的Pod替换旧的Pod的策略, 支持两个属性:  type:指定策略类型,支持两种策略    Recreate:在创建出新的Pod之前会先杀掉所有已存在的Pod    RollingUpdate:滚动更新,就是杀死一部分,就启动一部分,在更新过程中,存在两个版本Pod  rollingUpdate:当type为RollingUpdate时生效,用于为RollingUpdate设置参数,支持两个属性:    maxUnavailable:用来指定在升级过程中不可用Pod的最大数量,默认为25%。    maxSurge: 用来指定在升级过程中可以超过期望的Pod的最大数量,默认为25%。
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <p>重建更新</p> 
    <ol><li>编辑pc-deployment.yaml,在spec节点下添加更新策略</li></ol> 
    <pre data-index="196" class="set-code-show prettyprint"><code class="prism language-yaml has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token key atrule">spec</span><span class="token punctuation">:</span>  <span class="token key atrule">strategy</span><span class="token punctuation">:</span> <span class="token comment"># 策略    type: Recreate # 重建更新</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <ol start="2"><li>创建deploy进行验证</li></ol> 
    <pre data-index="197" class="set-code-show prettyprint"><code class="prism language-powershell has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token comment"># 变更镜像[root@master ~]# kubectl set image deployment pc-deployment nginx=nginx:1.17.2 -n devdeployment.apps/pc-deployment image updated# 观察升级过程[root@master ~]#  kubectl get pods -n dev -wNAME                             READY   STATUS    RESTARTS   AGEpc-deployment-5d89bdfbf9-65qcw   1/1     Running   0          31spc-deployment-5d89bdfbf9-w5nzv   1/1     Running   0          31spc-deployment-5d89bdfbf9-xpt7w   1/1     Running   0          31spc-deployment-5d89bdfbf9-xpt7w   1/1     Terminating   0          41spc-deployment-5d89bdfbf9-65qcw   1/1     Terminating   0          41spc-deployment-5d89bdfbf9-w5nzv   1/1     Terminating   0          41spc-deployment-675d469f8b-grn8z   0/1     Pending       0          0spc-deployment-675d469f8b-hbl4v   0/1     Pending       0          0spc-deployment-675d469f8b-67nz2   0/1     Pending       0          0spc-deployment-675d469f8b-grn8z   0/1     ContainerCreating   0          0spc-deployment-675d469f8b-hbl4v   0/1     ContainerCreating   0          0spc-deployment-675d469f8b-67nz2   0/1     ContainerCreating   0          0spc-deployment-675d469f8b-grn8z   1/1     Running             0          1spc-deployment-675d469f8b-67nz2   1/1     Running             0          1spc-deployment-675d469f8b-hbl4v   1/1     Running             0          2s</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <p>滚动更新</p> 
    <ol><li>编辑pc-deployment.yaml,在spec节点下添加更新策略</li></ol> 
    <pre data-index="198" class="set-code-show prettyprint"><code class="prism language-yaml has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token key atrule">spec</span><span class="token punctuation">:</span>  <span class="token key atrule">strategy</span><span class="token punctuation">:</span> <span class="token comment"># 策略    type: RollingUpdate # 滚动更新策略    rollingUpdate:      maxSurge: 25%       maxUnavailable: 25%</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <ol start="2"><li>创建deploy进行验证</li></ol> 
    <pre data-index="199" class="set-code-show prettyprint"><code class="prism language-powershell has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token comment"># 变更镜像[root@master ~]# kubectl set image deployment pc-deployment nginx=nginx:1.17.3 -n devdeployment.apps/pc-deployment image updated# 观察升级过程[root@master ~]# kubectl get pods -n dev -wNAME                           READY   STATUS    RESTARTS   AGEpc-deployment-c848d767-8rbzt   1/1     Running   0          31mpc-deployment-c848d767-h4p68   1/1     Running   0          31mpc-deployment-c848d767-hlmz4   1/1     Running   0          31mpc-deployment-c848d767-rrqcn   1/1     Running   0          31mpc-deployment-966bf7f44-226rx   0/1     Pending             0          0spc-deployment-966bf7f44-226rx   0/1     ContainerCreating   0          0spc-deployment-966bf7f44-226rx   1/1     Running             0          1spc-deployment-c848d767-h4p68    0/1     Terminating         0          34mpc-deployment-966bf7f44-cnd44   0/1     Pending             0          0spc-deployment-966bf7f44-cnd44   0/1     ContainerCreating   0          0spc-deployment-966bf7f44-cnd44   1/1     Running             0          2spc-deployment-c848d767-hlmz4    0/1     Terminating         0          34mpc-deployment-966bf7f44-px48p   0/1     Pending             0          0spc-deployment-966bf7f44-px48p   0/1     ContainerCreating   0          0spc-deployment-966bf7f44-px48p   1/1     Running             0          0spc-deployment-c848d767-8rbzt    0/1     Terminating         0          34mpc-deployment-966bf7f44-dkmqp   0/1     Pending             0          0spc-deployment-966bf7f44-dkmqp   0/1     ContainerCreating   0          0spc-deployment-966bf7f44-dkmqp   1/1     Running             0          2spc-deployment-c848d767-rrqcn    0/1     Terminating         0          34m# 至此,新版本的pod创建完毕,就版本的pod销毁完毕# 中间过程是滚动进行的,也就是边销毁边创建</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <p>滚动更新的过程:</p> 
    <img src="https://1000bd.com/contentImg/2024/04/15/2800406980231130.png"> 
    <p>镜像更新中rs的变化:</p> 
    <pre data-index="200" class="set-code-show prettyprint"><code class="prism language-powershell has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token comment"># 查看rs,发现原来的rs的依旧存在,只是pod数量变为了0,而后又新产生了一个rs,pod数量为4# 其实这就是deployment能够进行版本回退的奥妙所在,后面会详细解释[root@master ~]# kubectl get rs -n devNAME                       DESIRED   CURRENT   READY   AGEpc-deployment-6696798b78   0         0         0       7m37spc-deployment-6696798b11   0         0         0       5m37spc-deployment-c848d76789   4         4         4       72s</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <p><strong>版本回退</strong></p> 
    <p>deployment支持版本升级过程中的暂停、继续功能以及版本回退等诸多功能,下面具体来看.</p> 
    <p>kubectl rollout: 版本升级相关功能,支持下面的选项:</p> 
    <ul><li> <p>status 显示当前升级状态</p> </li><li> <p>history 显示 升级历史记录</p> </li><li> <p>pause 暂停版本升级过程</p> </li><li> <p>resume 继续已经暂停的版本升级过程</p> </li><li> <p>restart 重启版本升级过程</p> </li><li> <p>undo 回滚到上一级版本(可以使用–to-revision回滚到指定版本)</p> </li></ul> 
    <pre data-index="201" class="set-code-show prettyprint"><code class="prism language-powershell has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token comment"># 查看当前升级版本的状态[root@master ~]# kubectl rollout status deploy pc-deployment -n devdeployment "pc-deployment" successfully rolled out# 查看升级历史记录[root@master ~]# kubectl rollout history deploy pc-deployment -n devdeployment.apps/pc-deploymentREVISION  CHANGE-CAUSE1         kubectl create --filename=pc-deployment.yaml --record=true2         kubectl create --filename=pc-deployment.yaml --record=true3         kubectl create --filename=pc-deployment.yaml --record=true# 可以发现有三次版本记录,说明完成过两次升级# 版本回滚# 这里直接使用--to-revision=1回滚到了1版本, 如果省略这个选项,就是回退到上个版本,就是2版本[root@master ~]# kubectl rollout undo deployment pc-deployment --to-revision=1 -n devdeployment.apps/pc-deployment rolled back# 查看发现,通过nginx镜像版本可以发现到了第一版[root@master ~]# kubectl get deploy -n dev -o wideNAME            READY   UP-TO-DATE   AVAILABLE   AGE   CONTAINERS   IMAGES         pc-deployment   4/4     4            4           74m   nginx        nginx:1.17.1   # 查看rs,发现第一个rs中有4个pod运行,后面两个版本的rs中pod为运行# 其实deployment之所以可是实现版本的回滚,就是通过记录下历史rs来实现的,# 一旦想回滚到哪个版本,只需要将当前版本pod数量降为0,然后将回滚版本的pod提升为目标数量就可以了[root@master ~]# kubectl get rs -n devNAME                       DESIRED   CURRENT   READY   AGEpc-deployment-6696798b78   4         4         4       78mpc-deployment-966bf7f44    0         0         0       37mpc-deployment-c848d767     0         0         0       71m</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <p><strong>金丝雀发布</strong></p> 
    <p>​ Deployment控制器支持控制更新过程中的控制,如“暂停(pause)”或“继续(resume)”更新操作。</p> 
    <p>​ 比如有一批新的Pod资源创建完成后立即暂停更新过程,此时,仅存在一部分新版本的应用,主体部分还是旧的版本。然后,再筛选一小部分的用户请求路由到新版本的Pod应用,继续观察能否稳定地按期望的方式运行。确定没问题之后再继续完成余下的Pod资源滚动更新,否则立即回滚更新操作。这就是所谓的金丝雀发布。</p> 
    <pre data-index="202" class="set-code-show prettyprint"><code class="prism language-powershell has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token comment"># 更新deployment的版本,并配置暂停deployment[root@master ~]#  kubectl set image deploy pc-deployment nginx=nginx:1.17.4 -n dev && kubectl rollout pause deployment pc-deployment  -n devdeployment.apps/pc-deployment image updateddeployment.apps/pc-deployment paused#观察更新状态[root@master ~]# kubectl rollout status deploy pc-deployment -n dev Waiting for deployment "pc-deployment" rollout to finish: 2 out of 4 new replicas have been updated...# 监控更新的过程,可以看到已经新增了一个资源,但是并未按照预期的状态去删除一个旧的资源,就是因为使用了pause暂停命令[root@master ~]# kubectl get rs -n dev -o wideNAME                       DESIRED   CURRENT   READY   AGE     CONTAINERS   IMAGES         pc-deployment-5d89bdfbf9   3         3         3       19m     nginx        nginx:1.17.1   pc-deployment-675d469f8b   0         0         0       14m     nginx        nginx:1.17.2   pc-deployment-6c9f56fcfb   2         2         2       3m16s   nginx        nginx:1.17.4   [root@master ~]# kubectl get pods -n devNAME                             READY   STATUS    RESTARTS   AGEpc-deployment-5d89bdfbf9-rj8sq   1/1     Running   0          7m33spc-deployment-5d89bdfbf9-ttwgg   1/1     Running   0          7m35spc-deployment-5d89bdfbf9-v4wvc   1/1     Running   0          7m34spc-deployment-6c9f56fcfb-996rt   1/1     Running   0          3m31spc-deployment-6c9f56fcfb-j2gtj   1/1     Running   0          3m31s# 确保更新的pod没问题了,继续更新[root@master ~]# kubectl rollout resume deploy pc-deployment -n devdeployment.apps/pc-deployment resumed# 查看最后的更新情况[root@master ~]# kubectl get rs -n dev -o wideNAME                       DESIRED   CURRENT   READY   AGE     CONTAINERS   IMAGES         pc-deployment-5d89bdfbf9   0         0         0       21m     nginx        nginx:1.17.1   pc-deployment-675d469f8b   0         0         0       16m     nginx        nginx:1.17.2   pc-deployment-6c9f56fcfb   4         4         4       5m11s   nginx        nginx:1.17.4   [root@master ~]# kubectl get pods -n devNAME                             READY   STATUS    RESTARTS   AGEpc-deployment-6c9f56fcfb-7bfwh   1/1     Running   0          37spc-deployment-6c9f56fcfb-996rt   1/1     Running   0          5m27spc-deployment-6c9f56fcfb-j2gtj   1/1     Running   0          5m27spc-deployment-6c9f56fcfb-rf84v   1/1     Running   0          37s</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <p><strong>删除Deployment</strong></p> 
    <pre data-index="203" class="set-code-show prettyprint"><code class="prism language-powershell has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token comment"># 删除deployment,其下的rs和pod也将被删除[root@master ~]# kubectl delete -f pc-deployment.yamldeployment.apps "pc-deployment" deleted</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <h3><a name="t79"></a><a id="Horizontal_Pod_AutoscalerHPA_3381"></a>Horizontal Pod Autoscaler(HPA)</h3> 
    <p>​ 在前面的课程中,我们已经可以实现通过手工执行<code>kubectl scale</code>命令实现Pod扩容或缩容,但是这显然不符合Kubernetes的定位目标–自动化、智能化。 Kubernetes期望可以实现通过监测Pod的使用情况,实现pod数量的自动调整,于是就产生了Horizontal Pod Autoscaler(HPA)这种控制器。</p> 
    <p>​ HPA可以获取每个Pod利用率,然后和HPA中定义的指标进行对比,同时计算出需要伸缩的具体值,最后实现Pod的数量的调整。其实HPA与之前的Deployment一样,也属于一种Kubernetes资源对象,它通过追踪分析RC控制的所有目标Pod的负载变化情况,来确定是否需要针对性地调整目标Pod的副本数,这是HPA的实现原理。</p> 
    <img src="https://1000bd.com/contentImg/2024/04/15/72447cb1c45138e6.png"> 
    <p>接下来,我们来做一个实验</p> 
    <p><strong>1 安装metrics-server</strong></p> 
    <p>metrics-server可以用来收集集群中的资源使用情况</p> 
    <pre data-index="204" class="set-code-show prettyprint"><code class="prism language-powershell has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token comment"># 安装git[root@master ~]# yum install git -y# 获取metrics-server, 注意使用的版本[root@master ~]# git clone -b v0.3.6 https://github.com/kubernetes-incubator/metrics-server# 修改deployment, 注意修改的是镜像和初始化参数[root@master ~]# cd /root/metrics-server/deploy/1.8+/[root@master 1.8+]# vim metrics-server-deployment.yaml按图中添加下面选项hostNetwork: trueimage: registry.cn-hangzhou.aliyuncs.com/google_containers/metrics-server-amd64:v0.3.6args:- --kubelet-insecure-tls- --kubelet-preferred-address-types=InternalIP,Hostname,InternalDNS,ExternalDNS,ExternalIP</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <p><img src="https://1000bd.com/contentImg/2024/04/15/d0496ea58c1a6bff.png" alt="image-20200608163326496"></p> 
    <pre data-index="205" class="set-code-show prettyprint"><code class="prism language-powershell has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token comment"># 安装metrics-server[root@master 1.8+]# kubectl apply -f ./# 查看pod运行情况[root@master 1.8+]# kubectl get pod -n kube-systemmetrics-server-6b976979db-2xwbj   1/1     Running   0          90s# 使用kubectl top node 查看资源使用情况[root@master 1.8+]# kubectl top nodeNAME     CPU(cores)   CPU%   MEMORY(bytes)   MEMORY%master   98m          4%     1067Mi          62%node1    27m          1%     727Mi           42%node2    34m          1%     800Mi           46%[root@master 1.8+]# kubectl top pod -n kube-systemNAME                              CPU(cores)   MEMORY(bytes)coredns-6955765f44-7ptsb          3m           9Micoredns-6955765f44-vcwr5          3m           8Mietcd-master                       14m          145Mi...# 至此,metrics-server安装完成</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <p><strong>2 准备deployment和servie</strong></p> 
    <p>为了操作简单,直接使用命令</p> 
    <pre data-index="206" class="set-code-show prettyprint"><code class="prism language-powershell has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token comment"># 创建deployment [root@master 1.8+]# kubectl run nginx --image=nginx:latest --requests=cpu=100m -n dev# 创建service[root@master 1.8+]# kubectl expose deployment nginx --type=NodePort --port=80 -n dev# 查看[root@master 1.8+]# kubectl get deployment,pod,svc -n devNAME                    READY   UP-TO-DATE   AVAILABLE   AGEdeployment.apps/nginx   1/1     1            1           47sNAME                         READY   STATUS    RESTARTS   AGEpod/nginx-7df9756ccc-bh8dr   1/1     Running   0          47sNAME            TYPE       CLUSTER-IP      EXTERNAL-IP   PORT(S)        AGEservice/nginx   NodePort   10.109.57.248   <none>        80:31136/TCP   35s</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <p><strong>3 部署HPA</strong></p> 
    <p>创建pc-hpa.yaml</p> 
    <pre data-index="207" class="set-code-show prettyprint"><code class="prism language-yaml has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token key atrule">apiVersion</span><span class="token punctuation">:</span> <span class="token key atrule">autoscaling/v1kind</span><span class="token punctuation">:</span> <span class="token key atrule">HorizontalPodAutoscalermetadata</span><span class="token punctuation">:</span>  <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">pc-hpa  namespace</span><span class="token punctuation">:</span> <span class="token key atrule">devspec</span><span class="token punctuation">:</span>  <span class="token key atrule">minReplicas</span><span class="token punctuation">:</span> <span class="token number">1</span>  <span class="token comment">#最小pod数量  maxReplicas: 10 #最大pod数量  targetCPUUtilizationPercentage: 3 # CPU使用率指标  scaleTargetRef:   # 指定要控制的nginx信息    apiVersion: apps/v1    kind: Deployment      name: nginx  </span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <pre data-index="208" class="set-code-show prettyprint"><code class="prism language-powershell has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token comment"># 创建hpa[root@master 1.8+]# kubectl create -f pc-hpa.yamlhorizontalpodautoscaler.autoscaling/pc-hpa created# 查看hpa[root@master 1.8+]# kubectl get hpa -n devNAME     REFERENCE          TARGETS   MINPODS   MAXPODS   REPLICAS   AGEpc-hpa   Deployment/nginx   0%/3%     1         10        1          62s</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <p><strong>4 测试</strong></p> 
    <p>使用压测工具对service地址<code>192.168.109.100:31136</code>进行压测,然后通过控制台查看hpa和pod的变化</p> 
    <p><code>hpa变化</code></p> 
    <pre data-index="209" class="set-code-show prettyprint"><code class="prism language-powershell has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token namespace">[root@master ~]</span><span class="token comment"># kubectl get hpa -n dev -wNAME     REFERENCE          TARGETS   MINPODS   MAXPODS   REPLICAS   AGEpc-hpa   Deployment/nginx   0%/3%     1         10        1          4m11spc-hpa   Deployment/nginx   0%/3%     1         10        1          5m19spc-hpa   Deployment/nginx   22%/3%    1         10        1          6m50spc-hpa   Deployment/nginx   22%/3%    1         10        4          7m5spc-hpa   Deployment/nginx   22%/3%    1         10        8          7m21spc-hpa   Deployment/nginx   6%/3%     1         10        8          7m51spc-hpa   Deployment/nginx   0%/3%     1         10        8          9m6spc-hpa   Deployment/nginx   0%/3%     1         10        8          13mpc-hpa   Deployment/nginx   0%/3%     1         10        1          14m</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <p><code>deployment变化</code></p> 
    <pre data-index="210" class="set-code-show prettyprint"><code class="prism language-powershell has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token namespace">[root@master ~]</span><span class="token comment"># kubectl get deployment -n dev -wNAME    READY   UP-TO-DATE   AVAILABLE   AGEnginx   1/1     1            1           11mnginx   1/4     1            1           13mnginx   1/4     1            1           13mnginx   1/4     1            1           13mnginx   1/4     4            1           13mnginx   1/8     4            1           14mnginx   1/8     4            1           14mnginx   1/8     4            1           14mnginx   1/8     8            1           14mnginx   2/8     8            2           14mnginx   3/8     8            3           14mnginx   4/8     8            4           14mnginx   5/8     8            5           14mnginx   6/8     8            6           14mnginx   7/8     8            7           14mnginx   8/8     8            8           15mnginx   8/1     8            8           20mnginx   8/1     8            8           20mnginx   1/1     1            1           20m</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <p><code>pod变化</code></p> 
    <pre data-index="211" class="set-code-show prettyprint"><code class="prism language-powershell has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token namespace">[root@master ~]</span><span class="token comment"># kubectl get pods -n dev -wNAME                     READY   STATUS    RESTARTS   AGEnginx-7df9756ccc-bh8dr   1/1     Running   0          11mnginx-7df9756ccc-cpgrv   0/1     Pending   0          0snginx-7df9756ccc-8zhwk   0/1     Pending   0          0snginx-7df9756ccc-rr9bn   0/1     Pending   0          0snginx-7df9756ccc-cpgrv   0/1     ContainerCreating   0          0snginx-7df9756ccc-8zhwk   0/1     ContainerCreating   0          0snginx-7df9756ccc-rr9bn   0/1     ContainerCreating   0          0snginx-7df9756ccc-m9gsj   0/1     Pending             0          0snginx-7df9756ccc-g56qb   0/1     Pending             0          0snginx-7df9756ccc-sl9c6   0/1     Pending             0          0snginx-7df9756ccc-fgst7   0/1     Pending             0          0snginx-7df9756ccc-g56qb   0/1     ContainerCreating   0          0snginx-7df9756ccc-m9gsj   0/1     ContainerCreating   0          0snginx-7df9756ccc-sl9c6   0/1     ContainerCreating   0          0snginx-7df9756ccc-fgst7   0/1     ContainerCreating   0          0snginx-7df9756ccc-8zhwk   1/1     Running             0          19snginx-7df9756ccc-rr9bn   1/1     Running             0          30snginx-7df9756ccc-m9gsj   1/1     Running             0          21snginx-7df9756ccc-cpgrv   1/1     Running             0          47snginx-7df9756ccc-sl9c6   1/1     Running             0          33snginx-7df9756ccc-g56qb   1/1     Running             0          48snginx-7df9756ccc-fgst7   1/1     Running             0          66snginx-7df9756ccc-fgst7   1/1     Terminating         0          6m50snginx-7df9756ccc-8zhwk   1/1     Terminating         0          7m5snginx-7df9756ccc-cpgrv   1/1     Terminating         0          7m5snginx-7df9756ccc-g56qb   1/1     Terminating         0          6m50snginx-7df9756ccc-rr9bn   1/1     Terminating         0          7m5snginx-7df9756ccc-m9gsj   1/1     Terminating         0          6m50snginx-7df9756ccc-sl9c6   1/1     Terminating         0          6m50s</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <h3><a name="t80"></a><a id="DaemonSetDS_3447"></a>DaemonSet(DS)</h3> 
    <p>​ DaemonSet类型的控制器可以保证在集群中的每一台(或指定)节点上都运行一个副本。一般适用于日志收集、节点监控等场景。也就是说,如果一个Pod提供的功能是节点级别的(每个节点都需要且只需要一个),那么这类Pod就适合使用DaemonSet类型的控制器创建。</p> 
    <p><img src="https://1000bd.com/contentImg/2024/04/15/c86b1a4858802126.png" alt=""></p> 
    <p>DaemonSet控制器的特点:</p> 
    <ul><li>每当向集群中添加一个节点时,指定的 Pod 副本也将添加到该节点上</li><li>当节点从集群中移除时,Pod 也就被垃圾回收了</li></ul> 
    <p>下面先来看下DaemonSet的资源清单文件</p> 
    <pre data-index="212" class="set-code-show prettyprint"><code class="prism language-yaml has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token key atrule">apiVersion</span><span class="token punctuation">:</span> apps/v1 <span class="token comment"># 版本号kind: DaemonSet # 类型       metadata: # 元数据  name: # rs名称   namespace: # 所属命名空间   labels: #标签    controller: daemonsetspec: # 详情描述  revisionHistoryLimit: 3 # 保留历史版本  updateStrategy: # 更新策略    type: RollingUpdate # 滚动更新策略    rollingUpdate: # 滚动更新      maxUnavailable: 1 # 最大不可用状态的 Pod 的最大值,可以为百分比,也可以为整数  selector: # 选择器,通过它指定该控制器管理哪些pod    matchLabels:      # Labels匹配规则      app: nginx-pod    matchExpressions: # Expressions匹配规则      - {key: app, operator: In, values: [nginx-pod]}  template: # 模板,当副本数量不足时,会根据下面的模板创建pod副本    metadata:      labels:        app: nginx-pod    spec:      containers:      - name: nginx        image: nginx:1.17.1        ports:        - containerPort: 80</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <p>创建pc-daemonset.yaml,内容如下:</p> 
    <pre data-index="213" class="set-code-show prettyprint"><code class="prism language-yaml has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token key atrule">apiVersion</span><span class="token punctuation">:</span> <span class="token key atrule">apps/v1kind</span><span class="token punctuation">:</span> <span class="token key atrule">DaemonSet      metadata</span><span class="token punctuation">:</span>  <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">pc-daemonset  namespace</span><span class="token punctuation">:</span> <span class="token key atrule">devspec</span><span class="token punctuation">:</span>   <span class="token key atrule">selector</span><span class="token punctuation">:</span>    <span class="token key atrule">matchLabels</span><span class="token punctuation">:</span>      <span class="token key atrule">app</span><span class="token punctuation">:</span> <span class="token key atrule">nginx-pod  template</span><span class="token punctuation">:</span>    <span class="token key atrule">metadata</span><span class="token punctuation">:</span>      <span class="token key atrule">labels</span><span class="token punctuation">:</span>        <span class="token key atrule">app</span><span class="token punctuation">:</span> <span class="token key atrule">nginx-pod    spec</span><span class="token punctuation">:</span>      <span class="token key atrule">containers</span><span class="token punctuation">:</span>      <span class="token punctuation">-</span> <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">nginx        image</span><span class="token punctuation">:</span> nginx<span class="token punctuation">:</span>1.17.1
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <pre data-index="214" class="set-code-show prettyprint"><code class="prism language-powershell has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token comment"># 创建daemonset[root@master ~]# kubectl create -f  pc-daemonset.yamldaemonset.apps/pc-daemonset created# 查看daemonset[root@master ~]#  kubectl get ds -n dev -o wideNAME        DESIRED  CURRENT  READY  UP-TO-DATE  AVAILABLE   AGE   CONTAINERS   IMAGES         pc-daemonset   2        2        2      2           2        24s   nginx        nginx:1.17.1   # 查看pod,发现在每个Node上都运行一个pod[root@master ~]#  kubectl get pods -n dev -o wideNAME                 READY   STATUS    RESTARTS   AGE   IP            NODE    pc-daemonset-9bck8   1/1     Running   0          37s   10.244.1.43   node1     pc-daemonset-k224w   1/1     Running   0          37s   10.244.2.74   node2      # 删除daemonset[root@master ~]# kubectl delete -f pc-daemonset.yamldaemonset.apps "pc-daemonset" deleted</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <h3><a name="t81"></a><a id="Job_3474"></a>Job</h3> 
    <p>Job,主要用于负责**批量处理(一次要处理指定数量任务)<strong>短暂的</strong>一次性(每个任务仅运行一次就结束)**任务。Job特点如下:</p> 
    <ul><li>当Job创建的pod执行成功结束时,Job将记录成功结束的pod数量</li><li>当成功结束的pod达到指定的数量时,Job将完成执行</li></ul> 
    <img src="https://1000bd.com/contentImg/2024/04/13/f8aba8e744be6f05.png"> 
    <p>Job的资源清单文件:</p> 
    <pre data-index="215" class="set-code-show prettyprint"><code class="prism language-yaml has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token key atrule">apiVersion</span><span class="token punctuation">:</span> batch/v1 <span class="token comment"># 版本号kind: Job # 类型       metadata: # 元数据  name: # rs名称   namespace: # 所属命名空间   labels: #标签    controller: jobspec: # 详情描述  completions: 1 # 指定job需要成功运行Pods的次数。默认值: 1  parallelism: 1 # 指定job在任一时刻应该并发运行Pods的数量。默认值: 1  activeDeadlineSeconds: 30 # 指定job可运行的时间期限,超过时间还未结束,系统将会尝试进行终止。  backoffLimit: 6 # 指定job失败后进行重试的次数。默认是6  manualSelector: true # 是否可以使用selector选择器选择pod,默认是false  selector: # 选择器,通过它指定该控制器管理哪些pod    matchLabels:      # Labels匹配规则      app: counter-pod    matchExpressions: # Expressions匹配规则      - {key: app, operator: In, values: [counter-pod]}  template: # 模板,当副本数量不足时,会根据下面的模板创建pod副本    metadata:      labels:        app: counter-pod    spec:      restartPolicy: Never # 重启策略只能设置为Never或者OnFailure      containers:      - name: counter        image: busybox:1.30        command: ["bin/sh","-c","for i in 9 8 7 6 5 4 3 2 1; do echo $i;sleep 2;done"]</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <pre data-index="216" class="set-code-show prettyprint"><code class="prism language-markdown has-numbering" onclick="mdcp.signin(event)" style="position: unset;">关于重启策略设置的说明:    如果指定为OnFailure,则job会在pod出现故障时重启容器,而不是创建pod,failed次数不变    如果指定为Never,则job会在pod出现故障时创建新的pod,并且故障pod不会消失,也不会重启,failed次数加1    如果指定为Always的话,就意味着一直重启,意味着job任务会重复去执行了,当然不对,所以不能设置为Always
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <p>创建pc-job.yaml,内容如下:</p> 
    <pre data-index="217" class="set-code-show prettyprint"><code class="prism language-yaml has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token key atrule">apiVersion</span><span class="token punctuation">:</span> <span class="token key atrule">batch/v1kind</span><span class="token punctuation">:</span> <span class="token key atrule">Job      metadata</span><span class="token punctuation">:</span>  <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">pc-job  namespace</span><span class="token punctuation">:</span> <span class="token key atrule">devspec</span><span class="token punctuation">:</span>  <span class="token key atrule">manualSelector</span><span class="token punctuation">:</span> <span class="token key atrule">true  selector</span><span class="token punctuation">:</span>    <span class="token key atrule">matchLabels</span><span class="token punctuation">:</span>      <span class="token key atrule">app</span><span class="token punctuation">:</span> <span class="token key atrule">counter-pod  template</span><span class="token punctuation">:</span>    <span class="token key atrule">metadata</span><span class="token punctuation">:</span>      <span class="token key atrule">labels</span><span class="token punctuation">:</span>        <span class="token key atrule">app</span><span class="token punctuation">:</span> <span class="token key atrule">counter-pod    spec</span><span class="token punctuation">:</span>      <span class="token key atrule">restartPolicy</span><span class="token punctuation">:</span> <span class="token key atrule">Never      containers</span><span class="token punctuation">:</span>      <span class="token punctuation">-</span> <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">counter        image</span><span class="token punctuation">:</span> <span class="token key atrule">busybox:1.30        command</span><span class="token punctuation">:</span> <span class="token punctuation">[</span><span class="token string">"bin/sh"</span><span class="token punctuation">,</span><span class="token string">"-c"</span><span class="token punctuation">,</span><span class="token string">"for i in 9 8 7 6 5 4 3 2 1; do echo $i;sleep 3;done"</span><span class="token punctuation">]</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <pre data-index="218" class="set-code-show prettyprint"><code class="prism language-powershell has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token comment"># 创建job[root@master ~]# kubectl create -f pc-job.yamljob.batch/pc-job created# 查看job[root@master ~]# kubectl get job -n dev -o wide  -wNAME     COMPLETIONS   DURATION   AGE   CONTAINERS   IMAGES         SELECTORpc-job   0/1           21s        21s   counter      busybox:1.30   app=counter-podpc-job   1/1           31s        79s   counter      busybox:1.30   app=counter-pod# 通过观察pod状态可以看到,pod在运行完毕任务后,就会变成Completed状态[root@master ~]# kubectl get pods -n dev -wNAME           READY   STATUS     RESTARTS      AGEpc-job-rxg96   1/1     Running     0            29spc-job-rxg96   0/1     Completed   0            33s# 接下来,调整下pod运行的总数量和并行数量 即:在spec下设置下面两个选项#  completions: 6 # 指定job需要成功运行Pods的次数为6#  parallelism: 3 # 指定job并发运行Pods的数量为3#  然后重新运行job,观察效果,此时会发现,job会每次运行3个pod,总共执行了6个pod[root@master ~]# kubectl get pods -n dev -wNAME           READY   STATUS    RESTARTS   AGEpc-job-684ft   1/1     Running   0          5spc-job-jhj49   1/1     Running   0          5spc-job-pfcvh   1/1     Running   0          5spc-job-684ft   0/1     Completed   0          11spc-job-v7rhr   0/1     Pending     0          0spc-job-v7rhr   0/1     Pending     0          0spc-job-v7rhr   0/1     ContainerCreating   0          0spc-job-jhj49   0/1     Completed           0          11spc-job-fhwf7   0/1     Pending             0          0spc-job-fhwf7   0/1     Pending             0          0spc-job-pfcvh   0/1     Completed           0          11spc-job-5vg2j   0/1     Pending             0          0spc-job-fhwf7   0/1     ContainerCreating   0          0spc-job-5vg2j   0/1     Pending             0          0spc-job-5vg2j   0/1     ContainerCreating   0          0spc-job-fhwf7   1/1     Running             0          2spc-job-v7rhr   1/1     Running             0          2spc-job-5vg2j   1/1     Running             0          3spc-job-fhwf7   0/1     Completed           0          12spc-job-v7rhr   0/1     Completed           0          12spc-job-5vg2j   0/1     Completed           0          12s# 删除job[root@master ~]# kubectl delete -f pc-job.yamljob.batch "pc-job" deleted</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <h3><a name="t82"></a><a id="CronJobCJ_3503"></a>CronJob(CJ)</h3> 
    <p>​ CronJob控制器以Job控制器资源为其管控对象,并借助它管理pod资源对象,Job控制器定义的作业任务在其控制器资源创建之后便会立即执行,但CronJob可以以类似于Linux操作系统的周期性任务作业计划的方式控制其运行<strong>时间点</strong>及<strong>重复运行</strong>的方式。也就是说,<strong>CronJob可以在特定的时间点(反复的)去运行job任务</strong>。</p> 
    <img src="https://1000bd.com/contentImg/2024/04/13/4716bf3182fe1f25.png"> 
    <p>CronJob的资源清单文件:</p> 
    <pre data-index="219" class="set-code-show prettyprint"><code class="prism language-yaml has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token key atrule">apiVersion</span><span class="token punctuation">:</span> batch/v1beta1 <span class="token comment"># 版本号kind: CronJob # 类型       metadata: # 元数据  name: # rs名称   namespace: # 所属命名空间   labels: #标签    controller: cronjobspec: # 详情描述  schedule: # cron格式的作业调度运行时间点,用于控制任务在什么时间执行  concurrencyPolicy: # 并发执行策略,用于定义前一次作业运行尚未完成时是否以及如何运行后一次的作业  failedJobHistoryLimit: # 为失败的任务执行保留的历史记录数,默认为1  successfulJobHistoryLimit: # 为成功的任务执行保留的历史记录数,默认为3  startingDeadlineSeconds: # 启动作业错误的超时时长  jobTemplate: # job控制器模板,用于为cronjob控制器生成job对象;下面其实就是job的定义    metadata:    spec:      completions: 1      parallelism: 1      activeDeadlineSeconds: 30      backoffLimit: 6      manualSelector: true      selector:        matchLabels:          app: counter-pod        matchExpressions: 规则          - {key: app, operator: In, values: [counter-pod]}      template:        metadata:          labels:            app: counter-pod        spec:          restartPolicy: Never           containers:          - name: counter            image: busybox:1.30            command: ["bin/sh","-c","for i in 9 8 7 6 5 4 3 2 1; do echo $i;sleep 20;done"]</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <pre data-index="220" class="set-code-show prettyprint"><code class="prism language-markdown has-numbering" onclick="mdcp.signin(event)" style="position: unset;">需要重点解释的几个选项:schedule: cron表达式,用于指定任务的执行时间	*/1    *      *    *     *	<分钟> <小时> <日> <月份> <星期>    分钟 值从 0 到 59.    小时 值从 0 到 23.    日 值从 1 到 31.    月 值从 1 到 12.    星期 值从 0 到 6, 0 代表星期日    多个时间可以用逗号隔开; 范围可以用连字符给出;*可以作为通配符; /表示每...concurrencyPolicy:	Allow:   允许Jobs并发运行(默认)	Forbid:  禁止并发运行,如果上一次运行尚未完成,则跳过下一次运行	Replace: 替换,取消当前正在运行的作业并用新作业替换它
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <p>创建pc-cronjob.yaml,内容如下:</p> 
    <pre data-index="221" class="set-code-show prettyprint"><code class="prism language-yaml has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token key atrule">apiVersion</span><span class="token punctuation">:</span> <span class="token key atrule">batch/v1beta1kind</span><span class="token punctuation">:</span> <span class="token key atrule">CronJobmetadata</span><span class="token punctuation">:</span>  <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">pc-cronjob  namespace</span><span class="token punctuation">:</span> <span class="token key atrule">dev  labels</span><span class="token punctuation">:</span>    <span class="token key atrule">controller</span><span class="token punctuation">:</span> <span class="token key atrule">cronjobspec</span><span class="token punctuation">:</span>  <span class="token key atrule">schedule</span><span class="token punctuation">:</span> "<span class="token important">*/1</span> * * * <span class="token important">*"</span>  jobTemplate<span class="token punctuation">:</span>    <span class="token key atrule">metadata</span><span class="token punctuation">:</span>    <span class="token key atrule">spec</span><span class="token punctuation">:</span>      <span class="token key atrule">template</span><span class="token punctuation">:</span>        <span class="token key atrule">spec</span><span class="token punctuation">:</span>          <span class="token key atrule">restartPolicy</span><span class="token punctuation">:</span> <span class="token key atrule">Never          containers</span><span class="token punctuation">:</span>          <span class="token punctuation">-</span> <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">counter            image</span><span class="token punctuation">:</span> <span class="token key atrule">busybox:1.30            command</span><span class="token punctuation">:</span> <span class="token punctuation">[</span><span class="token string">"bin/sh"</span><span class="token punctuation">,</span><span class="token string">"-c"</span><span class="token punctuation">,</span><span class="token string">"for i in 9 8 7 6 5 4 3 2 1; do echo $i;sleep 3;done"</span><span class="token punctuation">]</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <pre data-index="222" class="set-code-show prettyprint"><code class="prism language-powershell has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token comment"># 创建cronjob[root@master ~]# kubectl create -f pc-cronjob.yamlcronjob.batch/pc-cronjob created# 查看cronjob[root@master ~]# kubectl get cronjobs -n devNAME         SCHEDULE      SUSPEND   ACTIVE   LAST SCHEDULE   AGEpc-cronjob   */1 * * * *   False     0        <none>          6s# 查看job[root@master ~]# kubectl get jobs -n devNAME                    COMPLETIONS   DURATION   AGEpc-cronjob-1592587800   1/1           28s        3m26spc-cronjob-1592587860   1/1           28s        2m26spc-cronjob-1592587920   1/1           28s        86s# 查看pod[root@master ~]# kubectl get pods -n devpc-cronjob-1592587800-x4tsm   0/1     Completed   0          2m24spc-cronjob-1592587860-r5gv4   0/1     Completed   0          84spc-cronjob-1592587920-9dxxq   1/1     Running     0          24s# 删除cronjob[root@master ~]# kubectl  delete -f pc-cronjob.yamlcronjob.batch "pc-cronjob" deleted</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <h2><a name="t83"></a><a id="_Service_3531"></a>第七章 Service详解</h2> 
    <p>本章节主要介绍kubernetes的流量负载组件:Service和Ingress。</p> 
    <h3><a name="t84"></a><a id="Service_3535"></a>Service介绍</h3> 
    <p>​ 在kubernetes中,pod是应用程序的载体,我们可以通过pod的ip来访问应用程序,但是pod的ip地址不是固定的,这也就意味着不方便直接采用pod的ip对服务进行访问。</p> 
    <p>​ 为了解决这个问题,kubernetes提供了Service资源,Service会对提供同一个服务的多个pod进行聚合,并且提供一个统一的入口地址。通过访问Service的入口地址就能访问到后面的pod服务。</p> 
    <img src="Kubernetes教程.assets/image-20200408194716912-16338583136346.png"> 
    <p>​ Service在很多情况下只是一个概念,真正起作用的其实是kube-proxy服务进程,每个Node节点上都运行着一个kube-proxy服务进程。当创建Service的时候会通过api-server向etcd写入创建的service的信息,而kube-proxy会基于监听的机制发现这种Service的变动,然后<strong>它会将最新的Service信息转换成对应的访问规则</strong>。</p> 
    <img src="https://1000bd.com/contentImg/2024/04/14/0ac0c15c79b458b8.png"> 
    <pre data-index="223" class="set-code-show prettyprint"><code class="prism language-powershell has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token comment"># 10.97.97.97:80 是service提供的访问入口# 当访问这个入口的时候,可以发现后面有三个pod的服务在等待调用,# kube-proxy会基于rr(轮询)的策略,将请求分发到其中一个pod上去# 这个规则会同时在集群内的所有节点上都生成,所以在任何一个节点上访问都可以。[root@node1 ~]# ipvsadm -LnIP Virtual Server version 1.2.1 (size=4096)Prot LocalAddress:Port Scheduler Flags  -> RemoteAddress:Port           Forward Weight ActiveConn InActConnTCP  10.97.97.97:80 rr  -> 10.244.1.39:80               Masq    1      0          0  -> 10.244.1.40:80               Masq    1      0          0  -> 10.244.2.33:80               Masq    1      0          0</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <p>kube-proxy目前支持三种工作模式:</p> 
    <p><strong>userspace 模式</strong></p> 
    <p>​ userspace模式下,kube-proxy会为每一个Service创建一个监听端口,发向Cluster IP的请求被Iptables规则重定向到kube-proxy监听的端口上,kube-proxy根据LB算法选择一个提供服务的Pod并和其建立链接,以将请求转发到Pod上。<br> ​ 该模式下,kube-proxy充当了一个四层负责均衡器的角色。由于kube-proxy运行在userspace中,在进行转发处理时会增加内核和用户空间之间的数据拷贝,虽然比较稳定,但是效率比较低。</p> 
    <img src="https://1000bd.com/contentImg/2024/04/14/34399b4c80bf3cc9.png"> 
    <p><strong>iptables 模式</strong></p> 
    <p>​ iptables模式下,kube-proxy为service后端的每个Pod创建对应的iptables规则,直接将发向Cluster IP的请求重定向到一个Pod IP。<br> ​ 该模式下kube-proxy不承担四层负责均衡器的角色,只负责创建iptables规则。该模式的优点是较userspace模式效率更高,但不能提供灵活的LB策略,当后端Pod不可用时也无法进行重试。</p> 
    <img src="https://1000bd.com/contentImg/2024/04/14/4f2488a4d0856a36.png"> 
    <p><strong>ipvs 模式</strong></p> 
    <p>​ ipvs模式和iptables类似,kube-proxy监控Pod的变化并创建相应的ipvs规则。ipvs相对iptables转发效率更高。除此以外,ipvs支持更多的LB算法。</p> 
    <img src="https://1000bd.com/contentImg/2024/04/14/480a20e1239dda8a.png"> 
    <pre data-index="224" class="set-code-show prettyprint"><code class="prism language-powershell has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token comment"># 此模式必须安装ipvs内核模块,否则会降级为iptables# 开启ipvs[root@master ~]# kubectl edit cm kube-proxy -n kube-system[root@master ~]# kubectl delete pod -l k8s-app=kube-proxy -n kube-system[root@node1 ~]# ipvsadm -LnIP Virtual Server version 1.2.1 (size=4096)Prot LocalAddress:Port Scheduler Flags  -> RemoteAddress:Port           Forward Weight ActiveConn InActConnTCP  10.97.97.97:80 rr  -> 10.244.1.39:80               Masq    1      0          0  -> 10.244.1.40:80               Masq    1      0          0  -> 10.244.2.33:80               Masq    1      0          0</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <h3><a name="t85"></a><a id="Service_3577"></a>Service类型</h3> 
    <p>Service的资源清单文件:</p> 
    <pre data-index="225" class="set-code-show prettyprint"><code class="prism language-yaml has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token key atrule">kind</span><span class="token punctuation">:</span> Service  <span class="token comment"># 资源类型apiVersion: v1  # 资源版本metadata: # 元数据  name: service # 资源名称  namespace: dev # 命名空间spec: # 描述  selector: # 标签选择器,用于确定当前service代理哪些pod    app: nginx  type: # Service类型,指定service的访问方式  clusterIP:  # 虚拟服务的ip地址  sessionAffinity: # session亲和性,支持ClientIP、None两个选项  ports: # 端口信息    - protocol: TCP       port: 3017  # service端口      targetPort: 5003 # pod端口      nodePort: 31122 # 主机端口</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <ul><li>ClusterIP:默认值,它是Kubernetes系统自动分配的虚拟IP,只能在集群内部访问</li><li>NodePort:将Service通过指定的Node上的端口暴露给外部,通过此方法,就可以在集群外部访问服务</li><li>LoadBalancer:使用外接负载均衡器完成到服务的负载分发,注意此模式需要外部云环境支持</li><li>ExternalName: 把集群外部的服务引入集群内部,直接使用</li></ul> 
    <h3><a name="t86"></a><a id="Service_3590"></a>Service使用</h3> 
    <h4><a name="t87"></a><a id="_3592"></a>实验环境准备</h4> 
    <p>在使用service之前,首先利用Deployment创建出3个pod,注意要为pod设置<code>app=nginx-pod</code>的标签</p> 
    <p>创建deployment.yaml,内容如下:</p> 
    <pre data-index="226" class="set-code-show prettyprint"><code class="prism language-yaml has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token key atrule">apiVersion</span><span class="token punctuation">:</span> <span class="token key atrule">apps/v1kind</span><span class="token punctuation">:</span> <span class="token key atrule">Deployment      metadata</span><span class="token punctuation">:</span>  <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">pc-deployment  namespace</span><span class="token punctuation">:</span> <span class="token key atrule">devspec</span><span class="token punctuation">:</span>   <span class="token key atrule">replicas</span><span class="token punctuation">:</span> <span class="token key atrule">3  selector</span><span class="token punctuation">:</span>    <span class="token key atrule">matchLabels</span><span class="token punctuation">:</span>      <span class="token key atrule">app</span><span class="token punctuation">:</span> <span class="token key atrule">nginx-pod  template</span><span class="token punctuation">:</span>    <span class="token key atrule">metadata</span><span class="token punctuation">:</span>      <span class="token key atrule">labels</span><span class="token punctuation">:</span>        <span class="token key atrule">app</span><span class="token punctuation">:</span> <span class="token key atrule">nginx-pod    spec</span><span class="token punctuation">:</span>      <span class="token key atrule">containers</span><span class="token punctuation">:</span>      <span class="token punctuation">-</span> <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">nginx        image</span><span class="token punctuation">:</span> <span class="token key atrule">nginx:1.17.1        ports</span><span class="token punctuation">:</span>        <span class="token punctuation">-</span> <span class="token key atrule">containerPort</span><span class="token punctuation">:</span> <span class="token number">80</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <pre data-index="227" class="set-code-show prettyprint"><code class="prism language-powershell has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token namespace">[root@master ~]</span><span class="token comment"># kubectl create -f deployment.yamldeployment.apps/pc-deployment created# 查看pod详情[root@master ~]# kubectl get pods -n dev -o wide --show-labelsNAME                             READY   STATUS     IP            NODE     LABELSpc-deployment-66cb59b984-8p84h   1/1     Running    10.244.1.40   node1    app=nginx-podpc-deployment-66cb59b984-vx8vx   1/1     Running    10.244.2.33   node2    app=nginx-podpc-deployment-66cb59b984-wnncx   1/1     Running    10.244.1.39   node1    app=nginx-pod# 为了方便后面的测试,修改下三台nginx的index.html页面(三台修改的IP地址不一致)# kubectl exec -it pc-deployment-66cb59b984-8p84h -n dev /bin/sh# echo "10.244.1.40" > /usr/share/nginx/html/index.html#修改完毕之后,访问测试[root@master ~]# curl 10.244.1.4010.244.1.40[root@master ~]# curl 10.244.2.3310.244.2.33[root@master ~]# curl 10.244.1.3910.244.1.39</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <h4><a name="t88"></a><a id="ClusterIPService_3606"></a>ClusterIP类型的Service</h4> 
    <p>创建service-clusterip.yaml文件</p> 
    <pre data-index="228" class="set-code-show prettyprint"><code class="prism language-yaml has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token key atrule">apiVersion</span><span class="token punctuation">:</span> <span class="token key atrule">v1kind</span><span class="token punctuation">:</span> <span class="token key atrule">Servicemetadata</span><span class="token punctuation">:</span>  <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">service-clusterip  namespace</span><span class="token punctuation">:</span> <span class="token key atrule">devspec</span><span class="token punctuation">:</span>  <span class="token key atrule">selector</span><span class="token punctuation">:</span>    <span class="token key atrule">app</span><span class="token punctuation">:</span> <span class="token key atrule">nginx-pod  clusterIP</span><span class="token punctuation">:</span> 10.97.97.97 <span class="token comment"># service的ip地址,如果不写,默认会生成一个  type: ClusterIP  ports:  - port: 80  # Service端口           targetPort: 80 # pod端口</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <pre data-index="229" class="set-code-show prettyprint"><code class="prism language-powershell has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token comment"># 创建service[root@master ~]# kubectl create -f service-clusterip.yamlservice/service-clusterip created# 查看service[root@master ~]# kubectl get svc -n dev -o wideNAME                TYPE        CLUSTER-IP    EXTERNAL-IP   PORT(S)   AGE   SELECTORservice-clusterip   ClusterIP   10.97.97.97   <none>        80/TCP    13s   app=nginx-pod# 查看service的详细信息# 在这里有一个Endpoints列表,里面就是当前service可以负载到的服务入口[root@master ~]# kubectl describe svc service-clusterip -n devName:              service-clusteripNamespace:         devLabels:            <none>Annotations:       <none>Selector:          app=nginx-podType:              ClusterIPIP:                10.97.97.97Port:              <unset>  80/TCPTargetPort:        80/TCPEndpoints:         10.244.1.39:80,10.244.1.40:80,10.244.2.33:80Session Affinity:  NoneEvents:            <none># 查看ipvs的映射规则[root@master ~]# ipvsadm -LnTCP  10.97.97.97:80 rr  -> 10.244.1.39:80               Masq    1      0          0  -> 10.244.1.40:80               Masq    1      0          0  -> 10.244.2.33:80               Masq    1      0          0# 访问10.97.97.97:80观察效果[root@master ~]# curl 10.97.97.97:8010.244.2.33</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <p><strong>Endpoint</strong></p> 
    <p>​ Endpoint是kubernetes中的一个资源对象,存储在etcd中,用来记录一个service对应的所有pod的访问地址,它是根据service配置文件中selector描述产生的。</p> 
    <p>​ 一个Service由一组Pod组成,这些Pod通过Endpoints暴露出来,<strong>Endpoints是实现实际服务的端点集合</strong>。换句话说,service和pod之间的联系是通过endpoints实现的。</p> 
    <p><img src="https://1000bd.com/contentImg/2024/04/14/947fcbdc04d34135.png" alt="image-20200509191917069"></p> 
    <p><strong>负载分发策略</strong></p> 
    <p>对Service的访问被分发到了后端的Pod上去,目前kubernetes提供了两种负载分发策略:</p> 
    <ul><li> <p>如果不定义,默认使用kube-proxy的策略,比如随机、轮询</p> </li><li> <p>基于客户端地址的会话保持模式,即来自同一个客户端发起的所有请求都会转发到固定的一个Pod上</p> <p>此模式可以使在spec中添加<code>sessionAffinity:ClientIP</code>选项</p> </li></ul> 
    <pre data-index="230" class="set-code-show prettyprint"><code class="prism language-powershell has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token comment"># 查看ipvs的映射规则【rr 轮询】[root@master ~]# ipvsadm -LnTCP  10.97.97.97:80 rr  -> 10.244.1.39:80               Masq    1      0          0  -> 10.244.1.40:80               Masq    1      0          0  -> 10.244.2.33:80               Masq    1      0          0# 循环访问测试[root@master ~]# while true;do curl 10.97.97.97:80; sleep 5; done;10.244.1.4010.244.1.3910.244.2.3310.244.1.4010.244.1.3910.244.2.33# 修改分发策略----sessionAffinity:ClientIP# 查看ipvs规则【persistent 代表持久】[root@master ~]# ipvsadm -LnTCP  10.97.97.97:80 rr persistent 10800  -> 10.244.1.39:80               Masq    1      0          0  -> 10.244.1.40:80               Masq    1      0          0  -> 10.244.2.33:80               Masq    1      0          0# 循环访问测试[root@master ~]# while true;do curl 10.97.97.97; sleep 5; done;10.244.2.3310.244.2.3310.244.2.33  # 删除service[root@master ~]# kubectl delete -f service-clusterip.yamlservice "service-clusterip" deleted</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <h4><a name="t89"></a><a id="HeadLinessService_3640"></a>HeadLiness类型的Service</h4> 
    <p>​ 在某些场景中,开发人员可能不想使用Service提供的负载均衡功能,而希望自己来控制负载均衡策略,针对这种情况,kubernetes提供了HeadLiness Service,这类Service不会分配Cluster IP,如果想要访问service,只能通过service的域名进行查询。</p> 
    <p>创建service-headliness.yaml</p> 
    <pre data-index="231" class="set-code-show prettyprint"><code class="prism language-yaml has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token key atrule">apiVersion</span><span class="token punctuation">:</span> <span class="token key atrule">v1kind</span><span class="token punctuation">:</span> <span class="token key atrule">Servicemetadata</span><span class="token punctuation">:</span>  <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">service-headliness  namespace</span><span class="token punctuation">:</span> <span class="token key atrule">devspec</span><span class="token punctuation">:</span>  <span class="token key atrule">selector</span><span class="token punctuation">:</span>    <span class="token key atrule">app</span><span class="token punctuation">:</span> <span class="token key atrule">nginx-pod  clusterIP</span><span class="token punctuation">:</span> None <span class="token comment"># 将clusterIP设置为None,即可创建headliness Service  type: ClusterIP  ports:  - port: 80        targetPort: 80</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <pre data-index="232" class="set-code-show prettyprint"><code class="prism language-powershell has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token comment"># 创建service[root@master ~]# kubectl create -f service-headliness.yamlservice/service-headliness created# 获取service, 发现CLUSTER-IP未分配[root@master ~]# kubectl get svc service-headliness -n dev -o wideNAME                 TYPE        CLUSTER-IP   EXTERNAL-IP   PORT(S)   AGE   SELECTORservice-headliness   ClusterIP   None         <none>        80/TCP    11s   app=nginx-pod# 查看service详情[root@master ~]# kubectl describe svc service-headliness  -n devName:              service-headlinessNamespace:         devLabels:            <none>Annotations:       <none>Selector:          app=nginx-podType:              ClusterIPIP:                NonePort:              <unset>  80/TCPTargetPort:        80/TCPEndpoints:         10.244.1.39:80,10.244.1.40:80,10.244.2.33:80Session Affinity:  NoneEvents:            <none># 查看域名的解析情况[root@master ~]# kubectl exec -it pc-deployment-66cb59b984-8p84h -n dev /bin/sh/ # cat /etc/resolv.confnameserver 10.96.0.10search dev.svc.cluster.local svc.cluster.local cluster.local[root@master ~]# dig @10.96.0.10 service-headliness.dev.svc.cluster.localservice-headliness.dev.svc.cluster.local. 30 IN A 10.244.1.40service-headliness.dev.svc.cluster.local. 30 IN A 10.244.1.39service-headliness.dev.svc.cluster.local. 30 IN A 10.244.2.33</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <h4><a name="t90"></a><a id="NodePortService_3654"></a>NodePort类型的Service</h4> 
    <p>​ 在之前的样例中,创建的Service的ip地址只有集群内部才可以访问,如果希望将Service暴露给集群外部使用,那么就要使用到另外一种类型的Service,称为NodePort类型。NodePort的工作原理其实就是<strong>将service的端口映射到Node的一个端口上</strong>,然后就可以通过<code>NodeIp:NodePort</code>来访问service了。</p> 
    <img src="https://1000bd.com/contentImg/2024/04/14/34a05804ede3608a.png"> 
    <p>创建service-nodeport.yaml</p> 
    <pre data-index="233" class="set-code-show prettyprint"><code class="prism language-yaml has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token key atrule">apiVersion</span><span class="token punctuation">:</span> <span class="token key atrule">v1kind</span><span class="token punctuation">:</span> <span class="token key atrule">Servicemetadata</span><span class="token punctuation">:</span>  <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">service-nodeport  namespace</span><span class="token punctuation">:</span> <span class="token key atrule">devspec</span><span class="token punctuation">:</span>  <span class="token key atrule">selector</span><span class="token punctuation">:</span>    <span class="token key atrule">app</span><span class="token punctuation">:</span> <span class="token key atrule">nginx-pod  type</span><span class="token punctuation">:</span> NodePort <span class="token comment"># service类型  ports:  - port: 80    nodePort: 30002 # 指定绑定的node的端口(默认的取值范围是:30000-32767), 如果不指定,会默认分配    targetPort: 80</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <pre data-index="234" class="set-code-show prettyprint"><code class="prism language-powershell has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token comment"># 创建service[root@master ~]# kubectl create -f service-nodeport.yamlservice/service-nodeport created# 查看service[root@master ~]# kubectl get svc -n dev -o wideNAME               TYPE       CLUSTER-IP      EXTERNAL-IP   PORT(S)       SELECTORservice-nodeport   NodePort   10.105.64.191   <none>        80:30002/TCP  app=nginx-pod# 接下来可以通过电脑主机的浏览器去访问集群中任意一个nodeip的30002端口,即可访问到pod</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <h4><a name="t91"></a><a id="LoadBalancerService_3670"></a>LoadBalancer类型的Service</h4> 
    <p>​ LoadBalancer和NodePort很相似,目的都是向外部暴露一个端口,区别在于LoadBalancer会在集群的外部再来做一个负载均衡设备,而这个设备需要外部环境支持的,外部服务发送到这个设备上的请求,会被设备负载之后转发到集群中。</p> 
    <img src="https://1000bd.com/contentImg/2024/04/14/a15e30808fe4519b.png"> 
    <h4><a name="t92"></a><a id="ExternalNameService_3676"></a>ExternalName类型的Service</h4> 
    <p>​ ExternalName类型的Service用于引入集群外部的服务,它通过<code>externalName</code>属性指定外部一个服务的地址,然后在集群内部访问此service就可以访问到外部的服务了。</p> 
    <img src="https://1000bd.com/contentImg/2024/04/14/1463ba3dc52a8ae1.png"> 
    <pre data-index="235" class="set-code-show prettyprint"><code class="prism language-yaml has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token key atrule">apiVersion</span><span class="token punctuation">:</span> <span class="token key atrule">v1kind</span><span class="token punctuation">:</span> <span class="token key atrule">Servicemetadata</span><span class="token punctuation">:</span>  <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">service-externalname  namespace</span><span class="token punctuation">:</span> <span class="token key atrule">devspec</span><span class="token punctuation">:</span>  <span class="token key atrule">type</span><span class="token punctuation">:</span> ExternalName <span class="token comment"># service类型  externalName: www.baidu.com  #改成ip地址也可以</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <pre data-index="236" class="set-code-show prettyprint"><code class="prism language-powershell has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token comment"># 创建service[root@master ~]# kubectl  create -f service-externalname.yamlservice/service-externalname created# 域名解析[root@master ~]# dig @10.96.0.10 service-externalname.dev.svc.cluster.localservice-externalname.dev.svc.cluster.local. 30 IN CNAME www.baidu.com.www.baidu.com.          30      IN      CNAME   www.a.shifen.com.www.a.shifen.com.       30      IN      A       39.156.66.18www.a.shifen.com.       30      IN      A       39.156.66.14</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <h3><a name="t93"></a><a id="Ingress_3690"></a>Ingress介绍</h3> 
    <p>​ 在前面课程中已经提到,Service对集群之外暴露服务的主要方式有两种:NotePort和LoadBalancer,但是这两种方式,都有一定的缺点:</p> 
    <ul><li>NodePort方式的缺点是会占用很多集群机器的端口,那么当集群服务变多的时候,这个缺点就愈发明显</li><li>LB方式的缺点是每个service需要一个LB,浪费、麻烦,并且需要kubernetes之外设备的支持</li></ul> 
    <p>​ 基于这种现状,kubernetes提供了Ingress资源对象,Ingress只需要一个NodePort或者一个LB就可以满足暴露多个Service的需求。工作机制大致如下图表示:</p> 
    <img src="https://1000bd.com/contentImg/2024/04/14/6193447848783c54.png"> 
    <p>​ 实际上,Ingress相当于一个7层的负载均衡器,是kubernetes对反向代理的一个抽象,它的工作原理类似于Nginx,可以理解成在<strong>Ingress里建立诸多映射规则,Ingress Controller通过监听这些配置规则并转化成Nginx的反向代理配置 , 然后对外部提供服务</strong>。在这里有两个核心概念:</p> 
    <ul><li>ingress:kubernetes中的一个对象,作用是定义请求如何转发到service的规则</li><li>ingress controller:具体实现反向代理及负载均衡的程序,对ingress定义的规则进行解析,根据配置的规则来实现请求转发,实现方式有很多,比如Nginx, Contour, Haproxy等等</li></ul> 
    <p>Ingress(以Nginx为例)的工作原理如下:</p> 
    <ol><li>用户编写Ingress规则,说明哪个域名对应kubernetes集群中的哪个Service</li><li>Ingress控制器动态感知Ingress服务规则的变化,然后生成一段对应的Nginx反向代理配置</li><li>Ingress控制器会将生成的Nginx配置写入到一个运行着的Nginx服务中,并动态更新</li><li>到此为止,其实真正在工作的就是一个Nginx了,内部配置了用户定义的请求转发规则</li></ol> 
    <img src="https://1000bd.com/contentImg/2024/04/14/aa7510db9b5f4b8c.png"> 
    <h3><a name="t94"></a><a id="Ingress_3715"></a>Ingress使用</h3> 
    <h4><a name="t95"></a><a id="_3717"></a>环境准备</h4> 
    <p><strong>搭建ingress环境</strong></p> 
    <pre data-index="237" class="set-code-show prettyprint"><code class="prism language-powershell has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token comment"># 创建文件夹[root@master ~]# mkdir ingress-controller[root@master ~]# cd ingress-controller/# 获取ingress-nginx,本次案例使用的是0.30版本[root@master ingress-controller]# wget https://raw.githubusercontent.com/kubernetes/ingress-nginx/nginx-0.30.0/deploy/static/mandatory.yaml[root@master ingress-controller]# wget https://raw.githubusercontent.com/kubernetes/ingress-nginx/nginx-0.30.0/deploy/static/provider/baremetal/service-nodeport.yaml# 修改mandatory.yaml文件中的仓库# 修改quay.io/kubernetes-ingress-controller/nginx-ingress-controller:0.30.0# 为quay-mirror.qiniu.com/kubernetes-ingress-controller/nginx-ingress-controller:0.30.0# 创建ingress-nginx[root@master ingress-controller]# kubectl apply -f ./# 查看ingress-nginx[root@master ingress-controller]# kubectl get pod -n ingress-nginxNAME                                           READY   STATUS    RESTARTS   AGEpod/nginx-ingress-controller-fbf967dd5-4qpbp   1/1     Running   0          12h# 查看service[root@master ingress-controller]# kubectl get svc -n ingress-nginxNAME            TYPE       CLUSTER-IP     EXTERNAL-IP   PORT(S)                      AGEingress-nginx   NodePort   10.98.75.163   <none>        80:32240/TCP,443:31335/TCP   11h</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <p><strong>准备service和pod</strong></p> 
    <p>为了后面的实验比较方便,创建如下图所示的模型</p> 
    <img src="https://1000bd.com/contentImg/2024/04/14/64659a15db380a05.png"> 
    <p>创建tomcat-nginx.yaml</p> 
    <pre data-index="238" class="set-code-show prettyprint"><code class="prism language-yaml has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token key atrule">apiVersion</span><span class="token punctuation">:</span> <span class="token key atrule">apps/v1kind</span><span class="token punctuation">:</span> <span class="token key atrule">Deploymentmetadata</span><span class="token punctuation">:</span>  <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">nginx-deployment  namespace</span><span class="token punctuation">:</span> <span class="token key atrule">devspec</span><span class="token punctuation">:</span>  <span class="token key atrule">replicas</span><span class="token punctuation">:</span> <span class="token key atrule">3  selector</span><span class="token punctuation">:</span>    <span class="token key atrule">matchLabels</span><span class="token punctuation">:</span>      <span class="token key atrule">app</span><span class="token punctuation">:</span> <span class="token key atrule">nginx-pod  template</span><span class="token punctuation">:</span>    <span class="token key atrule">metadata</span><span class="token punctuation">:</span>      <span class="token key atrule">labels</span><span class="token punctuation">:</span>        <span class="token key atrule">app</span><span class="token punctuation">:</span> <span class="token key atrule">nginx-pod    spec</span><span class="token punctuation">:</span>      <span class="token key atrule">containers</span><span class="token punctuation">:</span>      <span class="token punctuation">-</span> <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">nginx        image</span><span class="token punctuation">:</span> <span class="token key atrule">nginx:1.17.1        ports</span><span class="token punctuation">:</span>        <span class="token punctuation">-</span> <span class="token key atrule">containerPort</span><span class="token punctuation">:</span> <span class="token key atrule">80---apiVersion</span><span class="token punctuation">:</span> <span class="token key atrule">apps/v1kind</span><span class="token punctuation">:</span> <span class="token key atrule">Deploymentmetadata</span><span class="token punctuation">:</span>  <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">tomcat-deployment  namespace</span><span class="token punctuation">:</span> <span class="token key atrule">devspec</span><span class="token punctuation">:</span>  <span class="token key atrule">replicas</span><span class="token punctuation">:</span> <span class="token key atrule">3  selector</span><span class="token punctuation">:</span>    <span class="token key atrule">matchLabels</span><span class="token punctuation">:</span>      <span class="token key atrule">app</span><span class="token punctuation">:</span> <span class="token key atrule">tomcat-pod  template</span><span class="token punctuation">:</span>    <span class="token key atrule">metadata</span><span class="token punctuation">:</span>      <span class="token key atrule">labels</span><span class="token punctuation">:</span>        <span class="token key atrule">app</span><span class="token punctuation">:</span> <span class="token key atrule">tomcat-pod    spec</span><span class="token punctuation">:</span>      <span class="token key atrule">containers</span><span class="token punctuation">:</span>      <span class="token punctuation">-</span> <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">tomcat        image</span><span class="token punctuation">:</span> <span class="token key atrule">tomcat:8.5-jre10-slim        ports</span><span class="token punctuation">:</span>        <span class="token punctuation">-</span> <span class="token key atrule">containerPort</span><span class="token punctuation">:</span> <span class="token key atrule">8080---apiVersion</span><span class="token punctuation">:</span> <span class="token key atrule">v1kind</span><span class="token punctuation">:</span> <span class="token key atrule">Servicemetadata</span><span class="token punctuation">:</span>  <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">nginx-service  namespace</span><span class="token punctuation">:</span> <span class="token key atrule">devspec</span><span class="token punctuation">:</span>  <span class="token key atrule">selector</span><span class="token punctuation">:</span>    <span class="token key atrule">app</span><span class="token punctuation">:</span> <span class="token key atrule">nginx-pod  clusterIP</span><span class="token punctuation">:</span> <span class="token key atrule">None  type</span><span class="token punctuation">:</span> <span class="token key atrule">ClusterIP  ports</span><span class="token punctuation">:</span>  <span class="token punctuation">-</span> <span class="token key atrule">port</span><span class="token punctuation">:</span> <span class="token key atrule">80    targetPort</span><span class="token punctuation">:</span> <span class="token key atrule">80---apiVersion</span><span class="token punctuation">:</span> <span class="token key atrule">v1kind</span><span class="token punctuation">:</span> <span class="token key atrule">Servicemetadata</span><span class="token punctuation">:</span>  <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">tomcat-service  namespace</span><span class="token punctuation">:</span> <span class="token key atrule">devspec</span><span class="token punctuation">:</span>  <span class="token key atrule">selector</span><span class="token punctuation">:</span>    <span class="token key atrule">app</span><span class="token punctuation">:</span> <span class="token key atrule">tomcat-pod  clusterIP</span><span class="token punctuation">:</span> <span class="token key atrule">None  type</span><span class="token punctuation">:</span> <span class="token key atrule">ClusterIP  ports</span><span class="token punctuation">:</span>  <span class="token punctuation">-</span> <span class="token key atrule">port</span><span class="token punctuation">:</span> <span class="token key atrule">8080    targetPort</span><span class="token punctuation">:</span> <span class="token number">8080</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <pre data-index="239" class="set-code-show prettyprint"><code class="prism language-powershell has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token comment"># 创建[root@master ~]# kubectl create -f tomcat-nginx.yaml# 查看[root@master ~]# kubectl get svc -n devNAME             TYPE        CLUSTER-IP   EXTERNAL-IP   PORT(S)    AGEnginx-service    ClusterIP   None         <none>        80/TCP     48stomcat-service   ClusterIP   None         <none>        8080/TCP   48s</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <h4><a name="t96"></a><a id="Http_3741"></a>Http代理</h4> 
    <p>创建ingress-http.yaml</p> 
    <pre data-index="240" class="set-code-show prettyprint"><code class="prism language-yaml has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token key atrule">apiVersion</span><span class="token punctuation">:</span> <span class="token key atrule">extensions/v1beta1kind</span><span class="token punctuation">:</span> <span class="token key atrule">Ingressmetadata</span><span class="token punctuation">:</span>  <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">ingress-http  namespace</span><span class="token punctuation">:</span> <span class="token key atrule">devspec</span><span class="token punctuation">:</span>  <span class="token key atrule">rules</span><span class="token punctuation">:</span>  <span class="token punctuation">-</span> <span class="token key atrule">host</span><span class="token punctuation">:</span> <span class="token key atrule">nginx.itheima.com    http</span><span class="token punctuation">:</span>      <span class="token key atrule">paths</span><span class="token punctuation">:</span>      <span class="token punctuation">-</span> <span class="token key atrule">path</span><span class="token punctuation">:</span> <span class="token key atrule">/        backend</span><span class="token punctuation">:</span>          <span class="token key atrule">serviceName</span><span class="token punctuation">:</span> <span class="token key atrule">nginx-service          servicePort</span><span class="token punctuation">:</span> <span class="token key atrule">80  - host</span><span class="token punctuation">:</span> <span class="token key atrule">tomcat.itheima.com    http</span><span class="token punctuation">:</span>      <span class="token key atrule">paths</span><span class="token punctuation">:</span>      <span class="token punctuation">-</span> <span class="token key atrule">path</span><span class="token punctuation">:</span> <span class="token key atrule">/        backend</span><span class="token punctuation">:</span>          <span class="token key atrule">serviceName</span><span class="token punctuation">:</span> <span class="token key atrule">tomcat-service          servicePort</span><span class="token punctuation">:</span> <span class="token number">8080</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <pre data-index="241" class="set-code-show prettyprint"><code class="prism language-powershell has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token comment"># 创建[root@master ~]# kubectl create -f ingress-http.yamlingress.extensions/ingress-http created# 查看[root@master ~]# kubectl get ing ingress-http -n devNAME           HOSTS                                  ADDRESS   PORTS   AGEingress-http   nginx.itheima.com,tomcat.itheima.com             80      22s# 查看详情[root@master ~]# kubectl describe ing ingress-http  -n dev...Rules:Host                Path  Backends----                ----  --------nginx.itheima.com   / nginx-service:80 (10.244.1.96:80,10.244.1.97:80,10.244.2.112:80)tomcat.itheima.com  / tomcat-service:8080(10.244.1.94:8080,10.244.1.95:8080,10.244.2.111:8080)...# 接下来,在本地电脑上配置host文件,解析上面的两个域名到192.168.109.100(master)上# 然后,就可以分别访问tomcat.itheima.com:32240  和  nginx.itheima.com:32240 查看效果了</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <h4><a name="t97"></a><a id="Https_3753"></a>Https代理</h4> 
    <p>创建证书</p> 
    <pre data-index="242" class="set-code-show prettyprint"><code class="prism language-powershell has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token comment"># 生成证书openssl req -x509 -sha256 -nodes -days 365 -newkey rsa:2048 -keyout tls.key -out tls.crt -subj "/C=CN/ST=BJ/L=BJ/O=nginx/CN=itheima.com"# 创建密钥kubectl create secret tls tls-secret --key tls.key --cert tls.crt</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <p>创建ingress-https.yaml</p> 
    <pre data-index="243" class="set-code-hide prettyprint"><code class="prism language-yaml has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token key atrule">apiVersion</span><span class="token punctuation">:</span> extensions/v1beta1
    <span class="token key atrule">kind</span><span class="token punctuation">:</span> Ingress
    <span class="token key atrule">metadata</span><span class="token punctuation">:</span>
      <span class="token key atrule">name</span><span class="token punctuation">:</span> ingress<span class="token punctuation">-</span>https
      <span class="token key atrule">namespace</span><span class="token punctuation">:</span> dev
    <span class="token key atrule">spec</span><span class="token punctuation">:</span>
      <span class="token key atrule">tls</span><span class="token punctuation">:</span>
        <span class="token punctuation">-</span> <span class="token key atrule">hosts</span><span class="token punctuation">:</span>
          <span class="token punctuation">-</span> nginx.itheima.com
          <span class="token punctuation">-</span> tomcat.itheima.com
          <span class="token key atrule">secretName</span><span class="token punctuation">:</span> tls<span class="token punctuation">-</span>secret <span class="token comment"># 指定秘钥</span>
      <span class="token key atrule">rules</span><span class="token punctuation">:</span>
      <span class="token punctuation">-</span> <span class="token key atrule">host</span><span class="token punctuation">:</span> nginx.itheima.com
        <span class="token key atrule">http</span><span class="token punctuation">:</span>
          <span class="token key atrule">paths</span><span class="token punctuation">:</span>
          <span class="token punctuation">-</span> <span class="token key atrule">path</span><span class="token punctuation">:</span> /
            <span class="token key atrule">backend</span><span class="token punctuation">:</span>
              <span class="token key atrule">serviceName</span><span class="token punctuation">:</span> nginx<span class="token punctuation">-</span>service
              <span class="token key atrule">servicePort</span><span class="token punctuation">:</span> <span class="token number">80</span>
      <span class="token punctuation">-</span> <span class="token key atrule">host</span><span class="token punctuation">:</span> tomcat.itheima.com
        <span class="token key atrule">http</span><span class="token punctuation">:</span>
          <span class="token key atrule">paths</span><span class="token punctuation">:</span>
          <span class="token punctuation">-</span> <span class="token key atrule">path</span><span class="token punctuation">:</span> /
            <span class="token key atrule">backend</span><span class="token punctuation">:</span>
              <span class="token key atrule">serviceName</span><span class="token punctuation">:</span> tomcat<span class="token punctuation">-</span>service
              <span class="token key atrule">servicePort</span><span class="token punctuation">:</span> <span class="token number">8080</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><div class="hide-preCode-box"><span class="hide-preCode-bt" data-report-view="{"spm":"1001.2101.3001.7365"}"><img class="look-more-preCode contentImg-no-view" src="https://1000bd.com/contentImg/2022/06/27/191644837.png" alt="" title=""></span></div><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li><li style="color: rgb(153, 153, 153);">2</li><li style="color: rgb(153, 153, 153);">3</li><li style="color: rgb(153, 153, 153);">4</li><li style="color: rgb(153, 153, 153);">5</li><li style="color: rgb(153, 153, 153);">6</li><li style="color: rgb(153, 153, 153);">7</li><li style="color: rgb(153, 153, 153);">8</li><li style="color: rgb(153, 153, 153);">9</li><li style="color: rgb(153, 153, 153);">10</li><li style="color: rgb(153, 153, 153);">11</li><li style="color: rgb(153, 153, 153);">12</li><li style="color: rgb(153, 153, 153);">13</li><li style="color: rgb(153, 153, 153);">14</li><li style="color: rgb(153, 153, 153);">15</li><li style="color: rgb(153, 153, 153);">16</li><li style="color: rgb(153, 153, 153);">17</li><li style="color: rgb(153, 153, 153);">18</li><li style="color: rgb(153, 153, 153);">19</li><li style="color: rgb(153, 153, 153);">20</li><li style="color: rgb(153, 153, 153);">21</li><li style="color: rgb(153, 153, 153);">22</li><li style="color: rgb(153, 153, 153);">23</li><li style="color: rgb(153, 153, 153);">24</li><li style="color: rgb(153, 153, 153);">25</li><li style="color: rgb(153, 153, 153);">26</li></ul></pre> 
    <pre data-index="244" class="set-code-hide prettyprint"><code class="prism language-powershell has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token comment"># 创建</span>
    <span class="token namespace">[root@master ~]</span><span class="token comment"># kubectl create -f ingress-https.yaml</span>
    ingress<span class="token punctuation">.</span>extensions/ingress-https created
    
    <span class="token comment"># 查看</span>
    <span class="token namespace">[root@master ~]</span><span class="token comment"># kubectl get ing ingress-https -n dev</span>
    NAME            HOSTS                                  ADDRESS         PORTS     AGE
    ingress-https   nginx<span class="token punctuation">.</span>itheima<span class="token punctuation">.</span>com<span class="token punctuation">,</span>tomcat<span class="token punctuation">.</span>itheima<span class="token punctuation">.</span>com   10<span class="token punctuation">.</span>104<span class="token punctuation">.</span>184<span class="token punctuation">.</span>38   80<span class="token punctuation">,</span> 443   2m42s
    
    <span class="token comment"># 查看详情</span>
    <span class="token namespace">[root@master ~]</span><span class="token comment"># kubectl describe ing ingress-https -n dev</span>
    <span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span>
    TLS:
      tls-secret terminates nginx<span class="token punctuation">.</span>itheima<span class="token punctuation">.</span>com<span class="token punctuation">,</span>tomcat<span class="token punctuation">.</span>itheima<span class="token punctuation">.</span>com
    Rules:
    Host              Path Backends
    <span class="token operator">--</span><span class="token operator">--</span>              <span class="token operator">--</span><span class="token operator">--</span> <span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span>
    nginx<span class="token punctuation">.</span>itheima<span class="token punctuation">.</span>com  <span class="token operator">/</span>  nginx-service:80 <span class="token punctuation">(</span>10<span class="token punctuation">.</span>244<span class="token punctuation">.</span>1<span class="token punctuation">.</span>97:80<span class="token punctuation">,</span>10<span class="token punctuation">.</span>244<span class="token punctuation">.</span>1<span class="token punctuation">.</span>98:80<span class="token punctuation">,</span>10<span class="token punctuation">.</span>244<span class="token punctuation">.</span>2<span class="token punctuation">.</span>119:80<span class="token punctuation">)</span>
    tomcat<span class="token punctuation">.</span>itheima<span class="token punctuation">.</span>com <span class="token operator">/</span>  tomcat-service:8080<span class="token punctuation">(</span>10<span class="token punctuation">.</span>244<span class="token punctuation">.</span>1<span class="token punctuation">.</span>99:8080<span class="token punctuation">,</span>10<span class="token punctuation">.</span>244<span class="token punctuation">.</span>2<span class="token punctuation">.</span>117:8080<span class="token punctuation">,</span>10<span class="token punctuation">.</span>244<span class="token punctuation">.</span>2<span class="token punctuation">.</span>120:8080<span class="token punctuation">)</span>
    <span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span>
    
    <span class="token comment"># 下面可以通过浏览器访问https://nginx.itheima.com:31335 和 https://tomcat.itheima.com:31335来查看了</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><div class="hide-preCode-box"><span class="hide-preCode-bt" data-report-view="{"spm":"1001.2101.3001.7365"}"><img class="look-more-preCode contentImg-no-view" src="https://1000bd.com/contentImg/2022/06/27/191644837.png" alt="" title=""></span></div><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li><li style="color: rgb(153, 153, 153);">2</li><li style="color: rgb(153, 153, 153);">3</li><li style="color: rgb(153, 153, 153);">4</li><li style="color: rgb(153, 153, 153);">5</li><li style="color: rgb(153, 153, 153);">6</li><li style="color: rgb(153, 153, 153);">7</li><li style="color: rgb(153, 153, 153);">8</li><li style="color: rgb(153, 153, 153);">9</li><li style="color: rgb(153, 153, 153);">10</li><li style="color: rgb(153, 153, 153);">11</li><li style="color: rgb(153, 153, 153);">12</li><li style="color: rgb(153, 153, 153);">13</li><li style="color: rgb(153, 153, 153);">14</li><li style="color: rgb(153, 153, 153);">15</li><li style="color: rgb(153, 153, 153);">16</li><li style="color: rgb(153, 153, 153);">17</li><li style="color: rgb(153, 153, 153);">18</li><li style="color: rgb(153, 153, 153);">19</li><li style="color: rgb(153, 153, 153);">20</li><li style="color: rgb(153, 153, 153);">21</li><li style="color: rgb(153, 153, 153);">22</li></ul></pre> 
    <h2><a name="t98"></a><a id="_Service_3817"></a>第七章 Service详解</h2> 
    <p>本章节主要介绍kubernetes的流量负载组件:Service和Ingress。</p> 
    <h3><a name="t99"></a><a id="Service_3821"></a>Service介绍</h3> 
    <p>​ 在kubernetes中,pod是应用程序的载体,我们可以通过pod的ip来访问应用程序,但是pod的ip地址不是固定的,这也就意味着不方便直接采用pod的ip对服务进行访问。</p> 
    <p>​ 为了解决这个问题,kubernetes提供了Service资源,Service会对提供同一个服务的多个pod进行聚合,并且提供一个统一的入口地址。通过访问Service的入口地址就能访问到后面的pod服务。</p> 
    <img src="https://1000bd.com/contentImg/2024/04/14/ce690ac052858b83.png"> 
    <p>​ Service在很多情况下只是一个概念,真正起作用的其实是kube-proxy服务进程,每个Node节点上都运行着一个kube-proxy服务进程。当创建Service的时候会通过api-server向etcd写入创建的service的信息,而kube-proxy会基于监听的机制发现这种Service的变动,然后<strong>它会将最新的Service信息转换成对应的访问规则</strong>。</p> 
    <img src="https://1000bd.com/contentImg/2024/04/14/0ac0c15c79b458b8.png"> 
    <pre data-index="245" class="set-code-show prettyprint"><code class="prism language-powershell has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token comment"># 10.97.97.97:80 是service提供的访问入口# 当访问这个入口的时候,可以发现后面有三个pod的服务在等待调用,# kube-proxy会基于rr(轮询)的策略,将请求分发到其中一个pod上去# 这个规则会同时在集群内的所有节点上都生成,所以在任何一个节点上访问都可以。[root@node1 ~]# ipvsadm -LnIP Virtual Server version 1.2.1 (size=4096)Prot LocalAddress:Port Scheduler Flags  -> RemoteAddress:Port           Forward Weight ActiveConn InActConnTCP  10.97.97.97:80 rr  -> 10.244.1.39:80               Masq    1      0          0  -> 10.244.1.40:80               Masq    1      0          0  -> 10.244.2.33:80               Masq    1      0          0</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <p>kube-proxy目前支持三种工作模式:</p> 
    <p><strong>userspace 模式</strong></p> 
    <p>​ userspace模式下,kube-proxy会为每一个Service创建一个监听端口,发向Cluster IP的请求被Iptables规则重定向到kube-proxy监听的端口上,kube-proxy根据LB算法选择一个提供服务的Pod并和其建立链接,以将请求转发到Pod上。<br> ​ 该模式下,kube-proxy充当了一个四层负责均衡器的角色。由于kube-proxy运行在userspace中,在进行转发处理时会增加内核和用户空间之间的数据拷贝,虽然比较稳定,但是效率比较低。</p> 
    <img src="https://1000bd.com/contentImg/2024/04/14/34399b4c80bf3cc9.png"> 
    <p><strong>iptables 模式</strong></p> 
    <p>​ iptables模式下,kube-proxy为service后端的每个Pod创建对应的iptables规则,直接将发向Cluster IP的请求重定向到一个Pod IP。<br> ​ 该模式下kube-proxy不承担四层负责均衡器的角色,只负责创建iptables规则。该模式的优点是较userspace模式效率更高,但不能提供灵活的LB策略,当后端Pod不可用时也无法进行重试。</p> 
    <img src="https://1000bd.com/contentImg/2024/04/14/4f2488a4d0856a36.png"> 
    <p><strong>ipvs 模式</strong></p> 
    <p>​ ipvs模式和iptables类似,kube-proxy监控Pod的变化并创建相应的ipvs规则。ipvs相对iptables转发效率更高。除此以外,ipvs支持更多的LB算法。</p> 
    <img src="https://1000bd.com/contentImg/2024/04/14/480a20e1239dda8a.png"> 
    <pre data-index="246" class="set-code-show prettyprint"><code class="prism language-powershell has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token comment"># 此模式必须安装ipvs内核模块,否则会降级为iptables# 开启ipvs[root@master ~]# kubectl edit cm kube-proxy -n kube-system[root@master ~]# kubectl delete pod -l k8s-app=kube-proxy -n kube-system[root@node1 ~]# ipvsadm -LnIP Virtual Server version 1.2.1 (size=4096)Prot LocalAddress:Port Scheduler Flags  -> RemoteAddress:Port           Forward Weight ActiveConn InActConnTCP  10.97.97.97:80 rr  -> 10.244.1.39:80               Masq    1      0          0  -> 10.244.1.40:80               Masq    1      0          0  -> 10.244.2.33:80               Masq    1      0          0</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <h3><a name="t100"></a><a id="Service_3863"></a>Service类型</h3> 
    <p>Service的资源清单文件:</p> 
    <pre data-index="247" class="set-code-show prettyprint"><code class="prism language-yaml has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token key atrule">kind</span><span class="token punctuation">:</span> Service  <span class="token comment"># 资源类型apiVersion: v1  # 资源版本metadata: # 元数据  name: service # 资源名称  namespace: dev # 命名空间spec: # 描述  selector: # 标签选择器,用于确定当前service代理哪些pod    app: nginx  type: # Service类型,指定service的访问方式  clusterIP:  # 虚拟服务的ip地址  sessionAffinity: # session亲和性,支持ClientIP、None两个选项  ports: # 端口信息    - protocol: TCP       port: 3017  # service端口      targetPort: 5003 # pod端口      nodePort: 31122 # 主机端口</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <ul><li>ClusterIP:默认值,它是Kubernetes系统自动分配的虚拟IP,只能在集群内部访问</li><li>NodePort:将Service通过指定的Node上的端口暴露给外部,通过此方法,就可以在集群外部访问服务</li><li>LoadBalancer:使用外接负载均衡器完成到服务的负载分发,注意此模式需要外部云环境支持</li><li>ExternalName: 把集群外部的服务引入集群内部,直接使用</li></ul> 
    <h3><a name="t101"></a><a id="Service_3876"></a>Service使用</h3> 
    <h4><a name="t102"></a><a id="_3878"></a>实验环境准备</h4> 
    <p>在使用service之前,首先利用Deployment创建出3个pod,注意要为pod设置<code>app=nginx-pod</code>的标签</p> 
    <p>创建deployment.yaml,内容如下:</p> 
    <pre data-index="248" class="set-code-show prettyprint"><code class="prism language-yaml has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token key atrule">apiVersion</span><span class="token punctuation">:</span> <span class="token key atrule">apps/v1kind</span><span class="token punctuation">:</span> <span class="token key atrule">Deployment      metadata</span><span class="token punctuation">:</span>  <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">pc-deployment  namespace</span><span class="token punctuation">:</span> <span class="token key atrule">devspec</span><span class="token punctuation">:</span>   <span class="token key atrule">replicas</span><span class="token punctuation">:</span> <span class="token key atrule">3  selector</span><span class="token punctuation">:</span>    <span class="token key atrule">matchLabels</span><span class="token punctuation">:</span>      <span class="token key atrule">app</span><span class="token punctuation">:</span> <span class="token key atrule">nginx-pod  template</span><span class="token punctuation">:</span>    <span class="token key atrule">metadata</span><span class="token punctuation">:</span>      <span class="token key atrule">labels</span><span class="token punctuation">:</span>        <span class="token key atrule">app</span><span class="token punctuation">:</span> <span class="token key atrule">nginx-pod    spec</span><span class="token punctuation">:</span>      <span class="token key atrule">containers</span><span class="token punctuation">:</span>      <span class="token punctuation">-</span> <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">nginx        image</span><span class="token punctuation">:</span> <span class="token key atrule">nginx:1.17.1        ports</span><span class="token punctuation">:</span>        <span class="token punctuation">-</span> <span class="token key atrule">containerPort</span><span class="token punctuation">:</span> <span class="token number">80</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <pre data-index="249" class="set-code-show prettyprint"><code class="prism language-powershell has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token namespace">[root@master ~]</span><span class="token comment"># kubectl create -f deployment.yamldeployment.apps/pc-deployment created# 查看pod详情[root@master ~]# kubectl get pods -n dev -o wide --show-labelsNAME                             READY   STATUS     IP            NODE     LABELSpc-deployment-66cb59b984-8p84h   1/1     Running    10.244.1.40   node1    app=nginx-podpc-deployment-66cb59b984-vx8vx   1/1     Running    10.244.2.33   node2    app=nginx-podpc-deployment-66cb59b984-wnncx   1/1     Running    10.244.1.39   node1    app=nginx-pod# 为了方便后面的测试,修改下三台nginx的index.html页面(三台修改的IP地址不一致)# kubectl exec -it pc-deployment-66cb59b984-8p84h -n dev /bin/sh# echo "10.244.1.40" > /usr/share/nginx/html/index.html#修改完毕之后,访问测试[root@master ~]# curl 10.244.1.4010.244.1.40[root@master ~]# curl 10.244.2.3310.244.2.33[root@master ~]# curl 10.244.1.3910.244.1.39</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <h4><a name="t103"></a><a id="ClusterIPService_3892"></a>ClusterIP类型的Service</h4> 
    <p>创建service-clusterip.yaml文件</p> 
    <pre data-index="250" class="set-code-show prettyprint"><code class="prism language-yaml has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token key atrule">apiVersion</span><span class="token punctuation">:</span> <span class="token key atrule">v1kind</span><span class="token punctuation">:</span> <span class="token key atrule">Servicemetadata</span><span class="token punctuation">:</span>  <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">service-clusterip  namespace</span><span class="token punctuation">:</span> <span class="token key atrule">devspec</span><span class="token punctuation">:</span>  <span class="token key atrule">selector</span><span class="token punctuation">:</span>    <span class="token key atrule">app</span><span class="token punctuation">:</span> <span class="token key atrule">nginx-pod  clusterIP</span><span class="token punctuation">:</span> 10.97.97.97 <span class="token comment"># service的ip地址,如果不写,默认会生成一个  type: ClusterIP  ports:  - port: 80  # Service端口           targetPort: 80 # pod端口</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <pre data-index="251" class="set-code-show prettyprint"><code class="prism language-powershell has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token comment"># 创建service[root@master ~]# kubectl create -f service-clusterip.yamlservice/service-clusterip created# 查看service[root@master ~]# kubectl get svc -n dev -o wideNAME                TYPE        CLUSTER-IP    EXTERNAL-IP   PORT(S)   AGE   SELECTORservice-clusterip   ClusterIP   10.97.97.97   <none>        80/TCP    13s   app=nginx-pod# 查看service的详细信息# 在这里有一个Endpoints列表,里面就是当前service可以负载到的服务入口[root@master ~]# kubectl describe svc service-clusterip -n devName:              service-clusteripNamespace:         devLabels:            <none>Annotations:       <none>Selector:          app=nginx-podType:              ClusterIPIP:                10.97.97.97Port:              <unset>  80/TCPTargetPort:        80/TCPEndpoints:         10.244.1.39:80,10.244.1.40:80,10.244.2.33:80Session Affinity:  NoneEvents:            <none># 查看ipvs的映射规则[root@master ~]# ipvsadm -LnTCP  10.97.97.97:80 rr  -> 10.244.1.39:80               Masq    1      0          0  -> 10.244.1.40:80               Masq    1      0          0  -> 10.244.2.33:80               Masq    1      0          0# 访问10.97.97.97:80观察效果[root@master ~]# curl 10.97.97.97:8010.244.2.33</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <p><strong>Endpoint</strong></p> 
    <p>​ Endpoint是kubernetes中的一个资源对象,存储在etcd中,用来记录一个service对应的所有pod的访问地址,它是根据service配置文件中selector描述产生的。</p> 
    <p>​ 一个Service由一组Pod组成,这些Pod通过Endpoints暴露出来,<strong>Endpoints是实现实际服务的端点集合</strong>。换句话说,service和pod之间的联系是通过endpoints实现的。</p> 
    <p><img src="https://1000bd.com/contentImg/2024/04/14/947fcbdc04d34135.png" alt="image-20200509191917069"></p> 
    <p><strong>负载分发策略</strong></p> 
    <p>对Service的访问被分发到了后端的Pod上去,目前kubernetes提供了两种负载分发策略:</p> 
    <ul><li> <p>如果不定义,默认使用kube-proxy的策略,比如随机、轮询</p> </li><li> <p>基于客户端地址的会话保持模式,即来自同一个客户端发起的所有请求都会转发到固定的一个Pod上</p> <p>此模式可以使在spec中添加<code>sessionAffinity:ClientIP</code>选项</p> </li></ul> 
    <pre data-index="252" class="set-code-show prettyprint"><code class="prism language-powershell has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token comment"># 查看ipvs的映射规则【rr 轮询】[root@master ~]# ipvsadm -LnTCP  10.97.97.97:80 rr  -> 10.244.1.39:80               Masq    1      0          0  -> 10.244.1.40:80               Masq    1      0          0  -> 10.244.2.33:80               Masq    1      0          0# 循环访问测试[root@master ~]# while true;do curl 10.97.97.97:80; sleep 5; done;10.244.1.4010.244.1.3910.244.2.3310.244.1.4010.244.1.3910.244.2.33# 修改分发策略----sessionAffinity:ClientIP# 查看ipvs规则【persistent 代表持久】[root@master ~]# ipvsadm -LnTCP  10.97.97.97:80 rr persistent 10800  -> 10.244.1.39:80               Masq    1      0          0  -> 10.244.1.40:80               Masq    1      0          0  -> 10.244.2.33:80               Masq    1      0          0# 循环访问测试[root@master ~]# while true;do curl 10.97.97.97; sleep 5; done;10.244.2.3310.244.2.3310.244.2.33  # 删除service[root@master ~]# kubectl delete -f service-clusterip.yamlservice "service-clusterip" deleted</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <h4><a name="t104"></a><a id="HeadLinessService_3926"></a>HeadLiness类型的Service</h4> 
    <p>​ 在某些场景中,开发人员可能不想使用Service提供的负载均衡功能,而希望自己来控制负载均衡策略,针对这种情况,kubernetes提供了HeadLiness Service,这类Service不会分配Cluster IP,如果想要访问service,只能通过service的域名进行查询。</p> 
    <p>创建service-headliness.yaml</p> 
    <pre data-index="253" class="set-code-show prettyprint"><code class="prism language-yaml has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token key atrule">apiVersion</span><span class="token punctuation">:</span> <span class="token key atrule">v1kind</span><span class="token punctuation">:</span> <span class="token key atrule">Servicemetadata</span><span class="token punctuation">:</span>  <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">service-headliness  namespace</span><span class="token punctuation">:</span> <span class="token key atrule">devspec</span><span class="token punctuation">:</span>  <span class="token key atrule">selector</span><span class="token punctuation">:</span>    <span class="token key atrule">app</span><span class="token punctuation">:</span> <span class="token key atrule">nginx-pod  clusterIP</span><span class="token punctuation">:</span> None <span class="token comment"># 将clusterIP设置为None,即可创建headliness Service  type: ClusterIP  ports:  - port: 80        targetPort: 80</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <pre data-index="254" class="set-code-show prettyprint"><code class="prism language-powershell has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token comment"># 创建service[root@master ~]# kubectl create -f service-headliness.yamlservice/service-headliness created# 获取service, 发现CLUSTER-IP未分配[root@master ~]# kubectl get svc service-headliness -n dev -o wideNAME                 TYPE        CLUSTER-IP   EXTERNAL-IP   PORT(S)   AGE   SELECTORservice-headliness   ClusterIP   None         <none>        80/TCP    11s   app=nginx-pod# 查看service详情[root@master ~]# kubectl describe svc service-headliness  -n devName:              service-headlinessNamespace:         devLabels:            <none>Annotations:       <none>Selector:          app=nginx-podType:              ClusterIPIP:                NonePort:              <unset>  80/TCPTargetPort:        80/TCPEndpoints:         10.244.1.39:80,10.244.1.40:80,10.244.2.33:80Session Affinity:  NoneEvents:            <none># 查看域名的解析情况[root@master ~]# kubectl exec -it pc-deployment-66cb59b984-8p84h -n dev /bin/sh/ # cat /etc/resolv.confnameserver 10.96.0.10search dev.svc.cluster.local svc.cluster.local cluster.local[root@master ~]# dig @10.96.0.10 service-headliness.dev.svc.cluster.localservice-headliness.dev.svc.cluster.local. 30 IN A 10.244.1.40service-headliness.dev.svc.cluster.local. 30 IN A 10.244.1.39service-headliness.dev.svc.cluster.local. 30 IN A 10.244.2.33</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <h4><a name="t105"></a><a id="NodePortService_3940"></a>NodePort类型的Service</h4> 
    <p>​ 在之前的样例中,创建的Service的ip地址只有集群内部才可以访问,如果希望将Service暴露给集群外部使用,那么就要使用到另外一种类型的Service,称为NodePort类型。NodePort的工作原理其实就是<strong>将service的端口映射到Node的一个端口上</strong>,然后就可以通过<code>NodeIp:NodePort</code>来访问service了。</p> 
    <img src="https://1000bd.com/contentImg/2024/04/14/34a05804ede3608a.png"> 
    <p>创建service-nodeport.yaml</p> 
    <pre data-index="255" class="set-code-show prettyprint"><code class="prism language-yaml has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token key atrule">apiVersion</span><span class="token punctuation">:</span> <span class="token key atrule">v1kind</span><span class="token punctuation">:</span> <span class="token key atrule">Servicemetadata</span><span class="token punctuation">:</span>  <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">service-nodeport  namespace</span><span class="token punctuation">:</span> <span class="token key atrule">devspec</span><span class="token punctuation">:</span>  <span class="token key atrule">selector</span><span class="token punctuation">:</span>    <span class="token key atrule">app</span><span class="token punctuation">:</span> <span class="token key atrule">nginx-pod  type</span><span class="token punctuation">:</span> NodePort <span class="token comment"># service类型  ports:  - port: 80    nodePort: 30002 # 指定绑定的node的端口(默认的取值范围是:30000-32767), 如果不指定,会默认分配    targetPort: 80</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <pre data-index="256" class="set-code-show prettyprint"><code class="prism language-powershell has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token comment"># 创建service[root@master ~]# kubectl create -f service-nodeport.yamlservice/service-nodeport created# 查看service[root@master ~]# kubectl get svc -n dev -o wideNAME               TYPE       CLUSTER-IP      EXTERNAL-IP   PORT(S)       SELECTORservice-nodeport   NodePort   10.105.64.191   <none>        80:30002/TCP  app=nginx-pod# 接下来可以通过电脑主机的浏览器去访问集群中任意一个nodeip的30002端口,即可访问到pod</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <h4><a name="t106"></a><a id="LoadBalancerService_3956"></a>LoadBalancer类型的Service</h4> 
    <p>​ LoadBalancer和NodePort很相似,目的都是向外部暴露一个端口,区别在于LoadBalancer会在集群的外部再来做一个负载均衡设备,而这个设备需要外部环境支持的,外部服务发送到这个设备上的请求,会被设备负载之后转发到集群中。</p> 
    <img src="https://1000bd.com/contentImg/2024/04/14/a15e30808fe4519b.png"> 
    <h4><a name="t107"></a><a id="ExternalNameService_3962"></a>ExternalName类型的Service</h4> 
    <p>​ ExternalName类型的Service用于引入集群外部的服务,它通过<code>externalName</code>属性指定外部一个服务的地址,然后在集群内部访问此service就可以访问到外部的服务了。</p> 
    <img src="https://1000bd.com/contentImg/2024/04/14/1463ba3dc52a8ae1.png"> 
    <pre data-index="257" class="set-code-show prettyprint"><code class="prism language-yaml has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token key atrule">apiVersion</span><span class="token punctuation">:</span> <span class="token key atrule">v1kind</span><span class="token punctuation">:</span> <span class="token key atrule">Servicemetadata</span><span class="token punctuation">:</span>  <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">service-externalname  namespace</span><span class="token punctuation">:</span> <span class="token key atrule">devspec</span><span class="token punctuation">:</span>  <span class="token key atrule">type</span><span class="token punctuation">:</span> ExternalName <span class="token comment"># service类型  externalName: www.baidu.com  #改成ip地址也可以</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <pre data-index="258" class="set-code-show prettyprint"><code class="prism language-powershell has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token comment"># 创建service[root@master ~]# kubectl  create -f service-externalname.yamlservice/service-externalname created# 域名解析[root@master ~]# dig @10.96.0.10 service-externalname.dev.svc.cluster.localservice-externalname.dev.svc.cluster.local. 30 IN CNAME www.baidu.com.www.baidu.com.          30      IN      CNAME   www.a.shifen.com.www.a.shifen.com.       30      IN      A       39.156.66.18www.a.shifen.com.       30      IN      A       39.156.66.14</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <h3><a name="t108"></a><a id="Ingress_3976"></a>Ingress介绍</h3> 
    <p>​ 在前面课程中已经提到,Service对集群之外暴露服务的主要方式有两种:NotePort和LoadBalancer,但是这两种方式,都有一定的缺点:</p> 
    <ul><li>NodePort方式的缺点是会占用很多集群机器的端口,那么当集群服务变多的时候,这个缺点就愈发明显</li><li>LB方式的缺点是每个service需要一个LB,浪费、麻烦,并且需要kubernetes之外设备的支持</li></ul> 
    <p>​ 基于这种现状,kubernetes提供了Ingress资源对象,Ingress只需要一个NodePort或者一个LB就可以满足暴露多个Service的需求。工作机制大致如下图表示:</p> 
    <img src="https://1000bd.com/contentImg/2024/04/14/6193447848783c54.png"> 
    <p>​ 实际上,Ingress相当于一个7层的负载均衡器,是kubernetes对反向代理的一个抽象,它的工作原理类似于Nginx,可以理解成在<strong>Ingress里建立诸多映射规则,Ingress Controller通过监听这些配置规则并转化成Nginx的反向代理配置 , 然后对外部提供服务</strong>。在这里有两个核心概念:</p> 
    <ul><li>ingress:kubernetes中的一个对象,作用是定义请求如何转发到service的规则</li><li>ingress controller:具体实现反向代理及负载均衡的程序,对ingress定义的规则进行解析,根据配置的规则来实现请求转发,实现方式有很多,比如Nginx, Contour, Haproxy等等</li></ul> 
    <p>Ingress(以Nginx为例)的工作原理如下:</p> 
    <ol><li>用户编写Ingress规则,说明哪个域名对应kubernetes集群中的哪个Service</li><li>Ingress控制器动态感知Ingress服务规则的变化,然后生成一段对应的Nginx反向代理配置</li><li>Ingress控制器会将生成的Nginx配置写入到一个运行着的Nginx服务中,并动态更新</li><li>到此为止,其实真正在工作的就是一个Nginx了,内部配置了用户定义的请求转发规则</li></ol> 
    <img src="https://1000bd.com/contentImg/2024/04/14/aa7510db9b5f4b8c.png"> 
    <h3><a name="t109"></a><a id="Ingress_4001"></a>Ingress使用</h3> 
    <h4><a name="t110"></a><a id="_4003"></a>环境准备</h4> 
    <p><strong>搭建ingress环境</strong></p> 
    <pre data-index="259" class="set-code-show prettyprint"><code class="prism language-powershell has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token comment"># 创建文件夹[root@master ~]# mkdir ingress-controller[root@master ~]# cd ingress-controller/# 获取ingress-nginx,本次案例使用的是0.30版本[root@master ingress-controller]# wget https://raw.githubusercontent.com/kubernetes/ingress-nginx/nginx-0.30.0/deploy/static/mandatory.yaml[root@master ingress-controller]# wget https://raw.githubusercontent.com/kubernetes/ingress-nginx/nginx-0.30.0/deploy/static/provider/baremetal/service-nodeport.yaml# 修改mandatory.yaml文件中的仓库# 修改quay.io/kubernetes-ingress-controller/nginx-ingress-controller:0.30.0# 为quay-mirror.qiniu.com/kubernetes-ingress-controller/nginx-ingress-controller:0.30.0# 创建ingress-nginx[root@master ingress-controller]# kubectl apply -f ./# 查看ingress-nginx[root@master ingress-controller]# kubectl get pod -n ingress-nginxNAME                                           READY   STATUS    RESTARTS   AGEpod/nginx-ingress-controller-fbf967dd5-4qpbp   1/1     Running   0          12h# 查看service[root@master ingress-controller]# kubectl get svc -n ingress-nginxNAME            TYPE       CLUSTER-IP     EXTERNAL-IP   PORT(S)                      AGEingress-nginx   NodePort   10.98.75.163   <none>        80:32240/TCP,443:31335/TCP   11h</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <p><strong>准备service和pod</strong></p> 
    <p>为了后面的实验比较方便,创建如下图所示的模型</p> 
    <img src="https://1000bd.com/contentImg/2024/04/14/64659a15db380a05.png"> 
    <p>创建tomcat-nginx.yaml</p> 
    <pre data-index="260" class="set-code-show prettyprint"><code class="prism language-yaml has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token key atrule">apiVersion</span><span class="token punctuation">:</span> <span class="token key atrule">apps/v1kind</span><span class="token punctuation">:</span> <span class="token key atrule">Deploymentmetadata</span><span class="token punctuation">:</span>  <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">nginx-deployment  namespace</span><span class="token punctuation">:</span> <span class="token key atrule">devspec</span><span class="token punctuation">:</span>  <span class="token key atrule">replicas</span><span class="token punctuation">:</span> <span class="token key atrule">3  selector</span><span class="token punctuation">:</span>    <span class="token key atrule">matchLabels</span><span class="token punctuation">:</span>      <span class="token key atrule">app</span><span class="token punctuation">:</span> <span class="token key atrule">nginx-pod  template</span><span class="token punctuation">:</span>    <span class="token key atrule">metadata</span><span class="token punctuation">:</span>      <span class="token key atrule">labels</span><span class="token punctuation">:</span>        <span class="token key atrule">app</span><span class="token punctuation">:</span> <span class="token key atrule">nginx-pod    spec</span><span class="token punctuation">:</span>      <span class="token key atrule">containers</span><span class="token punctuation">:</span>      <span class="token punctuation">-</span> <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">nginx        image</span><span class="token punctuation">:</span> <span class="token key atrule">nginx:1.17.1        ports</span><span class="token punctuation">:</span>        <span class="token punctuation">-</span> <span class="token key atrule">containerPort</span><span class="token punctuation">:</span> <span class="token key atrule">80---apiVersion</span><span class="token punctuation">:</span> <span class="token key atrule">apps/v1kind</span><span class="token punctuation">:</span> <span class="token key atrule">Deploymentmetadata</span><span class="token punctuation">:</span>  <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">tomcat-deployment  namespace</span><span class="token punctuation">:</span> <span class="token key atrule">devspec</span><span class="token punctuation">:</span>  <span class="token key atrule">replicas</span><span class="token punctuation">:</span> <span class="token key atrule">3  selector</span><span class="token punctuation">:</span>    <span class="token key atrule">matchLabels</span><span class="token punctuation">:</span>      <span class="token key atrule">app</span><span class="token punctuation">:</span> <span class="token key atrule">tomcat-pod  template</span><span class="token punctuation">:</span>    <span class="token key atrule">metadata</span><span class="token punctuation">:</span>      <span class="token key atrule">labels</span><span class="token punctuation">:</span>        <span class="token key atrule">app</span><span class="token punctuation">:</span> <span class="token key atrule">tomcat-pod    spec</span><span class="token punctuation">:</span>      <span class="token key atrule">containers</span><span class="token punctuation">:</span>      <span class="token punctuation">-</span> <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">tomcat        image</span><span class="token punctuation">:</span> <span class="token key atrule">tomcat:8.5-jre10-slim        ports</span><span class="token punctuation">:</span>        <span class="token punctuation">-</span> <span class="token key atrule">containerPort</span><span class="token punctuation">:</span> <span class="token key atrule">8080---apiVersion</span><span class="token punctuation">:</span> <span class="token key atrule">v1kind</span><span class="token punctuation">:</span> <span class="token key atrule">Servicemetadata</span><span class="token punctuation">:</span>  <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">nginx-service  namespace</span><span class="token punctuation">:</span> <span class="token key atrule">devspec</span><span class="token punctuation">:</span>  <span class="token key atrule">selector</span><span class="token punctuation">:</span>    <span class="token key atrule">app</span><span class="token punctuation">:</span> <span class="token key atrule">nginx-pod  clusterIP</span><span class="token punctuation">:</span> <span class="token key atrule">None  type</span><span class="token punctuation">:</span> <span class="token key atrule">ClusterIP  ports</span><span class="token punctuation">:</span>  <span class="token punctuation">-</span> <span class="token key atrule">port</span><span class="token punctuation">:</span> <span class="token key atrule">80    targetPort</span><span class="token punctuation">:</span> <span class="token key atrule">80---apiVersion</span><span class="token punctuation">:</span> <span class="token key atrule">v1kind</span><span class="token punctuation">:</span> <span class="token key atrule">Servicemetadata</span><span class="token punctuation">:</span>  <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">tomcat-service  namespace</span><span class="token punctuation">:</span> <span class="token key atrule">devspec</span><span class="token punctuation">:</span>  <span class="token key atrule">selector</span><span class="token punctuation">:</span>    <span class="token key atrule">app</span><span class="token punctuation">:</span> <span class="token key atrule">tomcat-pod  clusterIP</span><span class="token punctuation">:</span> <span class="token key atrule">None  type</span><span class="token punctuation">:</span> <span class="token key atrule">ClusterIP  ports</span><span class="token punctuation">:</span>  <span class="token punctuation">-</span> <span class="token key atrule">port</span><span class="token punctuation">:</span> <span class="token key atrule">8080    targetPort</span><span class="token punctuation">:</span> <span class="token number">8080</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <pre data-index="261" class="set-code-show prettyprint"><code class="prism language-powershell has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token comment"># 创建[root@master ~]# kubectl create -f tomcat-nginx.yaml# 查看[root@master ~]# kubectl get svc -n devNAME             TYPE        CLUSTER-IP   EXTERNAL-IP   PORT(S)    AGEnginx-service    ClusterIP   None         <none>        80/TCP     48stomcat-service   ClusterIP   None         <none>        8080/TCP   48s</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <h4><a name="t111"></a><a id="Http_4027"></a>Http代理</h4> 
    <p>创建ingress-http.yaml</p> 
    <pre data-index="262" class="set-code-show prettyprint"><code class="prism language-yaml has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token key atrule">apiVersion</span><span class="token punctuation">:</span> <span class="token key atrule">extensions/v1beta1kind</span><span class="token punctuation">:</span> <span class="token key atrule">Ingressmetadata</span><span class="token punctuation">:</span>  <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">ingress-http  namespace</span><span class="token punctuation">:</span> <span class="token key atrule">devspec</span><span class="token punctuation">:</span>  <span class="token key atrule">rules</span><span class="token punctuation">:</span>  <span class="token punctuation">-</span> <span class="token key atrule">host</span><span class="token punctuation">:</span> <span class="token key atrule">nginx.itheima.com    http</span><span class="token punctuation">:</span>      <span class="token key atrule">paths</span><span class="token punctuation">:</span>      <span class="token punctuation">-</span> <span class="token key atrule">path</span><span class="token punctuation">:</span> <span class="token key atrule">/        backend</span><span class="token punctuation">:</span>          <span class="token key atrule">serviceName</span><span class="token punctuation">:</span> <span class="token key atrule">nginx-service          servicePort</span><span class="token punctuation">:</span> <span class="token key atrule">80  - host</span><span class="token punctuation">:</span> <span class="token key atrule">tomcat.itheima.com    http</span><span class="token punctuation">:</span>      <span class="token key atrule">paths</span><span class="token punctuation">:</span>      <span class="token punctuation">-</span> <span class="token key atrule">path</span><span class="token punctuation">:</span> <span class="token key atrule">/        backend</span><span class="token punctuation">:</span>          <span class="token key atrule">serviceName</span><span class="token punctuation">:</span> <span class="token key atrule">tomcat-service          servicePort</span><span class="token punctuation">:</span> <span class="token number">8080</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <pre data-index="263" class="set-code-show prettyprint"><code class="prism language-powershell has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token comment"># 创建[root@master ~]# kubectl create -f ingress-http.yamlingress.extensions/ingress-http created# 查看[root@master ~]# kubectl get ing ingress-http -n devNAME           HOSTS                                  ADDRESS   PORTS   AGEingress-http   nginx.itheima.com,tomcat.itheima.com             80      22s# 查看详情[root@master ~]# kubectl describe ing ingress-http  -n dev...Rules:Host                Path  Backends----                ----  --------nginx.itheima.com   / nginx-service:80 (10.244.1.96:80,10.244.1.97:80,10.244.2.112:80)tomcat.itheima.com  / tomcat-service:8080(10.244.1.94:8080,10.244.1.95:8080,10.244.2.111:8080)...# 接下来,在本地电脑上配置host文件,解析上面的两个域名到192.168.109.100(master)上# 然后,就可以分别访问tomcat.itheima.com:32240  和  nginx.itheima.com:32240 查看效果了</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <h4><a name="t112"></a><a id="Https_4039"></a>Https代理</h4> 
    <p>创建证书</p> 
    <pre data-index="264" class="set-code-show prettyprint"><code class="prism language-powershell has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token comment"># 生成证书openssl req -x509 -sha256 -nodes -days 365 -newkey rsa:2048 -keyout tls.key -out tls.crt -subj "/C=CN/ST=BJ/L=BJ/O=nginx/CN=itheima.com"# 创建密钥kubectl create secret tls tls-secret --key tls.key --cert tls.crt</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <p>创建ingress-https.yaml</p> 
    <pre data-index="265" class="set-code-show prettyprint"><code class="prism language-yaml has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token key atrule">apiVersion</span><span class="token punctuation">:</span> <span class="token key atrule">extensions/v1beta1kind</span><span class="token punctuation">:</span> <span class="token key atrule">Ingressmetadata</span><span class="token punctuation">:</span>  <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">ingress-https  namespace</span><span class="token punctuation">:</span> <span class="token key atrule">devspec</span><span class="token punctuation">:</span>  <span class="token key atrule">tls</span><span class="token punctuation">:</span>    <span class="token punctuation">-</span> <span class="token key atrule">hosts</span><span class="token punctuation">:</span>      <span class="token punctuation">-</span> <span class="token key atrule">nginx.itheima.com      - tomcat.itheima.com      secretName</span><span class="token punctuation">:</span> tls<span class="token punctuation">-</span>secret <span class="token comment"># 指定秘钥  rules:  - host: nginx.itheima.com    http:      paths:      - path: /        backend:          serviceName: nginx-service          servicePort: 80  - host: tomcat.itheima.com    http:      paths:      - path: /        backend:          serviceName: tomcat-service          servicePort: 8080</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <pre data-index="266" class="set-code-show prettyprint"><code class="prism language-powershell has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token comment"># 创建[root@master ~]# kubectl create -f ingress-https.yamlingress.extensions/ingress-https created# 查看[root@master ~]# kubectl get ing ingress-https -n devNAME            HOSTS                                  ADDRESS         PORTS     AGEingress-https   nginx.itheima.com,tomcat.itheima.com   10.104.184.38   80, 443   2m42s# 查看详情[root@master ~]# kubectl describe ing ingress-https -n dev...TLS:  tls-secret terminates nginx.itheima.com,tomcat.itheima.comRules:Host              Path Backends----              ---- --------nginx.itheima.com  /  nginx-service:80 (10.244.1.97:80,10.244.1.98:80,10.244.2.119:80)tomcat.itheima.com /  tomcat-service:8080(10.244.1.99:8080,10.244.2.117:8080,10.244.2.120:8080)...# 下面可以通过浏览器访问https://nginx.itheima.com:31335 和 https://tomcat.itheima.com:31335来查看了</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <h2><a name="t113"></a><a id="__4057"></a>第八章 数据存储</h2> 
    <p>​ 在前面已经提到,容器的生命周期可能很短,会被频繁地创建和销毁。那么容器在销毁时,保存在容器中的数据也会被清除。这种结果对用户来说,在某些情况下是不乐意看到的。为了持久化保存容器的数据,kubernetes引入了Volume的概念。</p> 
    <p>​ Volume是Pod中能够被多个容器访问的共享目录,它被定义在Pod上,然后被一个Pod里的多个容器挂载到具体的文件目录下,kubernetes通过Volume实现同一个Pod中不同容器之间的数据共享以及数据的持久化存储。Volume的生命容器不与Pod中单个容器的生命周期相关,当容器终止或者重启时,Volume中的数据也不会丢失。</p> 
    <p>kubernetes的Volume支持多种类型,比较常见的有下面几个:</p> 
    <ul><li>简单存储:EmptyDir、HostPath、NFS</li><li>高级存储:PV、PVC</li><li>配置存储:ConfigMap、Secret</li></ul> 
    <h3><a name="t114"></a><a id="_4069"></a>基本存储</h3> 
    <h4><a name="t115"></a><a id="EmptyDir_4071"></a>EmptyDir</h4> 
    <p>​ EmptyDir是最基础的Volume类型,一个EmptyDir就是Host上的一个空目录。</p> 
    <p>​ EmptyDir是在Pod被分配到Node时创建的,它的初始内容为空,并且无须指定宿主机上对应的目录文件,因为kubernetes会自动分配一个目录,当Pod销毁时, EmptyDir中的数据也会被永久删除。 EmptyDir用途如下:</p> 
    <ul><li> <p>临时空间,例如用于某些应用程序运行时所需的临时目录,且无须永久保留</p> </li><li> <p>一个容器需要从另一个容器中获取数据的目录(多容器共享目录)</p> </li></ul> 
    <p>接下来,通过一个容器之间文件共享的案例来使用一下EmptyDir。</p> 
    <p>​ 在一个Pod中准备两个容器nginx和busybox,然后声明一个Volume分别挂在到两个容器的目录中,然后nginx容器负责向Volume中写日志,busybox中通过命令将日志内容读到控制台。</p> 
    <img src="https://1000bd.com/contentImg/2024/04/13/4577e21f747b8aac.png"> 
    <p>创建一个volume-emptydir.yaml</p> 
    <pre data-index="267" class="set-code-show prettyprint"><code class="prism language-yaml has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token key atrule">apiVersion</span><span class="token punctuation">:</span> <span class="token key atrule">v1kind</span><span class="token punctuation">:</span> <span class="token key atrule">Podmetadata</span><span class="token punctuation">:</span>  <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">volume-emptydir  namespace</span><span class="token punctuation">:</span> <span class="token key atrule">devspec</span><span class="token punctuation">:</span>  <span class="token key atrule">containers</span><span class="token punctuation">:</span>  <span class="token punctuation">-</span> <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">nginx    image</span><span class="token punctuation">:</span> <span class="token key atrule">nginx:1.14-alpine    ports</span><span class="token punctuation">:</span>    <span class="token punctuation">-</span> <span class="token key atrule">containerPort</span><span class="token punctuation">:</span> <span class="token key atrule">80    volumeMounts</span><span class="token punctuation">:</span>  <span class="token comment"># 将logs-volume挂在到nginx容器中,对应的目录为 /var/log/nginx    - name: logs-volume      mountPath: /var/log/nginx  - name: busybox    image: busybox:1.30    command: ["/bin/sh","-c","tail -f /logs/access.log"] # 初始命令,动态读取指定文件中内容    volumeMounts:  # 将logs-volume 挂在到busybox容器中,对应的目录为 /logs    - name: logs-volume      mountPath: /logs  volumes: # 声明volume, name为logs-volume,类型为emptyDir  - name: logs-volume    emptyDir: {}</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <pre data-index="268" class="set-code-show prettyprint"><code class="prism language-powershell has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token comment"># 创建Pod[root@master ~]# kubectl create -f volume-emptydir.yamlpod/volume-emptydir created# 查看pod[root@master ~]# kubectl get pods volume-emptydir -n dev -o wideNAME                  READY   STATUS    RESTARTS   AGE   IP             NODE   ...... volume-emptydir   2/2     Running   0          97s   10.244.1.100   node1  ......# 通过podIp访问nginx[root@master ~]# curl 10.244.1.100......# 通过kubectl logs命令查看指定容器的标准输出[root@master ~]# kubectl logs -f volume-emptydir -n dev -c busybox10.244.0.0 - - [13/Apr/2020:10:58:47 +0000] "GET / HTTP/1.1" 200 612 "-" "curl/7.29.0" "-"</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <h4><a name="t116"></a><a id="HostPath_4097"></a>HostPath</h4> 
    <p>​ 上节课提到,EmptyDir中数据不会被持久化,它会随着Pod的结束而销毁,如果想简单的将数据持久化到主机中,可以选择HostPath。</p> 
    <p>​ HostPath就是将Node主机中一个实际目录挂在到Pod中,以供容器使用,这样的设计就可以保证Pod销毁了,但是数据依据可以存在于Node主机上。</p> 
    <img src="https://1000bd.com/contentImg/2024/04/13/c2b8c6b031d544ce.png"> 
    <p>创建一个volume-hostpath.yaml:</p> 
    <pre data-index="269" class="set-code-show prettyprint"><code class="prism language-yaml has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token key atrule">apiVersion</span><span class="token punctuation">:</span> <span class="token key atrule">v1kind</span><span class="token punctuation">:</span> <span class="token key atrule">Podmetadata</span><span class="token punctuation">:</span>  <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">volume-hostpath  namespace</span><span class="token punctuation">:</span> <span class="token key atrule">devspec</span><span class="token punctuation">:</span>  <span class="token key atrule">containers</span><span class="token punctuation">:</span>  <span class="token punctuation">-</span> <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">nginx    image</span><span class="token punctuation">:</span> <span class="token key atrule">nginx:1.17.1    ports</span><span class="token punctuation">:</span>    <span class="token punctuation">-</span> <span class="token key atrule">containerPort</span><span class="token punctuation">:</span> <span class="token key atrule">80    volumeMounts</span><span class="token punctuation">:</span>    <span class="token punctuation">-</span> <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">logs-volume      mountPath</span><span class="token punctuation">:</span> <span class="token key atrule">/var/log/nginx  - name</span><span class="token punctuation">:</span> <span class="token key atrule">busybox    image</span><span class="token punctuation">:</span> <span class="token key atrule">busybox:1.30    command</span><span class="token punctuation">:</span> <span class="token punctuation">[</span><span class="token string">"/bin/sh"</span><span class="token punctuation">,</span><span class="token string">"-c"</span><span class="token punctuation">,</span><span class="token string">"tail -f /logs/access.log"</span><span class="token punctuation">]</span>    volumeMounts<span class="token punctuation">:</span>    <span class="token punctuation">-</span> <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">logs-volume      mountPath</span><span class="token punctuation">:</span> <span class="token key atrule">/logs  volumes</span><span class="token punctuation">:</span>  <span class="token punctuation">-</span> <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">logs-volume    hostPath</span><span class="token punctuation">:</span>       <span class="token key atrule">path</span><span class="token punctuation">:</span> <span class="token key atrule">/root/logs      type</span><span class="token punctuation">:</span> DirectoryOrCreate  <span class="token comment"># 目录存在就使用,不存在就先创建后使用</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <pre data-index="270" class="set-code-show prettyprint"><code class="prism language-markdown has-numbering" onclick="mdcp.signin(event)" style="position: unset;">关于type的值的一点说明:	DirectoryOrCreate 目录存在就使用,不存在就先创建后使用	Directory	目录必须存在	FileOrCreate  文件存在就使用,不存在就先创建后使用	File 文件必须存在	    Socket	unix套接字必须存在	CharDevice	字符设备必须存在	BlockDevice 块设备必须存在
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <pre data-index="271" class="set-code-show prettyprint"><code class="prism language-powershell has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token comment"># 创建Pod[root@master ~]# kubectl create -f volume-hostpath.yamlpod/volume-hostpath created# 查看Pod[root@master ~]# kubectl get pods volume-hostpath -n dev -o wideNAME                  READY   STATUS    RESTARTS   AGE   IP             NODE   ......pod-volume-hostpath   2/2     Running   0          16s   10.244.1.104   node1  ......#访问nginx[root@master ~]# curl 10.244.1.104# 接下来就可以去host的/root/logs目录下查看存储的文件了###  注意: 下面的操作需要到Pod所在的节点运行(案例中是node1)[root@node1 ~]# ls /root/logs/access.log  error.log# 同样的道理,如果在此目录下创建一个文件,到容器中也是可以看到的</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <h4><a name="t117"></a><a id="NFS_4119"></a>NFS</h4> 
    <p>​ HostPath可以解决数据持久化的问题,但是一旦Node节点故障了,Pod如果转移到了别的节点,又会出现问题了,此时需要准备单独的网络存储系统,比较常用的用NFS、CIFS。</p> 
    <p>​ NFS是一个网络文件存储系统,可以搭建一台NFS服务器,然后将Pod中的存储直接连接到NFS系统上,这样的话,无论Pod在节点上怎么转移,只要Node跟NFS的对接没问题,数据就可以成功访问。</p> 
    <img src="https://1000bd.com/contentImg/2024/04/13/add9ac0a82e075f6.png"> 
    <p>1)首先要准备nfs的服务器,这里为了简单,直接是master节点做nfs服务器</p> 
    <pre data-index="272" class="set-code-show prettyprint"><code class="prism language-powershell has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token comment"># 在master上安装nfs服务[root@master ~]# yum install nfs-utils -y# 准备一个共享目录[root@master ~]# mkdir /root/data/nfs -pv# 将共享目录以读写权限暴露给192.168.109.0/24网段中的所有主机[root@master ~]# vim /etc/exports[root@master ~]# more /etc/exports/root/data/nfs     192.168.109.0/24(rw,no_root_squash)# 启动nfs服务[root@master ~]# systemctl start nfs</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <p>2)接下来,要在的每个node节点上都安装下nfs,这样的目的是为了node节点可以驱动nfs设备</p> 
    <pre data-index="273" class="set-code-show prettyprint"><code class="prism language-powershell has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token comment"># 在node上安装nfs服务,注意不需要启动[root@master ~]# yum install nfs-utils -y</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <p>3)接下来,就可以编写pod的配置文件了,创建volume-nfs.yaml</p> 
    <pre data-index="274" class="set-code-show prettyprint"><code class="prism language-yaml has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token key atrule">apiVersion</span><span class="token punctuation">:</span> <span class="token key atrule">v1kind</span><span class="token punctuation">:</span> <span class="token key atrule">Podmetadata</span><span class="token punctuation">:</span>  <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">volume-nfs  namespace</span><span class="token punctuation">:</span> <span class="token key atrule">devspec</span><span class="token punctuation">:</span>  <span class="token key atrule">containers</span><span class="token punctuation">:</span>  <span class="token punctuation">-</span> <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">nginx    image</span><span class="token punctuation">:</span> <span class="token key atrule">nginx:1.17.1    ports</span><span class="token punctuation">:</span>    <span class="token punctuation">-</span> <span class="token key atrule">containerPort</span><span class="token punctuation">:</span> <span class="token key atrule">80    volumeMounts</span><span class="token punctuation">:</span>    <span class="token punctuation">-</span> <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">logs-volume      mountPath</span><span class="token punctuation">:</span> <span class="token key atrule">/var/log/nginx  - name</span><span class="token punctuation">:</span> <span class="token key atrule">busybox    image</span><span class="token punctuation">:</span> <span class="token key atrule">busybox:1.30    command</span><span class="token punctuation">:</span> <span class="token punctuation">[</span><span class="token string">"/bin/sh"</span><span class="token punctuation">,</span><span class="token string">"-c"</span><span class="token punctuation">,</span><span class="token string">"tail -f /logs/access.log"</span><span class="token punctuation">]</span>     volumeMounts<span class="token punctuation">:</span>    <span class="token punctuation">-</span> <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">logs-volume      mountPath</span><span class="token punctuation">:</span> <span class="token key atrule">/logs  volumes</span><span class="token punctuation">:</span>  <span class="token punctuation">-</span> <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">logs-volume    nfs</span><span class="token punctuation">:</span>      <span class="token key atrule">server</span><span class="token punctuation">:</span> 192.168.109.100  <span class="token comment">#nfs服务器地址      path: /root/data/nfs #共享文件路径</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <p>4)最后,运行下pod,观察结果</p> 
    <pre data-index="275" class="set-code-show prettyprint"><code class="prism language-powershell has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token comment"># 创建pod[root@master ~]# kubectl create -f volume-nfs.yamlpod/volume-nfs created# 查看pod[root@master ~]# kubectl get pods volume-nfs -n devNAME                  READY   STATUS    RESTARTS   AGEvolume-nfs        2/2     Running   0          2m9s# 查看nfs服务器上的共享目录,发现已经有文件了[root@master ~]# ls /root/data/access.log  error.log</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <p>##高级存储</p> 
    <h4><a name="t118"></a><a id="PVPVC_4153"></a>PV和PVC</h4> 
    <p>​ 前面已经学习了使用NFS提供存储,此时就要求用户会搭建NFS系统,并且会在yaml配置nfs。由于kubernetes支持的存储系统有很多,要求客户全都掌握,显然不现实。为了能够屏蔽底层存储实现的细节,方便用户使用, kubernetes引入PV和PVC两种资源对象。</p> 
    <p>​ PV(Persistent Volume)是持久化卷的意思,是对底层的共享存储的一种抽象。一般情况下PV由kubernetes管理员进行创建和配置,它与底层具体的共享存储技术有关,并通过插件完成与共享存储的对接。</p> 
    <p>​ PVC(Persistent Volume Claim)是持久卷声明的意思,是用户对于存储需求的一种声明。换句话说,PVC其实就是用户向kubernetes系统发出的一种资源需求申请。</p> 
    <img src="https://1000bd.com/contentImg/2024/04/13/42ad912bf51dad85.png"> 
    <p>使用了PV和PVC之后,工作可以得到进一步的细分:</p> 
    <ul><li>存储:存储工程师维护</li><li>PV: kubernetes管理员维护</li><li>PVC:kubernetes用户维护</li></ul> 
    <h4><a name="t119"></a><a id="PV_4169"></a>PV</h4> 
    <p>PV是存储资源的抽象,下面是资源清单文件:</p> 
    <pre data-index="276" class="set-code-show prettyprint"><code class="prism language-yaml has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token key atrule">apiVersion</span><span class="token punctuation">:</span> <span class="token key atrule">v1  kind</span><span class="token punctuation">:</span> <span class="token key atrule">PersistentVolumemetadata</span><span class="token punctuation">:</span>  <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">pv2spec</span><span class="token punctuation">:</span>  <span class="token key atrule">nfs</span><span class="token punctuation">:</span> <span class="token comment"># 存储类型,与底层真正存储对应  capacity:  # 存储能力,目前只支持存储空间的设置    storage: 2Gi  accessModes:  # 访问模式  storageClassName: # 存储类别  persistentVolumeReclaimPolicy: # 回收策略</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <p>PV 的关键配置参数说明:</p> 
    <ul><li> <p><strong>存储类型</strong></p> <p>底层实际存储的类型,kubernetes支持多种存储类型,每种存储类型的配置都有所差异</p> </li><li> <p><strong>存储能力(capacity)</strong></p> </li></ul> 
    <p>​ 目前只支持存储空间的设置( storage=1Gi ),不过未来可能会加入IOPS、吞吐量等指标的配置</p> 
    <ul><li> <p><strong>访问模式(accessModes)</strong></p> <p>用于描述用户应用对存储资源的访问权限,访问权限包括下面几种方式:</p> 
      <ul><li>ReadWriteOnce(RWO):读写权限,但是只能被单个节点挂载</li><li>ReadOnlyMany(ROX): 只读权限,可以被多个节点挂载</li><li>ReadWriteMany(RWX):读写权限,可以被多个节点挂载</li></ul> <p><code>需要注意的是,底层不同的存储类型可能支持的访问模式不同</code></p> </li><li> <p><strong>回收策略(persistentVolumeReclaimPolicy)</strong></p> <p>当PV不再被使用了之后,对其的处理方式。目前支持三种策略:</p> 
      <ul><li>Retain (保留) 保留数据,需要管理员手工清理数据</li><li>Recycle(回收) 清除 PV 中的数据,效果相当于执行 rm -rf /thevolume/*</li><li>Delete (删除) 与 PV 相连的后端存储完成 volume 的删除操作,当然这常见于云服务商的存储服务</li></ul> <p><code>需要注意的是,底层不同的存储类型可能支持的回收策略不同</code></p> </li><li> <p><strong>存储类别</strong></p> <p>PV可以通过storageClassName参数指定一个存储类别</p> 
      <ul><li> <p>具有特定类别的PV只能与请求了该类别的PVC进行绑定</p> </li><li> <p>未设定类别的PV则只能与不请求任何类别的PVC进行绑定</p> </li></ul> </li><li> <p><strong>状态(status)</strong></p> <p>一个 PV 的生命周期中,可能会处于4中不同的阶段:</p> 
      <ul><li>Available(可用): 表示可用状态,还未被任何 PVC 绑定</li><li>Bound(已绑定): 表示 PV 已经被 PVC 绑定</li><li>Released(已释放): 表示 PVC 被删除,但是资源还未被集群重新声明</li><li>Failed(失败): 表示该 PV 的自动回收失败</li></ul> </li></ul> 
    <p><strong>实验</strong></p> 
    <p>使用NFS作为存储,来演示PV的使用,创建3个PV,对应NFS中的3个暴露的路径。</p> 
    <ol><li>准备NFS环境</li></ol> 
    <pre data-index="277" class="set-code-show prettyprint"><code class="prism language-powershell has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token comment"># 创建目录[root@master ~]# mkdir /root/data/{pv1,pv2,pv3} -pv# 暴露服务[root@master ~]# more /etc/exports/root/data/pv1     192.168.109.0/24(rw,no_root_squash)/root/data/pv2     192.168.109.0/24(rw,no_root_squash)/root/data/pv3     192.168.109.0/24(rw,no_root_squash)# 重启服务[root@master ~]#  systemctl restart nfs</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <ol start="2"><li>创建pv.yaml</li></ol> 
    <pre data-index="278" class="set-code-show prettyprint"><code class="prism language-yaml has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token key atrule">apiVersion</span><span class="token punctuation">:</span> <span class="token key atrule">v1kind</span><span class="token punctuation">:</span> <span class="token key atrule">PersistentVolumemetadata</span><span class="token punctuation">:</span>  <span class="token key atrule">name</span><span class="token punctuation">:</span>  <span class="token key atrule">pv1spec</span><span class="token punctuation">:</span>  <span class="token key atrule">capacity</span><span class="token punctuation">:</span>     <span class="token key atrule">storage</span><span class="token punctuation">:</span> <span class="token key atrule">1Gi  accessModes</span><span class="token punctuation">:</span>  <span class="token punctuation">-</span> <span class="token key atrule">ReadWriteMany  persistentVolumeReclaimPolicy</span><span class="token punctuation">:</span> <span class="token key atrule">Retain  nfs</span><span class="token punctuation">:</span>    <span class="token key atrule">path</span><span class="token punctuation">:</span> <span class="token key atrule">/root/data/pv1    server</span><span class="token punctuation">:</span> <span class="token key atrule">192.168.109.100---apiVersion</span><span class="token punctuation">:</span> <span class="token key atrule">v1kind</span><span class="token punctuation">:</span> <span class="token key atrule">PersistentVolumemetadata</span><span class="token punctuation">:</span>  <span class="token key atrule">name</span><span class="token punctuation">:</span>  <span class="token key atrule">pv2spec</span><span class="token punctuation">:</span>  <span class="token key atrule">capacity</span><span class="token punctuation">:</span>     <span class="token key atrule">storage</span><span class="token punctuation">:</span> <span class="token key atrule">2Gi  accessModes</span><span class="token punctuation">:</span>  <span class="token punctuation">-</span> <span class="token key atrule">ReadWriteMany  persistentVolumeReclaimPolicy</span><span class="token punctuation">:</span> <span class="token key atrule">Retain  nfs</span><span class="token punctuation">:</span>    <span class="token key atrule">path</span><span class="token punctuation">:</span> <span class="token key atrule">/root/data/pv2    server</span><span class="token punctuation">:</span> <span class="token key atrule">192.168.109.100    ---apiVersion</span><span class="token punctuation">:</span> <span class="token key atrule">v1kind</span><span class="token punctuation">:</span> <span class="token key atrule">PersistentVolumemetadata</span><span class="token punctuation">:</span>  <span class="token key atrule">name</span><span class="token punctuation">:</span>  <span class="token key atrule">pv3spec</span><span class="token punctuation">:</span>  <span class="token key atrule">capacity</span><span class="token punctuation">:</span>     <span class="token key atrule">storage</span><span class="token punctuation">:</span> <span class="token key atrule">3Gi  accessModes</span><span class="token punctuation">:</span>  <span class="token punctuation">-</span> <span class="token key atrule">ReadWriteMany  persistentVolumeReclaimPolicy</span><span class="token punctuation">:</span> <span class="token key atrule">Retain  nfs</span><span class="token punctuation">:</span>    <span class="token key atrule">path</span><span class="token punctuation">:</span> <span class="token key atrule">/root/data/pv3    server</span><span class="token punctuation">:</span> 192.168.109.100
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <pre data-index="279" class="set-code-show prettyprint"><code class="prism language-powershell has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token comment"># 创建 pv[root@master ~]# kubectl create -f pv.yamlpersistentvolume/pv1 createdpersistentvolume/pv2 createdpersistentvolume/pv3 created# 查看pv[root@master ~]# kubectl get pv -o wideNAME   CAPACITY   ACCESS MODES  RECLAIM POLICY  STATUS      AGE   VOLUMEMODEpv1    1Gi        RWX            Retain        Available    10s   Filesystempv2    2Gi        RWX            Retain        Available    10s   Filesystempv3    3Gi        RWX            Retain        Available    9s    Filesystem</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <h4><a name="t120"></a><a id="PVC_4244"></a>PVC</h4> 
    <p>PVC是资源的申请,用来声明对存储空间、访问模式、存储类别需求信息。下面是资源清单文件:</p> 
    <pre data-index="280" class="set-code-show prettyprint"><code class="prism language-yaml has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token key atrule">apiVersion</span><span class="token punctuation">:</span> <span class="token key atrule">v1kind</span><span class="token punctuation">:</span> <span class="token key atrule">PersistentVolumeClaimmetadata</span><span class="token punctuation">:</span>  <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">pvc  namespace</span><span class="token punctuation">:</span> <span class="token key atrule">devspec</span><span class="token punctuation">:</span>  <span class="token key atrule">accessModes</span><span class="token punctuation">:</span> <span class="token comment"># 访问模式  selector: # 采用标签对PV选择  storageClassName: # 存储类别  resources: # 请求空间    requests:      storage: 5Gi</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <p>PVC 的关键配置参数说明:</p> 
    <ul><li><strong>访问模式(accessModes)</strong></li></ul> 
    <p>​ 用于描述用户应用对存储资源的访问权限</p> 
    <ul><li> <p><strong>选择条件(selector)</strong></p> <p>通过Label Selector的设置,可使PVC对于系统中己存在的PV进行筛选</p> </li><li> <p><strong>存储类别(storageClassName)</strong></p> <p>PVC在定义时可以设定需要的后端存储的类别,只有设置了该class的pv才能被系统选出</p> </li><li> <p><strong>资源请求(Resources )</strong></p> <p>描述对存储资源的请求</p> </li></ul> 
    <p><strong>实验</strong></p> 
    <ol><li>创建pvc.yaml,申请pv</li></ol> 
    <pre data-index="281" class="set-code-show prettyprint"><code class="prism language-yaml has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token key atrule">apiVersion</span><span class="token punctuation">:</span> <span class="token key atrule">v1kind</span><span class="token punctuation">:</span> <span class="token key atrule">PersistentVolumeClaimmetadata</span><span class="token punctuation">:</span>  <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">pvc1  namespace</span><span class="token punctuation">:</span> <span class="token key atrule">devspec</span><span class="token punctuation">:</span>  <span class="token key atrule">accessModes</span><span class="token punctuation">:</span>   <span class="token punctuation">-</span> <span class="token key atrule">ReadWriteMany  resources</span><span class="token punctuation">:</span>    <span class="token key atrule">requests</span><span class="token punctuation">:</span>      <span class="token key atrule">storage</span><span class="token punctuation">:</span> <span class="token key atrule">1Gi      ---apiVersion</span><span class="token punctuation">:</span> <span class="token key atrule">v1kind</span><span class="token punctuation">:</span> <span class="token key atrule">PersistentVolumeClaimmetadata</span><span class="token punctuation">:</span>  <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">pvc2  namespace</span><span class="token punctuation">:</span> <span class="token key atrule">devspec</span><span class="token punctuation">:</span>  <span class="token key atrule">accessModes</span><span class="token punctuation">:</span>   <span class="token punctuation">-</span> <span class="token key atrule">ReadWriteMany  resources</span><span class="token punctuation">:</span>    <span class="token key atrule">requests</span><span class="token punctuation">:</span>      <span class="token key atrule">storage</span><span class="token punctuation">:</span> <span class="token key atrule">1Gi     ---apiVersion</span><span class="token punctuation">:</span> <span class="token key atrule">v1kind</span><span class="token punctuation">:</span> <span class="token key atrule">PersistentVolumeClaimmetadata</span><span class="token punctuation">:</span>  <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">pvc3  namespace</span><span class="token punctuation">:</span> <span class="token key atrule">devspec</span><span class="token punctuation">:</span>  <span class="token key atrule">accessModes</span><span class="token punctuation">:</span>   <span class="token punctuation">-</span> <span class="token key atrule">ReadWriteMany  resources</span><span class="token punctuation">:</span>    <span class="token key atrule">requests</span><span class="token punctuation">:</span>      <span class="token key atrule">storage</span><span class="token punctuation">:</span> 1Gi
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <pre data-index="282" class="set-code-show prettyprint"><code class="prism language-powershell has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token comment"># 创建pvc[root@master ~]# kubectl create -f pvc.yamlpersistentvolumeclaim/pvc1 createdpersistentvolumeclaim/pvc2 createdpersistentvolumeclaim/pvc3 created# 查看pvc[root@master ~]# kubectl get pvc  -n dev -o wideNAME   STATUS   VOLUME   CAPACITY   ACCESS MODES   STORAGECLASS   AGE   VOLUMEMODEpvc1   Bound    pv1      1Gi        RWX                           15s   Filesystempvc2   Bound    pv2      2Gi        RWX                           15s   Filesystempvc3   Bound    pv3      3Gi        RWX                           15s   Filesystem# 查看pv[root@master ~]# kubectl get pv -o wideNAME  CAPACITY ACCESS MODES  RECLAIM POLICY  STATUS    CLAIM       AGE     VOLUMEMODEpv1    1Gi        RWx        Retain          Bound    dev/pvc1    3h37m    Filesystempv2    2Gi        RWX        Retain          Bound    dev/pvc2    3h37m    Filesystempv3    3Gi        RWX        Retain          Bound    dev/pvc3    3h37m    Filesystem   </span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <ol start="2"><li>创建pods.yaml, 使用pv</li></ol> 
    <pre data-index="283" class="set-code-show prettyprint"><code class="prism language-yaml has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token key atrule">apiVersion</span><span class="token punctuation">:</span> <span class="token key atrule">v1kind</span><span class="token punctuation">:</span> <span class="token key atrule">Podmetadata</span><span class="token punctuation">:</span>  <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">pod1  namespace</span><span class="token punctuation">:</span> <span class="token key atrule">devspec</span><span class="token punctuation">:</span>  <span class="token key atrule">containers</span><span class="token punctuation">:</span>  <span class="token punctuation">-</span> <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">busybox    image</span><span class="token punctuation">:</span> <span class="token key atrule">busybox:1.30    command</span><span class="token punctuation">:</span> <span class="token punctuation">[</span><span class="token string">"/bin/sh"</span><span class="token punctuation">,</span><span class="token string">"-c"</span><span class="token punctuation">,</span><span class="token string">"while true;do echo pod1 >> /root/out.txt; sleep 10; done;"</span><span class="token punctuation">]</span>    volumeMounts<span class="token punctuation">:</span>    <span class="token punctuation">-</span> <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">volume      mountPath</span><span class="token punctuation">:</span> <span class="token key atrule">/root/  volumes</span><span class="token punctuation">:</span>    <span class="token punctuation">-</span> <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">volume      persistentVolumeClaim</span><span class="token punctuation">:</span>        <span class="token key atrule">claimName</span><span class="token punctuation">:</span> <span class="token key atrule">pvc1        readOnly</span><span class="token punctuation">:</span> <span class="token key atrule">false---apiVersion</span><span class="token punctuation">:</span> <span class="token key atrule">v1kind</span><span class="token punctuation">:</span> <span class="token key atrule">Podmetadata</span><span class="token punctuation">:</span>  <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">pod2  namespace</span><span class="token punctuation">:</span> <span class="token key atrule">devspec</span><span class="token punctuation">:</span>  <span class="token key atrule">containers</span><span class="token punctuation">:</span>  <span class="token punctuation">-</span> <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">busybox    image</span><span class="token punctuation">:</span> <span class="token key atrule">busybox:1.30    command</span><span class="token punctuation">:</span> <span class="token punctuation">[</span><span class="token string">"/bin/sh"</span><span class="token punctuation">,</span><span class="token string">"-c"</span><span class="token punctuation">,</span><span class="token string">"while true;do echo pod2 >> /root/out.txt; sleep 10; done;"</span><span class="token punctuation">]</span>    volumeMounts<span class="token punctuation">:</span>    <span class="token punctuation">-</span> <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">volume      mountPath</span><span class="token punctuation">:</span> <span class="token key atrule">/root/  volumes</span><span class="token punctuation">:</span>    <span class="token punctuation">-</span> <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">volume      persistentVolumeClaim</span><span class="token punctuation">:</span>        <span class="token key atrule">claimName</span><span class="token punctuation">:</span> <span class="token key atrule">pvc2        readOnly</span><span class="token punctuation">:</span> <span class="token boolean important">false</span>        
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <pre data-index="284" class="set-code-show prettyprint"><code class="prism language-powershell has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token comment"># 创建pod[root@master ~]# kubectl create -f pods.yamlpod/pod1 createdpod/pod2 created# 查看pod[root@master ~]# kubectl get pods -n dev -o wideNAME   READY   STATUS    RESTARTS   AGE   IP            NODE   pod1   1/1     Running   0          14s   10.244.1.69   node1   pod2   1/1     Running   0          14s   10.244.1.70   node1  # 查看pvc[root@master ~]# kubectl get pvc -n dev -o wideNAME   STATUS   VOLUME   CAPACITY   ACCESS MODES      AGE   VOLUMEMODEpvc1   Bound    pv1      1Gi        RWX               94m   Filesystempvc2   Bound    pv2      2Gi        RWX               94m   Filesystempvc3   Bound    pv3      3Gi        RWX               94m   Filesystem# 查看pv[root@master ~]# kubectl get pv -n dev -o wideNAME   CAPACITY   ACCESS MODES   RECLAIM POLICY   STATUS   CLAIM       AGE     VOLUMEMODEpv1    1Gi        RWX            Retain           Bound    dev/pvc1    5h11m   Filesystempv2    2Gi        RWX            Retain           Bound    dev/pvc2    5h11m   Filesystempv3    3Gi        RWX            Retain           Bound    dev/pvc3    5h11m   Filesystem# 查看nfs中的文件存储[root@master ~]# more /root/data/pv1/out.txtnode1node1[root@master ~]# more /root/data/pv2/out.txtnode2node2</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <h4><a name="t121"></a><a id="_4292"></a>生命周期</h4> 
    <p>PVC和PV是一一对应的,PV和PVC之间的相互作用遵循以下生命周期:</p> 
    <ul><li> <p><strong>资源供应</strong>:管理员手动创建底层存储和PV</p> </li><li> <p><strong>资源绑定</strong>:用户创建PVC,kubernetes负责根据PVC的声明去寻找PV,并绑定</p> <p>在用户定义好PVC之后,系统将根据PVC对存储资源的请求在已存在的PV中选择一个满足条件的</p> 
      <ul><li> <p>一旦找到,就将该PV与用户定义的PVC进行绑定,用户的应用就可以使用这个PVC了</p> </li><li> <p>如果找不到,PVC则会无限期处于Pending状态,直到等到系统管理员创建了一个符合其要求的PV</p> </li></ul> <p>PV一旦绑定到某个PVC上,就会被这个PVC独占,不能再与其他PVC进行绑定了</p> </li><li> <p><strong>资源使用</strong>:用户可在pod中像volume一样使用pvc</p> <p>Pod使用Volume的定义,将PVC挂载到容器内的某个路径进行使用。</p> </li><li> <p><strong>资源释放</strong>:用户删除pvc来释放pv</p> <p>当存储资源使用完毕后,用户可以删除PVC,与该PVC绑定的PV将会被标记为“已释放”,但还不能立刻与其他PVC进行绑定。通过之前PVC写入的数据可能还被留在存储设备上,只有在清除之后该PV才能再次使用。</p> </li><li> <p><strong>资源回收</strong>:kubernetes根据pv设置的回收策略进行资源的回收</p> <p>对于PV,管理员可以设定回收策略,用于设置与之绑定的PVC释放资源之后如何处理遗留数据的问题。只有PV的存储空间完成回收,才能供新的PVC绑定和使用</p> </li></ul> 
    <img src="https://1000bd.com/contentImg/2024/04/13/efdb47b089fdd0ff.png"> 
    <h3><a name="t122"></a><a id="_4322"></a>配置存储</h3> 
    <h4><a name="t123"></a><a id="ConfigMap_4324"></a>ConfigMap</h4> 
    <p>ConfigMap是一种比较特殊的存储卷,它的主要作用是用来存储配置信息的。</p> 
    <p>创建configmap.yaml,内容如下:</p> 
    <pre data-index="285" class="set-code-show prettyprint"><code class="prism language-yaml has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token key atrule">apiVersion</span><span class="token punctuation">:</span> <span class="token key atrule">v1kind</span><span class="token punctuation">:</span> <span class="token key atrule">ConfigMapmetadata</span><span class="token punctuation">:</span>  <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">configmap  namespace</span><span class="token punctuation">:</span> <span class="token key atrule">devdata</span><span class="token punctuation">:</span>  <span class="token key atrule">info</span><span class="token punctuation">:</span> <span class="token punctuation">|</span>    username<span class="token punctuation">:</span>admin    password<span class="token punctuation">:</span><span class="token number">123456</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <p>接下来,使用此配置文件创建configmap</p> 
    <pre data-index="286" class="set-code-show prettyprint"><code class="prism language-powershell has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token comment"># 创建configmap[root@master ~]# kubectl create -f configmap.yamlconfigmap/configmap created# 查看configmap详情[root@master ~]# kubectl describe cm configmap -n devName:         configmapNamespace:    devLabels:       <none>Annotations:  <none>Data====info:----username:adminpassword:123456Events:  <none></span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <p>接下来创建一个pod-configmap.yaml,将上面创建的configmap挂载进去</p> 
    <pre data-index="287" class="set-code-show prettyprint"><code class="prism language-yaml has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token key atrule">apiVersion</span><span class="token punctuation">:</span> <span class="token key atrule">v1kind</span><span class="token punctuation">:</span> <span class="token key atrule">Podmetadata</span><span class="token punctuation">:</span>  <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">pod-configmap  namespace</span><span class="token punctuation">:</span> <span class="token key atrule">devspec</span><span class="token punctuation">:</span>  <span class="token key atrule">containers</span><span class="token punctuation">:</span>  <span class="token punctuation">-</span> <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">nginx    image</span><span class="token punctuation">:</span> <span class="token key atrule">nginx:1.17.1    volumeMounts</span><span class="token punctuation">:</span> <span class="token comment"># 将configmap挂载到目录    - name: config      mountPath: /configmap/config  volumes: # 引用configmap  - name: config    configMap:      name: configmap</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <pre data-index="288" class="set-code-show prettyprint"><code class="prism language-powershell has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token comment"># 创建pod[root@master ~]# kubectl create -f pod-configmap.yamlpod/pod-configmap created# 查看pod[root@master ~]# kubectl get pod pod-configmap -n devNAME            READY   STATUS    RESTARTS   AGEpod-configmap   1/1     Running   0          6s#进入容器[root@master ~]# kubectl exec -it pod-configmap -n dev /bin/sh# cd /configmap/config/# lsinfo# more infousername:adminpassword:123456# 可以看到映射已经成功,每个configmap都映射成了一个目录# key--->文件     value---->文件中的内容# 此时如果更新configmap的内容, 容器中的值也会动态更新</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <h4><a name="t124"></a><a id="Secret_4350"></a>Secret</h4> 
    <p>​ 在kubernetes中,还存在一种和ConfigMap非常类似的对象,称为Secret对象。它主要用于存储敏感信息,例如密码、秘钥、证书等等。</p> 
    <ol><li>首先使用base64对数据进行编码</li></ol> 
    <pre data-index="289" class="set-code-show prettyprint"><code class="prism language-yaml has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token punctuation">[</span>root@master ~<span class="token punctuation">]</span><span class="token comment"># echo -n 'admin' | base64 #准备usernameYWRtaW4=[root@master ~]# echo -n '123456' | base64 #准备passwordMTIzNDU2</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <ol start="2"><li>接下来编写secret.yaml,并创建Secret</li></ol> 
    <pre data-index="290" class="set-code-show prettyprint"><code class="prism language-yaml has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token key atrule">apiVersion</span><span class="token punctuation">:</span> <span class="token key atrule">v1kind</span><span class="token punctuation">:</span> <span class="token key atrule">Secretmetadata</span><span class="token punctuation">:</span>  <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">secret  namespace</span><span class="token punctuation">:</span> <span class="token key atrule">devtype</span><span class="token punctuation">:</span> <span class="token key atrule">Opaquedata</span><span class="token punctuation">:</span>  <span class="token key atrule">username</span><span class="token punctuation">:</span> <span class="token key atrule">YWRtaW4=  password</span><span class="token punctuation">:</span> MTIzNDU2
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <pre data-index="291" class="set-code-show prettyprint"><code class="prism language-powershell has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token comment"># 创建secret[root@master ~]# kubectl create -f secret.yamlsecret/secret created# 查看secret详情[root@master ~]# kubectl describe secret secret -n devName:         secretNamespace:    devLabels:       <none>Annotations:  <none>Type:  OpaqueData====password:  6 bytesusername:  5 bytes</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <ol start="3"><li>创建pod-secret.yaml,将上面创建的secret挂载进去:</li></ol> 
    <pre data-index="292" class="set-code-show prettyprint"><code class="prism language-yaml has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token key atrule">apiVersion</span><span class="token punctuation">:</span> <span class="token key atrule">v1kind</span><span class="token punctuation">:</span> <span class="token key atrule">Podmetadata</span><span class="token punctuation">:</span>  <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">pod-secret  namespace</span><span class="token punctuation">:</span> <span class="token key atrule">devspec</span><span class="token punctuation">:</span>  <span class="token key atrule">containers</span><span class="token punctuation">:</span>  <span class="token punctuation">-</span> <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">nginx    image</span><span class="token punctuation">:</span> <span class="token key atrule">nginx:1.17.1    volumeMounts</span><span class="token punctuation">:</span> <span class="token comment"># 将secret挂载到目录    - name: config      mountPath: /secret/config  volumes:  - name: config    secret:      secretName: secret</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <pre data-index="293" class="set-code-show prettyprint"><code class="prism language-powershell has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token comment"># 创建pod[root@master ~]# kubectl create -f pod-secret.yamlpod/pod-secret created# 查看pod[root@master ~]# kubectl get pod pod-secret -n devNAME            READY   STATUS    RESTARTS   AGEpod-secret      1/1     Running   0          2m28s# 进入容器,查看secret信息,发现已经自动解码了[root@master ~]# kubectl exec -it pod-secret /bin/sh -n dev/ # ls /secret/config/password  username/ # more /secret/config/usernameadmin/ # more /secret/config/password123456</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <p>至此,已经实现了利用secret实现了信息的编码。</p> 
    <h2><a name="t125"></a><a id="__4382"></a>第九章 安全认证</h2> 
    <p>本章节主要介绍Kubernetes的安全认证机制。</p> 
    <h3><a name="t126"></a><a id="_4386"></a>访问控制概述</h3> 
    <p>​ Kubernetes作为一个分布式集群的管理工具,保证集群的安全性是其一个重要的任务。所谓的安全性其实就是保证对Kubernetes的各种<strong>客户端</strong>进行<strong>认证和鉴权</strong>操作。</p> 
    <p><strong>客户端</strong></p> 
    <p>在Kubernetes集群中,客户端通常有两类:</p> 
    <ul><li> <p><strong>User Account</strong>:一般是独立于kubernetes之外的其他服务管理的用户账号。</p> </li><li> <p><strong>Service Account</strong>:kubernetes管理的账号,用于为Pod中的服务进程在访问Kubernetes时提供身份标识。</p> </li></ul> 
    <img src="https://1000bd.com/contentImg/2024/04/15/7ed5440559a52033.png"> 
    <p><strong>认证、授权与准入控制</strong></p> 
    <p>ApiServer是访问及管理资源对象的唯一入口。任何一个请求访问ApiServer,都要经过下面三个流程:</p> 
    <ul><li>Authentication(认证):身份鉴别,只有正确的账号才能够通过认证</li><li>Authorization(授权): 判断用户是否有权限对访问的资源执行特定的动作</li><li>Admission Control(准入控制):用于补充授权机制以实现更加精细的访问控制功能。</li></ul> 
    <img src="https://1000bd.com/contentImg/2024/04/15/03d2e79a4018a33b.png"> 
    <h3><a name="t127"></a><a id="_4410"></a>认证管理</h3> 
    <p>Kubernetes集群安全的最关键点在于如何识别并认证客户端身份,它提供了3种客户端身份认证方式:</p> 
    <ul><li> <p>HTTP Base认证:通过用户名+密码的方式认证</p> <pre data-index="294" class="set-code-show prettyprint"><code class="prism language-markdown has-numbering" onclick="mdcp.signin(event)" style="position: unset;">    这种认证方式是把“用户名:密码”用BASE64算法进行编码后的字符串放在HTTP请求中的Header Authorization域里发送给服务端。服务端收到后进行解码,获取用户名及密码,然后进行用户身份认证的过程。
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> </li><li> <p>HTTP Token认证:通过一个Token来识别合法用户</p> <pre data-index="295" class="set-code-show prettyprint"><code class="prism language-markdown has-numbering" onclick="mdcp.signin(event)" style="position: unset;">    这种认证方式是用一个很长的难以被模仿的字符串--Token来表明客户身份的一种方式。每个Token对应一个用户名,当客户端发起API调用请求时,需要在HTTP Header里放入Token,API Server接到Token后会跟服务器中保存的token进行比对,然后进行用户身份认证的过程。
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> </li><li> <p>HTTPS证书认证:基于CA根证书签名的双向数字证书认证方式</p> <pre data-index="296" class="set-code-show prettyprint"><code class="prism language-markdown has-numbering" onclick="mdcp.signin(event)" style="position: unset;">    这种认证方式是安全性最高的一种方式,但是同时也是操作起来最麻烦的一种方式。
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> </li></ul> 
    <img src="https://1000bd.com/contentImg/2024/04/15/2dee04940b4d6c82.png"> 
    <p><strong>HTTPS认证大体分为3个过程:</strong></p> 
    <ol><li> <p>证书申请和下发</p> <pre data-index="297" class="set-code-show prettyprint"><code class="prism language-markdown has-numbering" onclick="mdcp.signin(event)" style="position: unset;">  HTTPS通信双方的服务器向CA机构申请证书,CA机构下发根证书、服务端证书及私钥给申请者
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> </li><li> <p>客户端和服务端的双向认证</p> <pre data-index="298" class="set-code-show prettyprint"><code class="prism language-markdown has-numbering" onclick="mdcp.signin(event)" style="position: unset;">  1> 客户端向服务器端发起请求,服务端下发自己的证书给客户端,     客户端接收到证书后,通过私钥解密证书,在证书中获得服务端的公钥,     客户端利用服务器端的公钥认证证书中的信息,如果一致,则认可这个服务器  2> 客户端发送自己的证书给服务器端,服务端接收到证书后,通过私钥解密证书,     在证书中获得客户端的公钥,并用该公钥认证证书信息,确认客户端是否合法
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> </li><li> <p>服务器端和客户端进行通信</p> <pre data-index="299" class="set-code-show prettyprint"><code class="prism language-markdown has-numbering" onclick="mdcp.signin(event)" style="position: unset;">  服务器端和客户端协商好加密方案后,客户端会产生一个随机的秘钥并加密,然后发送到服务器端。  服务器端接收这个秘钥后,双方接下来通信的所有内容都通过该随机秘钥加密
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> </li></ol> 
    <blockquote> 
     <p>注意: Kubernetes允许同时配置多种认证方式,只要其中任意一个方式认证通过即可</p> 
    </blockquote> 
    <h3><a name="t128"></a><a id="_4456"></a>授权管理</h3> 
    <p>​ 授权发生在认证成功之后,通过认证就可以知道请求用户是谁, 然后Kubernetes会根据事先定义的授权策略来决定用户是否有权限访问,这个过程就称为授权。</p> 
    <p>​ 每个发送到ApiServer的请求都带上了用户和资源的信息:比如发送请求的用户、请求的路径、请求的动作等,授权就是根据这些信息和授权策略进行比较,如果符合策略,则认为授权通过,否则会返回错误。</p> 
    <p>API Server目前支持以下几种授权策略:</p> 
    <ul><li> <p>AlwaysDeny:表示拒绝所有请求,一般用于测试</p> </li><li> <p>AlwaysAllow:允许接收所有请求,相当于集群不需要授权流程(Kubernetes默认的策略)</p> </li><li> <p>ABAC:基于属性的访问控制,表示使用用户配置的授权规则对用户请求进行匹配和控制</p> </li><li> <p>Webhook:通过调用外部REST服务对用户进行授权</p> </li><li> <p>Node:是一种专用模式,用于对kubelet发出的请求进行访问控制</p> </li><li> <p>RBAC:基于角色的访问控制(kubeadm安装方式下的默认选项)</p> </li></ul> 
    <p>RBAC(Role-Based Access Control) 基于角色的访问控制,主要是在描述一件事情:<strong>给哪些对象授予了哪些权限</strong></p> 
    <p>其中涉及到了下面几个概念:</p> 
    <ul><li>对象:User、Groups、ServiceAccount</li><li>角色:代表着一组定义在资源上的可操作动作(权限)的集合</li><li>绑定:将定义好的角色跟用户绑定在一起</li></ul> 
    <img src="https://1000bd.com/contentImg/2024/04/15/b76f684be7e840ee.png"> 
    <p>RBAC引入了4个顶级资源对象:</p> 
    <ul><li>Role、ClusterRole:角色,用于指定一组权限</li><li>RoleBinding、ClusterRoleBinding:角色绑定,用于将角色(权限)赋予给对象</li></ul> 
    <p><strong>Role、ClusterRole</strong></p> 
    <p>一个角色就是一组权限的集合,这里的权限都是许可形式的(白名单)。</p> 
    <pre data-index="300" class="set-code-show prettyprint"><code class="prism language-yaml has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token comment"># Role只能对命名空间内的资源进行授权,需要指定nameapcekind: RoleapiVersion: rbac.authorization.k8s.io/v1beta1metadata:  namespace: dev  name: authorization-rolerules:- apiGroups: [""]  # 支持的API组列表,"" 空字符串,表示核心API群  resources: ["pods"] # 支持的资源对象列表  verbs: ["get", "watch", "list"] # 允许的对资源对象的操作方法列表</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <pre data-index="301" class="set-code-show prettyprint"><code class="prism language-yaml has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token comment"># ClusterRole可以对集群范围内资源、跨namespaces的范围资源、非资源类型进行授权kind: ClusterRoleapiVersion: rbac.authorization.k8s.io/v1beta1metadata: name: authorization-clusterrolerules:- apiGroups: [""]  resources: ["pods"]  verbs: ["get", "watch", "list"]</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <p>需要详细说明的是,rules中的参数:</p> 
    <ul><li> <p>apiGroups: 支持的API组列表</p> <pre data-index="302" class="set-code-show prettyprint"><code class="prism language-bash has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token string">""</span>,<span class="token string">"apps"</span>, <span class="token string">"autoscaling"</span>, <span class="token string">"batch"</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> </li><li> <p>resources:支持的资源对象列表</p> <pre data-index="303" class="set-code-show prettyprint"><code class="prism language-bash has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token string">"services"</span>, <span class="token string">"endpoints"</span>, <span class="token string">"pods"</span>,<span class="token string">"secrets"</span>,<span class="token string">"configmaps"</span>,<span class="token string">"crontabs"</span>,<span class="token string">"deployments"</span>,<span class="token string">"jobs"</span>,<span class="token string">"nodes"</span>,<span class="token string">"rolebindings"</span>,<span class="token string">"clusterroles"</span>,<span class="token string">"daemonsets"</span>,<span class="token string">"replicasets"</span>,<span class="token string">"statefulsets"</span>,<span class="token string">"horizontalpodautoscalers"</span>,<span class="token string">"replicationcontrollers"</span>,<span class="token string">"cronjobs"</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> </li><li> <p>verbs:对资源对象的操作方法列表</p> <pre data-index="304" class="set-code-show prettyprint"><code class="prism language-bash has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token string">"get"</span>, <span class="token string">"list"</span>, <span class="token string">"watch"</span>, <span class="token string">"create"</span>, <span class="token string">"update"</span>, <span class="token string">"patch"</span>, <span class="token string">"delete"</span>, <span class="token string">"exec"</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> </li></ul> 
    <p><strong>RoleBinding、ClusterRoleBinding</strong></p> 
    <p>角色绑定用来把一个角色绑定到一个目标对象上,绑定目标可以是User、Group或者ServiceAccount。</p> 
    <pre data-index="305" class="set-code-show prettyprint"><code class="prism language-yaml has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token comment"># RoleBinding可以将同一namespace中的subject绑定到某个Role下,则此subject即具有该Role定义的权限kind: RoleBindingapiVersion: rbac.authorization.k8s.io/v1beta1metadata:  name: authorization-role-binding  namespace: devsubjects:- kind: User  name: heima  apiGroup: rbac.authorization.k8s.ioroleRef:  kind: Role  name: authorization-role  apiGroup: rbac.authorization.k8s.io</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <pre data-index="306" class="set-code-show prettyprint"><code class="prism language-yaml has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token comment"># ClusterRoleBinding在整个集群级别和所有namespaces将特定的subject与ClusterRole绑定,授予权限kind: ClusterRoleBindingapiVersion: rbac.authorization.k8s.io/v1beta1metadata: name: authorization-clusterrole-bindingsubjects:- kind: User  name: heima  apiGroup: rbac.authorization.k8s.ioroleRef:  kind: ClusterRole  name: authorization-clusterrole  apiGroup: rbac.authorization.k8s.io</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <p><strong>RoleBinding引用ClusterRole进行授权</strong></p> 
    <p>RoleBinding可以引用ClusterRole,对属于同一命名空间内ClusterRole定义的资源主体进行授权。</p> 
    <pre data-index="307" class="set-code-show prettyprint"><code class="prism language-markdown has-numbering" onclick="mdcp.signin(event)" style="position: unset;">    一种很常用的做法就是,集群管理员为集群范围预定义好一组角色(ClusterRole),然后在多个命名空间中重复使用这些ClusterRole。这样可以大幅提高授权管理工作效率,也使得各个命名空间下的基础性授权规则与使用体验保持一致。
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <pre data-index="308" class="set-code-show prettyprint"><code class="prism language-yaml has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token comment"># 虽然authorization-clusterrole是一个集群角色,但是因为使用了RoleBinding# 所以heima只能读取dev命名空间中的资源kind: RoleBindingapiVersion: rbac.authorization.k8s.io/v1beta1metadata:  name: authorization-role-binding-ns  namespace: devsubjects:- kind: User  name: heima  apiGroup: rbac.authorization.k8s.ioroleRef:  kind: ClusterRole  name: authorization-clusterrole  apiGroup: rbac.authorization.k8s.io</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <p><strong>实战:创建一个只能管理dev空间下Pods资源的账号</strong></p> 
    <ol><li>创建账号</li></ol> 
    <pre data-index="309" class="set-code-show prettyprint"><code class="prism language-powershell has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token comment"># 1) 创建证书[root@master pki]# cd /etc/kubernetes/pki/[root@master pki]# (umask 077;openssl genrsa -out devman.key 2048)# 2) 用apiserver的证书去签署# 2-1) 签名申请,申请的用户是devman,组是devgroup[root@master pki]# openssl req -new -key devman.key -out devman.csr -subj "/CN=devman/O=devgroup"     # 2-2) 签署证书[root@master pki]# openssl x509 -req -in devman.csr -CA ca.crt -CAkey ca.key -CAcreateserial -out devman.crt -days 3650# 3) 设置集群、用户、上下文信息[root@master pki]# kubectl config set-cluster kubernetes --embed-certs=true --certificate-authority=/etc/kubernetes/pki/ca.crt --server=https://192.168.109.100:6443[root@master pki]# kubectl config set-credentials devman --embed-certs=true --client-certificate=/etc/kubernetes/pki/devman.crt --client-key=/etc/kubernetes/pki/devman.key[root@master pki]# kubectl config set-context devman@kubernetes --cluster=kubernetes --user=devman# 切换账户到devman[root@master pki]# kubectl config use-context devman@kubernetesSwitched to context "devman@kubernetes".# 查看dev下pod,发现没有权限[root@master pki]# kubectl get pods -n devError from server (Forbidden): pods is forbidden: User "devman" cannot list resource "pods" in API group "" in the namespace "dev"# 切换到admin账户[root@master pki]# kubectl config use-context kubernetes-admin@kubernetesSwitched to context "kubernetes-admin@kubernetes".</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <p>2) 创建Role和RoleBinding,为devman用户授权</p> 
    <pre data-index="310" class="set-code-show prettyprint"><code class="prism language-yaml has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token key atrule">kind</span><span class="token punctuation">:</span> <span class="token key atrule">RoleapiVersion</span><span class="token punctuation">:</span> <span class="token key atrule">rbac.authorization.k8s.io/v1beta1metadata</span><span class="token punctuation">:</span>  <span class="token key atrule">namespace</span><span class="token punctuation">:</span> <span class="token key atrule">dev  name</span><span class="token punctuation">:</span> <span class="token key atrule">dev-rolerules:- apiGroups</span><span class="token punctuation">:</span> <span class="token punctuation">[</span><span class="token string">""</span><span class="token punctuation">]</span>  resources<span class="token punctuation">:</span> <span class="token punctuation">[</span><span class="token string">"pods"</span><span class="token punctuation">]</span>  verbs<span class="token punctuation">:</span> <span class="token punctuation">[</span><span class="token string">"get"</span><span class="token punctuation">,</span> <span class="token string">"watch"</span><span class="token punctuation">,</span> <span class="token string">"list"</span><span class="token punctuation">]</span>  <span class="token punctuation">-</span><span class="token key atrule">--kind</span><span class="token punctuation">:</span> <span class="token key atrule">RoleBindingapiVersion</span><span class="token punctuation">:</span> <span class="token key atrule">rbac.authorization.k8s.io/v1beta1metadata</span><span class="token punctuation">:</span>  <span class="token key atrule">name</span><span class="token punctuation">:</span> <span class="token key atrule">authorization-role-binding  namespace</span><span class="token punctuation">:</span> <span class="token key atrule">devsubjects:- kind</span><span class="token punctuation">:</span> <span class="token key atrule">User  name</span><span class="token punctuation">:</span> <span class="token key atrule">devman  apiGroup</span><span class="token punctuation">:</span> <span class="token key atrule">rbac.authorization.k8s.ioroleRef</span><span class="token punctuation">:</span>  <span class="token key atrule">kind</span><span class="token punctuation">:</span> <span class="token key atrule">Role  name</span><span class="token punctuation">:</span> <span class="token key atrule">dev-role  apiGroup</span><span class="token punctuation">:</span> rbac.authorization.k8s.io
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <pre data-index="311" class="set-code-show prettyprint"><code class="prism language-powershell has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token namespace">[root@master pki]</span><span class="token comment"># kubectl create -f dev-role.yamlrole.rbac.authorization.k8s.io/dev-role createdrolebinding.rbac.authorization.k8s.io/authorization-role-binding created</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <ol start="3"><li>切换账户,再次验证</li></ol> 
    <pre data-index="312" class="set-code-show prettyprint"><code class="prism language-powershell has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token comment"># 切换账户到devman[root@master pki]# kubectl config use-context devman@kubernetesSwitched to context "devman@kubernetes".# 再次查看[root@master pki]# kubectl get pods -n devNAME                                 READY   STATUS             RESTARTS   AGEnginx-deployment-66cb59b984-8wp2k    1/1     Running            0          4d1hnginx-deployment-66cb59b984-dc46j    1/1     Running            0          4d1hnginx-deployment-66cb59b984-thfck    1/1     Running            0          4d1h# 为了不影响后面的学习,切回admin账户[root@master pki]# kubectl config use-context kubernetes-admin@kubernetesSwitched to context "kubernetes-admin@kubernetes".</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <h3><a name="t129"></a><a id="_4572"></a>准入控制</h3> 
    <p>通过了前面的认证和授权之后,还需要经过准入控制处理通过之后,apiserver才会处理这个请求。</p> 
    <p>准入控制是一个可配置的控制器列表,可以通过在Api-Server上通过命令行设置选择执行哪些准入控制器:</p> 
    <pre data-index="313" class="set-code-show prettyprint"><code class="prism language-powershell has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token operator">--</span>admission-control=NamespaceLifecycle<span class="token punctuation">,</span>LimitRanger<span class="token punctuation">,</span>ServiceAccount<span class="token punctuation">,</span>PersistentVolumeLabel<span class="token punctuation">,</span>                      DefaultStorageClass<span class="token punctuation">,</span>ResourceQuota<span class="token punctuation">,</span>DefaultTolerationSeconds
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <p>只有当所有的准入控制器都检查通过之后,apiserver才执行该请求,否则返回拒绝。</p> 
    <p>当前可配置的Admission Control准入控制如下:</p> 
    <ul><li>AlwaysAdmit:允许所有请求</li><li>AlwaysDeny:禁止所有请求,一般用于测试</li><li>AlwaysPullImages:在启动容器之前总去下载镜像</li><li>DenyExecOnPrivileged:它会拦截所有想在Privileged Container上执行命令的请求</li><li>ImagePolicyWebhook:这个插件将允许后端的一个Webhook程序来完成admission controller的功能。</li><li>Service Account:实现ServiceAccount实现了自动化</li><li>SecurityContextDeny:这个插件将使用SecurityContext的Pod中的定义全部失效</li><li>ResourceQuota:用于资源配额管理目的,观察所有请求,确保在namespace上的配额不会超标</li><li>LimitRanger:用于资源限制管理,作用于namespace上,确保对Pod进行资源限制</li><li>InitialResources:为未设置资源请求与限制的Pod,根据其镜像的历史资源的使用情况进行设置</li><li>NamespaceLifecycle:如果尝试在一个不存在的namespace中创建资源对象,则该创建请求将被拒绝。当删除一个namespace时,系统将会删除该namespace中所有对象。</li><li>DefaultStorageClass:为了实现共享存储的动态供应,为未指定StorageClass或PV的PVC尝试匹配默认的StorageClass,尽可能减少用户在申请PVC时所需了解的后端存储细节</li><li>DefaultTolerationSeconds:这个插件为那些没有设置forgiveness tolerations并具有notready:NoExecute和unreachable:NoExecute两种taints的Pod设置默认的“容忍”时间,为5min</li><li>PodSecurityPolicy:这个插件用于在创建或修改Pod时决定是否根据Pod的security context和可用的PodSecurityPolicy对Pod的安全策略进行控制</li></ul> 
    <h2><a name="t130"></a><a id="_DashBoard_4601"></a>第十章 DashBoard</h2> 
    <p>​ 之前在kubernetes中完成的所有操作都是通过命令行工具kubectl完成的。其实,为了提供更丰富的用户体验,kubernetes还开发了一个基于web的用户界面(Dashboard)。用户可以使用Dashboard部署容器化的应用,还可以监控应用的状态,执行故障排查以及管理kubernetes中各种资源。</p> 
    <h3><a name="t131"></a><a id="Dashboard_4605"></a>部署Dashboard</h3> 
    <ol><li>下载yaml,并运行Dashboard</li></ol> 
    <pre data-index="314" class="set-code-show prettyprint"><code class="prism language-powershell has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token comment"># 下载yaml[root@master ~]# wget  https://raw.githubusercontent.com/kubernetes/dashboard/v2.0.0/aio/deploy/recommended.yaml# 修改kubernetes-dashboard的Service类型kind: ServiceapiVersion: v1metadata:  labels:    k8s-app: kubernetes-dashboard  name: kubernetes-dashboard  namespace: kubernetes-dashboardspec:  type: NodePort  # 新增  ports:    - port: 443      targetPort: 8443      nodePort: 30009  # 新增  selector:    k8s-app: kubernetes-dashboard# 部署[root@master ~]# kubectl create -f recommended.yaml# 查看namespace下的kubernetes-dashboard下的资源[root@master ~]# kubectl get pod,svc -n kubernetes-dashboardNAME                                            READY   STATUS    RESTARTS   AGEpod/dashboard-metrics-scraper-c79c65bb7-zwfvw   1/1     Running   0          111spod/kubernetes-dashboard-56484d4c5-z95z5        1/1     Running   0          111sNAME                               TYPE       CLUSTER-IP      EXTERNAL-IP  PORT(S)         AGEservice/dashboard-metrics-scraper  ClusterIP  10.96.89.218    <none>       8000/TCP        111sservice/kubernetes-dashboard       NodePort   10.104.178.171  <none>       443:30009/TCP   111s</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <p>2)创建访问账户,获取token</p> 
    <pre data-index="315" class="set-code-show prettyprint"><code class="prism language-powershell has-numbering" onclick="mdcp.signin(event)" style="position: unset;"><span class="token comment"># 创建账号[root@master-1 ~]# kubectl create serviceaccount dashboard-admin -n kubernetes-dashboard# 授权[root@master-1 ~]# kubectl create clusterrolebinding dashboard-admin-rb --clusterrole=cluster-admin --serviceaccount=kubernetes-dashboard:dashboard-admin# 获取账号token[root@master ~]#  kubectl get secrets -n kubernetes-dashboard | grep dashboard-admindashboard-admin-token-xbqhh        kubernetes.io/service-account-token   3      2m35s[root@master ~]# kubectl describe secrets dashboard-admin-token-xbqhh -n kubernetes-dashboardName:         dashboard-admin-token-xbqhhNamespace:    kubernetes-dashboardLabels:       <none>Annotations:  kubernetes.io/service-account.name: dashboard-admin              kubernetes.io/service-account.uid: 95d84d80-be7a-4d10-a2e0-68f90222d039Type:  kubernetes.io/service-account-tokenData====namespace:  20 bytestoken:      eyJhbGciOiJSUzI1NiIsImtpZCI6ImJrYkF4bW5XcDhWcmNGUGJtek5NODFuSXl1aWptMmU2M3o4LTY5a2FKS2cifQ.eyJpc3MiOiJrdWJlcm5ldGVzL3NlcnZpY2VhY2NvdW50Iiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9uYW1lc3BhY2UiOiJrdWJlcm5ldGVzLWRhc2hib2FyZCIsImt1YmVybmV0ZXMuaW8vc2VydmljZWFjY291bnQvc2VjcmV0Lm5hbWUiOiJkYXNoYm9hcmQtYWRtaW4tdG9rZW4teGJxaGgiLCJrdWJlcm5ldGVzLmlvL3NlcnZpY2VhY2NvdW50L3NlcnZpY2UtYWNjb3VudC5uYW1lIjoiZGFzaGJvYXJkLWFkbWluIiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9zZXJ2aWNlLWFjY291bnQudWlkIjoiOTVkODRkODAtYmU3YS00ZDEwLWEyZTAtNjhmOTAyMjJkMDM5Iiwic3ViIjoic3lzdGVtOnNlcnZpY2VhY2NvdW50Omt1YmVybmV0ZXMtZGFzaGJvYXJkOmRhc2hib2FyZC1hZG1pbiJ9.NAl7e8ZfWWdDoPxkqzJzTB46sK9E8iuJYnUI9vnBaY3Jts7T1g1msjsBnbxzQSYgAG--cV0WYxjndzJY_UWCwaGPrQrt_GunxmOK9AUnzURqm55GR2RXIZtjsWVP2EBatsDgHRmuUbQvTFOvdJB4x3nXcYLN2opAaMqg3rnU2rr-A8zCrIuX_eca12wIp_QiuP3SF-tzpdLpsyRfegTJZl6YnSGyaVkC9id-cxZRb307qdCfXPfCHR_2rt5FVfxARgg_C0e3eFHaaYQO7CitxsnIoIXpOFNAR8aUrmopJyODQIPqBWUehb7FhlU1DCduHnIIXVC_UICZ-MKYewBDLwca.crt:     1025 bytes</span>
    <div class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li></ul></pre> 
    <p>3)通过浏览器访问Dashboard的UI</p> 
    <p>在登录页面上输入上面的token</p> 
    <img src="https://1000bd.com/contentImg/2024/04/15/9aba971720f792f2.png" alt="image-20200520144548997"> 
    <p>出现下面的页面代表成功</p> 
    <img src="https://1000bd.com/contentImg/2024/04/15/6de94d2199ad4606.png" alt="image-20200520144959353"> 
    <h3><a name="t132"></a><a id="DashBoard_4629"></a>使用DashBoard</h3> 
    <p>本章节以Deployment为例演示DashBoard的使用</p> 
    <p><strong>查看</strong></p> 
    <p>选择指定的命名空间<code>dev</code>,然后点击<code>Deployments</code>,查看dev空间下的所有deployment</p> 
    <img src="https://1000bd.com/contentImg/2024/04/15/5aca94b338cf305e.png"> 
    <p><strong>扩缩容</strong></p> 
    <p>在<code>Deployment</code>上点击<code>规模</code>,然后指定<code>目标副本数量</code>,点击确定</p> 
    <img src="https://1000bd.com/contentImg/2024/04/15/449cfb20aa91053e.png"> 
    <p><strong>编辑</strong></p> 
    <p>在<code>Deployment</code>上点击<code>编辑</code>,然后修改<code>yaml文件</code>,点击确定</p> 
    <img src="https://1000bd.com/contentImg/2024/04/15/34f6ab27e647d4ca.png" alt="image-20200520163253644"> 
    <p><strong>查看Pod</strong></p> 
    <p>点击<code>Pods</code>, 查看pods列表</p> 
    <img src="https://1000bd.com/contentImg/2024/04/15/cd1af85a68214409.png"> 
    <p><strong>操作Pod</strong></p> 
    <p>选中某个Pod,可以对其执行日志(logs)、进入执行(exec)、编辑、删除操作</p> 
    <img src="https://1000bd.com/contentImg/2024/04/15/daeb8846e7be01e1.png"> 
    <blockquote> 
     <p>Dashboard提供了kubectl的绝大部分功能,这里不再一一演示</p> 
    </blockquote> 
    <p>[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-iOsT7Yxg-1669974966721)(Kubernetes教程.Kubernetes教程.assets/image-20211010173521250.png)]</p>
                    </div>
                        </div>
                    </li>
    
                    <li class="list-group-item ul-li">
    
                        <b>相关阅读:</b><br>
                        <nobr>
    <a href="/Article/Index/736826">【PyTorch】如何取得预训练模型的标签label列表(以 Alexnet 在 ImageNet 上的预训练模型为例)</a>                            <br />
    <a href="/Article/Index/1564207">shell脚本任务</a>                            <br />
    <a href="/Article/Index/988715">Java多线程进阶——CAS与synchronized优化</a>                            <br />
    <a href="/Article/Index/1195632">WPS通过“文档部件”的“域”设置图、表和公式的自动序列号</a>                            <br />
    <a href="/Article/Index/1325112">【MySQL数据库】基本命令操作及语句总结</a>                            <br />
    <a href="/Article/Index/622955">Unity之使用贝塞尔曲线制作图片轮播</a>                            <br />
    <a href="/Article/Index/1290000">嵌入式入门教学——模电基础概念</a>                            <br />
    <a href="/Article/Index/985121">自定义map的key类型---C++</a>                            <br />
    <a href="/Article/Index/1175435">离线解锁 CodeCombat 全关卡教程 使用docker安装实现</a>                            <br />
    <a href="/Article/Index/1465916">LeetCode701. Insert into a Binary Search Tree</a>                            <br />
                        </nobr>
                    </li>
                    <li class="list-group-item from-a mb-2">
                        原文地址:https://blog.csdn.net/why123wh/article/details/128152225
                    </li>
    
                </ul>
            </div>
    
            <div class="col-lg-4 col-sm-12">
                <ul class="list-group" style="word-break:break-all;">
                    <li class="list-group-item ul-li-bg" aria-current="true">
                        最新文章
                    </li>
                    <li class="list-group-item ul-li">
                        <nobr>
    <a href="/Article/Index/1484446">攻防演习之三天拿下官网站群</a>                            <br />
    <a href="/Article/Index/1515268">数据安全治理学习——前期安全规划和安全管理体系建设</a>                            <br />
    <a href="/Article/Index/1759065">企业安全 | 企业内一次钓鱼演练准备过程</a>                            <br />
    <a href="/Article/Index/1485036">内网渗透测试 | Kerberos协议及其部分攻击手法</a>                            <br />
    <a href="/Article/Index/1877332">0day的产生 | 不懂代码的"代码审计"</a>                            <br />
    <a href="/Article/Index/1887576">安装scrcpy-client模块av模块异常,环境问题解决方案</a>                            <br />
    <a href="/Article/Index/1887578">leetcode hot100【LeetCode 279. 完全平方数】java实现</a>                            <br />
    <a href="/Article/Index/1887512">OpenWrt下安装Mosquitto</a>                            <br />
    <a href="/Article/Index/1887520">AnatoMask论文汇总</a>                            <br />
    <a href="/Article/Index/1887496">【AI日记】24.11.01 LangChain、openai api和github copilot</a>                            <br />
                        </nobr>
                    </li>
                </ul>
    
                <ul class="list-group pt-2" style="word-break:break-all;">
                    <li class="list-group-item ul-li-bg" aria-current="true">
                        热门文章
                    </li>
                    <li class="list-group-item ul-li">
                        <nobr>
    <a href="/Article/Index/888177">十款代码表白小特效 一个比一个浪漫 赶紧收藏起来吧!!!</a>                            <br />
    <a href="/Article/Index/797680">奉劝各位学弟学妹们,该打造你的技术影响力了!</a>                            <br />
    <a href="/Article/Index/888183">五年了,我在 CSDN 的两个一百万。</a>                            <br />
    <a href="/Article/Index/888179">Java俄罗斯方块,老程序员花了一个周末,连接中学年代!</a>                            <br />
    <a href="/Article/Index/797730">面试官都震惊,你这网络基础可以啊!</a>                            <br />
    <a href="/Article/Index/797725">你真的会用百度吗?我不信 — 那些不为人知的搜索引擎语法</a>                            <br />
    <a href="/Article/Index/797702">心情不好的时候,用 Python 画棵樱花树送给自己吧</a>                            <br />
    <a href="/Article/Index/797709">通宵一晚做出来的一款类似CS的第一人称射击游戏Demo!原来做游戏也不是很难,连憨憨学妹都学会了!</a>                            <br />
    <a href="/Article/Index/797716">13 万字 C 语言从入门到精通保姆级教程2021 年版</a>                            <br />
    <a href="/Article/Index/888192">10行代码集2000张美女图,Python爬虫120例,再上征途</a>                            <br />
                        </nobr>
                    </li>
                </ul>
    
            </div>
        </div>
    </div>
    <!-- 主体 -->
    
    
        <!--body结束-->
        <!--这里是footer模板-->
        
        <!--footer-->
    <nav class="navbar navbar-inverse navbar-fixed-bottom">
        <div class="container">
            <div class="row">
                <div class="col-md-12">
                    <div class="text-muted center foot-height">
                        Copyright © 2022 侵权请联系<a href="mailto:2656653265@qq.com">2656653265@qq.com</a>   
                        <a href="https://beian.miit.gov.cn/" target="_blank">京ICP备2022015340号-1</a>
                    </div>
                    <div style="width:300px;margin:0 auto; padding:0px 5px;">
                        <a href="/regex.html">正则表达式工具</a>
                        <a href="/cron.html">cron表达式工具</a>
                        <a href="/pwdcreator.html">密码生成工具</a>
                    </div>
                    <div style="width:300px;margin:0 auto; padding:5px 0;">
                        <a target="_blank" href="http://www.beian.gov.cn/portal/registerSystemInfo?recordcode=11010502049817" style="display:inline-block;text-decoration:none;height:20px;line-height:20px;">
                        <img src="" style="float:left;" /><p style="float:left;height:20px;line-height:20px;margin: 0px 0px 0px 5px; color:#939393;">京公网安备 11010502049817号</p></a>
                    </div>
                </div>
            </div>
        </div>
      
    </nav>
    <!--footer-->
    
        <!--footer模板结束-->
    
        <script src="/js/plugins/jquery/jquery.js"></script>
        <script src="/js/bootstrap.min.js"></script>
    
        <!--这里是scripts模板-->
        
    
        
     
    
    
        <!--scripts模板结束-->
    
    </body>
    </html>