kubernetespod详解2

kubernetespod详解2

pod生命周期

我们一般将pod对象从创建至终的这段时间范围称为pod的生命周期,它主要包含下面的过程:
pod创建过程
运行初始化容器(init container)过程
运行主容器(main container)
容器启动后钩子(post start)、容器终止前钩子(pre stop)
容器的存活性探测(liveness probe)、就绪性探测(readiness probe)
pod终止过程
kubernetespod详解2_第1张图片

在整个生命周期中,Pod会出现5种状态(相位),分别如下:
• 挂起(Pending):apiserver已经创建了pod资源对象,但它尚未被调度完成或者仍处于下载镜像的过程中
• 运行中(Running):pod已经被调度至某节点,并且所有容器都已经被kubelet创建完成
• 成功(Succeeded):pod中的所有容器都已经成功终止并且不会被重启
• 失败(Failed):所有容器都已经终止,但至少有一个容器终止失败,即容器返回了非0值的退出状态
• 未知(Unknown):apiserver无法正常获取到pod对象的状态信息,通常由网络通信失败所导致

创建和终止

pod的创建过程
1、用户通过kubectl或其他api客户端提交需要创建的pod信息给apiServer
2、apiServer开始生成pod对象的信息,并将信息存入etcd,然后返回确认信息至客户端
3、apiServer开始反映etcd中的pod对象的变化,其它组件使用watch机制来跟踪检查apiServer上的变动
4、scheduler发现有新的pod对象要创建,开始为Pod分配主机并将结果信息更新至apiServer
5、node节点上的kubelet发现有pod调度过来,尝试调用docker启动容器,并将结果回送至apiServer
6、apiServer将接收到的pod状态信息存入etcd中

kubernetespod详解2_第2张图片

pod的终止过程

  1. 用户向apiServer发送删除pod对象的命令
  2. apiServcer中的pod对象信息会随着时间的推移而更新,在宽限期内(默认30s),pod被视为dead
  3. 将pod标记为terminating状态
  4. kubelet在监控到pod对象转为terminating状态的同时启动pod关闭过程
  5. 节点控制器监控到pod对象的关闭行为时将其从所有匹配到此节点的service资源的节点列表中移除
  6. 如果当前pod对象定义了preStop钩子处理器,则在其标记为terminating后即会以同步的方式启动执行
  7. pod对象中的容器进程收到停止信号
  8. 宽限期结束后,若pod中还存在仍在运行的进程,那么pod对象会收到立即终止的信号
  9. kubelet请求apiServer将此pod资源的宽限期设置为0从而完成删除操作,此时pod对于用户已不可见

初始化容器

初始化容器是在pod的主容器启动之前要运行的容器,主要是做一些主容器的前置工作,它具有两大特征:
1、初始化容器必须运行完成直至结束,若某初始化容器运行失败,那么kubernetes需要重启它直到成功完成
2、初始化容器必须按照定义的顺序执行,当且仅当前一个成功之后,后面的一个才能运行
初始化容器有很多的应用场景,下面列出的是最常见的几个:
• 提供主容器镜像中不具备的工具程序或自定义代码
• 初始化容器要先于应用容器串行启动并运行完成,因此可用于延后应用容器的启动直至其依赖的条件得到满足
接下来做一个案例,模拟下面这个需求:
假设要以主容器来运行nginx,但是要求在运行nginx之前先要能够连接上mysql和redis所在服务器
为了简化测试,事先规定好mysql(192.168.226.3)和redis(192.168.226.4)服务器的地址
创建pod-initcontainer.yaml,内容如下:


apiVersion: v1
kind: Pod
metadata:
  name: pod-initcontainer
  namespace: lh
spec:
  containers:
  - name: main-container
    image: nginx:latest
    ports:
    - name: nginx-port
      containerPort: 80
  initContainers:
  - name: test-mysql
    image: busybox:latest
    command: ['sh', '-c', 'until ping 192.168.226.3 -c 1 ; do echo waiting for mysql...; sleep 2; done;']
  - name: test-redis
    image: busybox:latest
    command: ['sh', '-c', 'until ping 192.168.226.4 -c 1 ; do echo waiting for reids...; sleep 2; done;']

创建容器

[root@master ~]# kubectl create -f  pod-initcontainer.yaml
pod/pod-initcontainer created
[root@master ~]# kubectl get pod -n lh
NAME                READY   STATUS     RESTARTS   AGE
pod-initcontainer   0/1     Init:0/2   0          15s
[root@master ~]# kubectl create pod-initcontainer.yaml
......
Events:
  Type    Reason     Age   From               Message
  ----    ------     ----  ----               -------
  Normal  Scheduled  67s   default-scheduler  Successfully assigned lh/pod-initcontainer to node2.example.com
  Normal  Pulling    67s   kubelet            Pulling image "busybox:latest"
  Normal  Pulled     64s   kubelet            Successfully pulled image "busybox:latest" in 2.769871076s
  Normal  Created    64s   kubelet            Created container test-mysql
  Normal  Started    64s   kubelet            Started container test-mysql

此时发现容器无法启动,pod卡在启动第一个初始化容器过程中,后面的容器不会运行

钩子函数

钩子函数能够感知自身生命周期中的事件,并在相应的时刻到来时运行用户指定的程序代码。
kubernetes在主容器的启动之后和停止之前提供了两个钩子函数:
• post start:容器创建之后执行,如果失败了会重启容器
• pre stop :容器终止之前执行,执行完成之后容器将成功终止,在其完成之前会阻塞删除容器的操作
钩子处理器支持使用下面三种方式定义动作:
Exec命令:在容器内执行一次命令


……
lifecycle:

  postStart: 

    exec:

      command:

      - cat

      - /tmp/healthy


TCPSocket:在当前容器尝试访问指定的socket


……      
lifecycle:

  postStart:

    tcpSocket:

      port: 8080

……

HTTPGet:在当前容器中向某url发起http请求


……
lifecycle:

  postStart:

    httpGet:

      path: / #URI地址

      port: 80 #端口号

      host: 192.168.5.3 #主机地址

      scheme: HTTP #支持的协议,http或者https

……

接下来,以exec方式为例,演示下钩子函数的使用,创建pod-exec.yaml文件

apiVersion: v1
kind: Pod
metadata:
  name: pod-hook-exec
  namespace: lh
spec:
  containers:
  - name: main-container
    image: nginx:1.17.1
    ports:
    - name: nginx-port
      containerPort: 80
    lifecycle:
      postStart: 
        exec: //容器启动时执行修改nginx默认网页类容 
          command: ["/bin/sh", "-c", "echo helloworld > /usr/share/nginx/html/index.html"]
      preStop:
        exec:  //容器停止之前关闭nginx服务
          command: ["/usr/sbin/nginx","-s","quit"]


创建pod


[root@master ~]# kubectl create -f pod-exec.yaml
pod/pod-hook-exec created
[root@master ~]# kubectl get pod -n lh
NAME                READY   STATUS     RESTARTS   AGE
pod-hook-exec       1/1     Running    0          28s

访问pod


[root@master ~]# curl http://10.244.1.14
helloworld

容器探测

容器探测用于检测容器中的应用实例是否正常工作,是保障业务可用性的一种传统机制。如果经过探测,实例的状态不符合预期,那么kubernetes就会把该问题实例" 摘除 ",不承担业务流量。kubernetes提供了两种探针来实现容器探测,分别是:
• liveness probes:存活性探针,用于检测应用实例当前是否处于正常运行状态,如果不是,k8s会重启容器
• readiness probes:就绪性探针,用于检测应用实例当前是否可以接收请求,如果不能,k8s不会转发流量
livenessProbe 决定是否重启容器,readinessProbe 决定是否将请求转发给容器。
上面两种探针目前均支持三种探测方式:
Exec命令:在容器内执行一次命令,如果命令执行的退出码为0,则认为程序正常,否则不正常



……
livenessProbe:

  exec:

    command:

    - cat

    - /tmp/healthy

……

TCPSocket:将会尝试访问一个用户容器的端口,如果能够建立这条连接,则认为程序正常,否则不正常


……      
livenessProbe:

  tcpSocket:

    port: 8080

……


HTTPGet:调用容器内Web应用的URL,如果返回的状态码在200和399之间,则认为程序正常,否则不正常


……
livenessProbe:

  httpGet:

    path: / #URI地址

    port: 80 #端口号

    host: 127.0.0.1 #主机地址

    scheme: HTTP #支持的协议,http或者https

……

下面以liveness probes为例,做几个演示:

exec

创建pod-liveness-exec.yaml



apiVersion: v1
kind: Pod
metadata:
  name: pod-liveness-exec
  namespace: lh
spec:
  containers:
  - name: nginx
    image: nginx:latest
    ports: 
    - name: nginx-port
      containerPort: 80
    livenessProbe:
      exec:
        command: ["/bin/cat","/root/123"]

创建查看效果

[root@master ~]# kubectl create -f pod-liveness-exec.yaml
pod/pod-liveness-exec created


[root@master ~]# kubectl describe pods pod-liveness-exec -n lh
  Type     Reason     Age               From               Message
  ----     ------     ----              ----               -------
  Normal   Scheduled  44s               default-scheduler  Successfully assigned lh/pod-liveness-exec to node2.example.com
  Warning  Failed     42s               kubelet            Failed to pull image "nginx:latest": rpc error: code = Unknown desc = failed to pull and unpack image "docker.io/library/nginx:latest": failed to resolve reference "docker.io/library/nginx:latest": failed to authorize: failed to fetch anonymous token: Get "https://auth.docker.io/token?scope=repository%3Alibrary%2Fnginx%3Apull&service=registry.docker.io": read tcp 192.168.226.30:57024->44.205.64.79:443: read: connection reset by peer
  Warning  Failed     42s               kubelet            Error: ErrImagePull
  Normal   BackOff    41s               kubelet            Back-off pulling image "nginx:latest"
  Warning  Failed     41s               kubelet            Error: ImagePullBackOff
  Normal   Pulled     25s               kubelet            Successfully pulled image "nginx:latest" in 2.854548687s
  Warning  Unhealthy  4s (x3 over 24s)  kubelet            Liveness probe failed: /bin/cat: /root/123: No such file or directory
  Normal   Killing    4s                kubelet            Container nginx failed liveness probe, will be restarted
  Normal   Pulling    3s (x3 over 43s)  kubelet            Pulling image "nginx:latest"
  Normal   Created    1s (x2 over 25s)  kubelet            Created container nginx
  Normal   Started    1s (x2 over 24s)  kubelet            Started container nginx
  Normal   Pulled     1s                kubelet            Successfully pulled image "nginx:latest" in 2.645598698s
[root@master ~]# kubectl get pod pod-liveness-exec -n lh
NAME                READY   STATUS             RESTARTS      AGE
pod-liveness-exec   0/1     CrashLoopBackOff   4 (31s ago)   3m11s

观察上面的信息就会发现nginx容器启动之后就进行了健康检查 检查失败之后,容器被kill掉,然后尝试进行重启,等待一下,再观察pod信息,就可以看到RESTARTS不再是0,而是一直增长

TCPSocket

创建pod-liveness-tcpsocket.yaml


apiVersion: v1
kind: Pod
metadata:
  name: pod-liveness-tcpsocket
  namespace: lh
spec:
  containers:
  - name: nginx
    image: nginx:latest
    ports: 
    - name: nginx-port
      containerPort: 80
    livenessProbe:
      tcpSocket:
        port: 8080

创建并查看效果


[root@master ~]# kubectl create -f pod-liveness-tcpsocket.yaml
pod/pod-liveness-tcpsocket created

[root@master ~]# kubectl describe pods pod-liveness-tcpsocket -n lh
.........
Events:
  Type     Reason     Age               From               Message
  ----     ------     ----              ----               -------
  Normal   Scheduled  20s               default-scheduler  Successfully assigned lh/pod-liveness-tcpsocket to node2.example.com
  Normal   Pulling    20s               kubelet            Pulling image "nginx:latest"
  Normal   Pulled     17s               kubelet            Successfully pulled image "nginx:latest" in 2.943589962s
  Normal   Created    17s               kubelet            Created container nginx
  Normal   Started    17s               kubelet            Started container nginx
  Warning  Unhealthy  0s (x2 over 10s)  kubelet            Liveness probe failed: dial tcp 10.244.2.20:8080: connect: connection refused
[root@master ~]# kubectl get pod -n lh
NAME                     READY   STATUS             RESTARTS        AGE
pod-liveness-tcpsocket   0/1     CrashLoopBackOff   4 (11s ago)     2m41s

观察上面的信息,发现尝试访问8080端口,但是失败了稍等一会之后,再观察pod信息,就可以看到RESTARTS不再是0,而是一直增长,当然如果将端口修改成能访问的端口就恢复正常了

HTTPGet

创建pod-liveness-httpget.yaml


apiVersion: v1
kind: Pod
metadata:
  name: pod-liveness-httpget
  namespace: lh
spec:
  containers:
  - name: nginx
    image: nginx:latest
    ports:
    - name: nginx-port
      containerPort: 80
    livenessProbe:
      httpGet: 
        scheme: HTTP 
        port: 80 
        path: /hello 

创建pod观看效果



[root@master ~]# kubectl create -f pod-liveness-httpget.yaml
pod/pod-liveness-httpget created
[root@master ~]#  kubectl describe pod pod-liveness-httpget -n lh
Events:
  Type     Reason     Age   From               Message
  ----     ------     ----  ----               -------
  Normal   Scheduled  18s   default-scheduler  Successfully assigned lh/pod-liveness-httpget to node1.example.com
  Normal   Pulling    16s   kubelet            Pulling image "nginx:latest"
  Normal   Pulled     13s   kubelet            Successfully pulled image "nginx:latest" in 2.661896334s
  Normal   Created    13s   kubelet            Created container nginx
  Normal   Started    13s   kubelet            Started container nginx
  Warning  Unhealthy  6s    kubelet            Liveness probe failed: HTTP probe failed with statuscode: 404

观察上面信息,尝试访问路径,但是未找到,出现404错误# 稍等一会之后,再观察pod信息,就可以看到RESTARTS不再是0,而是一直增长


[root@master ~]# kubectl get pod -n lh
NAME                     READY   STATUS             RESTARTS         AGE
pod-liveness-httpget     1/1     Running            2 (6s ago)       68s

至此,已经使用liveness Probe演示了三种探测方式,但是查看livenessProbe的子属性,会发现除了这三种方式,还有一些其他的配置,在这里一并解释下:


[root@master ~]# kubectl explain pod.spec.containers.livenessProbe
FIELDS:
   exec   
   tcpSocket    
   httpGet      
   initialDelaySeconds    # 容器启动后等待多少秒执行第一次探测
   timeoutSeconds         # 探测超时时间。默认1秒,最小1秒
   periodSeconds          # 执行探测的频率。默认是10秒,最小1秒
   failureThreshold       # 连续探测失败多少次才被认定为失败。默认是3。最小值是1
   successThreshold       # 连续探测成功多少次才被认定为成功。默认是1

 
  

下面稍微配置两个,演示下效果即可:


apiVersion: v1
kind: Pod
metadata:
  name: pod-liveness-httpget
  namespace: lh
spec:
  containers:
  - name: nginx
    image: nginx:latest
    ports:
    - name: nginx-port
      containerPort: 80
    livenessProbe:
      httpGet:
        scheme: HTTP
        port: 80 
        path: /
      initialDelaySeconds: 30 # 容器启动后30s开始探测
      timeoutSeconds: 5 # 探测超时时间为5s

重启策略

kubernetees中,一旦容器探测出现了问题,kubernetes就会对容器所在的Pod进行重启,其实这是由pod的重启策略决定的,pod的重启策略有 3 种,分别如下:
Always :容器失效时,自动重启该容器,这也是默认值。
• OnFailure : 容器终止运行且退出码不为0时重启
• Never : 不论状态为何,都不重启该容器
重启策略适用于pod对象中的所有容器,首次需要重启的容器,将在其需要时立即进行重启,随后再次需要重启的操作将由kubelet延迟一段时间后进行,且反复的重启操作的延迟时长以此为10s、20s、40s、80s、160s和300s,300s是最大延迟时长。
创建pod-resartpolicy.yaml


apiVersion: v1
kind: Pod
metadata:
  name: pod-restartpolicy
  namespace: lh
spec:
  containers:
  - name: nginx
    image: nginx:latest
    ports:
    - name: nginx-port
      containerPort: 80
    livenessProbe:
      httpGet:
        scheme: HTTP
        port: 80
        path: /hello
  restartPolicy: Never

此处我设置的调度策略为never即不重启容器
创建pod并查看结果

[root@master ~]# kubectl create -f pod-resartpolicy.yaml
pod/pod-restartpolicy created
[root@master ~]#  kubectl  describe pods pod-restartpolicy  -n lh
..........
Events:
  Type     Reason     Age               From               Message
  ----     ------     ----              ----               -------
  Normal   Scheduled  21s               default-scheduler  Successfully assigned lh/pod-restartpolicy to node1.example.com
  Normal   Pulling    20s               kubelet            Pulling image "nginx:latest"
  Normal   Pulled     17s               kubelet            Successfully pulled image "nginx:latest" in 2.821851538s
  Normal   Created    17s               kubelet            Created container nginx
  Normal   Started    17s               kubelet            Started container nginx
  Warning  Unhealthy  0s (x2 over 10s)  kubelet            Liveness probe failed: HTTP probe failed with statuscode: 404



查看Pod详情,发现nginx容器失败,多等一会,再观察pod的重启次数,发现一直是0,并未重启

[root@master ~]# kubectl get pod -n lh
NAME                     READY   STATUS             RESTARTS         AGE
pod-restartpolicy        0/1     Completed          0                105s


pod调度

在默认情况下,一个Pod在哪个Node节点上运行,是由Scheduler组件采用相应的算法计算出来的,这个过程是不受人工控制的。但是在实际使用中,这并不满足的需求,因为很多情况下,我们想控制某些Pod到达某些节点上,那么应该怎么做呢?这就要求了解kubernetes对Pod的调度规则,kubernetes提供了四大类调度方式:
• 自动调度:运行在哪个节点上完全由Scheduler经过一系列的算法计算得出
• 定向调度:NodeName、NodeSelector
• 亲和性调度:NodeAffinity、PodAffinity、PodAntiAffinity
• 污点(容忍)调度:Taints、Toleration

定向调度

定向调度,指的是利用在pod上声明nodeName或者nodeSelector,以此将Pod调度到期望的node节点上。注意,这里的调度是强制的,这就意味着即使要调度的目标Node不存在,也会向上面进行调度,只不过pod运行失败而已。

NodeName

NodeName用于强制约束将Pod调度到指定的Name的Node节点上。这种方式,其实是直接跳过Scheduler的调度逻辑,直接将Pod调度到指定名称的节点。
接下来,实验一下:创建一个pod-nodename.yaml文件


apiVersion: v1
kind: Pod
metadata:
  name: pod-nodename
  namespace: lh
spec:
  containers:
  - name: nginx
    image: nginx:latest
  nodeName: node2

指定调度到node2节点中
创建pod并查看效果

[root@master ~]# kubectl create -f pod-nodename.yaml
pod/pod-nodename created
[root@master ~]# kubectl get pod pod-nodename -n lh -o wide
NAME           READY   STATUS    RESTARTS   AGE   IP       NODE    NOMINATED NODE   READINESS GATES
pod-nodename   0/1     Pending   0          13s      node2              



可以看见已经调度node2节点中接下来删除pod,修改配置文件将pod调度到node3中,创建pod并查看效果

[root@master ~]# vim pod-nodename.yaml
 nodeName: node3

[root@master ~]# kubectl delete -f pod-nodename.yaml
pod "pod-nodename" deleted
[root@master ~]# kubectl create -f pod-nodename.yaml
pod/pod-nodename created
[root@master ~]#  kubectl get pods pod-nodename -n lh -o wide
NAME           READY   STATUS    RESTARTS   AGE   IP       NODE    NOMINATED NODE   READINESS GATES
pod-nodename   0/1     Pending   0          20s      node3              

再次查看,发现已经向Node3节点调度,但是由于不存在node3节点,所以pod无法正常运行

NodeSelector

NodeSelector用于将pod调度到添加了指定标签的node节点上。它是通过kubernetes的label-selector机制实现的,也就是说,在pod创建之前,会由scheduler使用MatchNodeSelector调度策略进行label匹配,找出目标node,然后将pod调度到目标节点,该匹配规则是强制约束。
接下来,实验一下:
1 首先分别为node节点添加标签


[root@master ~]# kubectl label nodes node1 nodeenv=pro
node/node2 labeled
[root@master ~]# kubectl label nodes node2 nodeenv=test
node/node2 labeled


创建一个pod-nodeselector.yaml文件,并使用它创建Pod



apiVersion: v1
kind: Pod
metadata:
 name: pod-nodeselector
 namespace: dev
spec:
 containers:
 - name: nginx
   image: nginx:latest
     nodeSelector: 
   nodeenv: pro


调度到有指定标签的节点中
创建pod并查看效果



[root@master ~]# kubectl create -f pod-nodeselector.yaml
pod/pod-nodeselector created
[root@master ~]# kubectl get pods pod-nodeselector -n dev -o wide
NAME               READY   STATUS    RESTARTS   AGE     IP          NODE    ......
pod-nodeselector   1/1     Running   0          52s   10.244.1.91   node1   ......

删除pod,修改nodeSelector的值为nodeenv: xxxx(不存在打有此标签的节点),再创建pod查看效果

[root@master ~]# kubectl delete -f pod-nodeselector.yaml
pod "pod-nodeselector" deleted
[root@master ~]# vim pod-nodeselector.yaml
[root@master ~]# kubectl create -f pod-nodeselector.yaml
pod/pod-nodeselector created
[root@k8s-master01 ~]# kubectl get pods -n lh -o wide
NAME               READY   STATUS    RESTARTS   AGE     IP       NODE    
pod-nodeselector   0/1     Pending   0          3m12s      
[root@k8s-master01 ~]# kubectl describe pods pod-nodeselector -n lh
.......Events:
 Type     Reason            Age        From               Message
 ----     ------            ----       ----               -------
 Warning  FailedScheduling    default-scheduler  0/3 nodes are available: 3 node(s) didn't match node selector.


亲和性调度

上一节,介绍了两种定向调度的方式,使用起来非常方便,但是也有一定的问题,那就是如果没有满足条件的Node,那么Pod将不会被运行,即使在集群中还有可用Node列表也不行,这就限制了它的使用场景。
基于上面的问题,kubernetes还提供了一种亲和性调度(Affinity)。它在NodeSelector的基础之上的进行了扩展,可以通过配置的形式,实现优先选择满足条件的Node进行调度,如果没有,也可以调度到不满足条件的节点上,使调度更加灵活。
Affinity主要分为三类:
• nodeAffinity(node亲和性): 以node为目标,解决pod可以调度到哪些node的问题
• podAffinity(pod亲和性) : 以pod为目标,解决pod可以和哪些已存在的pod部署在同一个拓扑域中的问题
• podAntiAffinity(pod反亲和性) : 以pod为目标,解决pod不能和哪些已存在pod部署在同一个拓扑域中的问题
关于亲和性(反亲和性)使用场景的说明:
亲和性:如果两个应用频繁交互,那就有必要利用亲和性让两个应用的尽可能的靠近,这样可以减少因网络通信而带来的性能损耗。
反亲和性:当应用的采用多副本部署时,有必要采用反亲和性让各个应用实例打散分布在各个node上,这样可以提高服务的高可用性。

NodeAffinity

首先查看一下NodeAffinity的可配置项:

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。
关系符的使用说明:

- 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"

接下来首先演示一下requiredDuringSchedulingIgnoredDuringExecution ,
创建pod-nodeaffinity-required.yaml

apiVersion: v1
kind: Pod
metadata:
  name: pod-nodeaffinity-required
  namespace: lh
spec:
  containers:
  - name: nginx
    image: nginx:latest
  affinity:  
    nodeAffinity: 
      requiredDuringSchedulingIgnoredDuringExecution: 
        nodeSelectorTerms:
        - matchExpressions: 
          - key: nodeenv
            operator: In
            values: ["xxx","yyy"]

创建pod并查看效果

[root@master ~]# kubectl create -f pod-nodeaffinity-required.yaml
pod/pod-nodeaffinity-required created
[root@master ~]# kubectl get pods pod-nodeaffinity-required -n lh -o wide
NAME                        READY   STATUS    RESTARTS   AGE   IP       NODE    ...... 
pod-nodeaffinity-required   0/1     Pending   0          12s        ......
[root@master ~]# kubectl describe pod pod-nodeaffinity-required -n lh
......
  Warning  FailedScheduling    default-scheduler  0/3 nodes are available: 3 node(s) didn't match node selector.
  Warning  FailedScheduling    default-scheduler  0/3 nodes are available: 3 node(s) didn't match node selector.

将pod删除修改文件,将values: [“xxx”,“yyy”]------> [“pro”,“yyy”],再创建pod并查看效果

[root@master ~]# kubectl delete -f pod-nodeaffinity-required.yaml
pod "pod-nodeaffinity-required" deleted
[root@master ~]# vim pod-nodeaffinity-required.yaml
[root@master ~]# kubectl create -f pod-nodeaffinity-required.yaml
pod/pod-nodeaffinity-required created
[root@master ~]# kubectl get pods pod-nodeaffinity-required -n lh -o wide
NAME                        READY   STATUS    RESTARTS   AGE   IP            NODE  ...... 
pod-nodeaffinity-required   1/1     Running   0          5m46s   10.244.1.79   node1 ......

演示requiredDuringSchedulingIgnoredDuringExecution ,
创建pod-nodeaffinity-preferred.yaml

apiVersion: v1
kind: Pod
metadata:
  name: pod-nodeaffinity-preferred
  namespace: lh
spec:
  containers:
  - name: nginx
    image: nginx:latest
  affinity:  
    nodeAffinity: 
      preferredDuringSchedulingIgnoredDuringExecution: 
      - weight: 1
        preference:
          matchExpressions: 
          - key: nodeenv
            operator: In
            values: ["xxx","yyy"]

创建pod,并查看结果

[root@master ~]# kubectl create -f pod-nodeaffinity-preferred.yaml
pod/pod-nodeaffinity-preferred created
[root@master ~]# kubectl get pod pod-nodeaffinity-preferred -n lh
NAME                         READY   STATUS    RESTARTS   AGE
pod-nodeaffinity-preferred   1/1     Running   0          8s

NodeAffinity规则设置的注意事项:
1 如果同时定义了nodeSelector和nodeAffinity,那么必须两个条件都得到满足,Pod才能运行在指定的Node上
2 如果nodeAffinity指定了多个nodeSelectorTerms,那么只需要其中一个能够匹配成功即可
3 如果一个nodeSelectorTerms中有多个matchExpressions ,则一个节点必须满足所有的才能匹配成功
4 如果一个pod所在的Node在Pod运行期间其标签发生了改变,不再符合该Pod的节点亲和性需求,则系统将忽略此变化
PodAffinity
PodAffinity主要实现以运行的Pod为参照,实现让新创建的Pod跟参照pod在一个区域的功能。
首先来看一下PodAffinity的可配置项:

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
topologyKey用于指定调度时作用域,例如:
    如果指定为kubernetes.io/hostname,那就是以Node节点为区分范围
    如果指定为beta.kubernetes.io/os,则以Node节点的操作系统类型来区分

接下来,演示requiredDuringSchedulingIgnoredDuringExecution,
创建一个参照Pod,pod-podaffinity-target.yaml:

apiVersion: v1
kind: Pod
metadata:
  name: pod-podaffinity-target
  namespace: lh
  labels:
    podenv: pro 
spec:
  containers:
  - name: nginx
    image: nginx:latest
  nodeName: node1  

启动目标pod,并查看pod状态

[root@master ~]# kubectl create -f pod-podaffinity-target.yaml
pod/pod-podaffinity-target created
[root@k8s-master01 ~]# kubectl get pods  pod-podaffinity-target -n lh
NAME                     READY   STATUS    RESTARTS   AGE
pod-podaffinity-target   1/1     Running   0          23s

创建pod-podaffinity-required.yaml,内容如下:

apiVersion: v1
kind: Pod
metadata:
  name: pod-podaffinity-required
  namespace: lh
spec:
  containers:
  - name: nginx
    image: nginx:latest
  affinity:  
    podAffinity: 
      requiredDuringSchedulingIgnoredDuringExecution: 
      - labelSelector:
          matchExpressions: 
          - key: podenv
            operator: In
            values: ["xxx","yyy"]
        topologyKey: kubernetes.io/hostname

上面配置表达的意思是:新Pod必须要与拥有标签nodeenv=xxx或者nodeenv=yyy的pod在同一Node上,显然现在没有这样pod,接下来,运行测试一下。
启动pod并查看状态

[root@master ~]# kubectl create -f pod-podaffinity-required.yaml
pod/pod-podaffinity-required created

[root@master ~]# kubectl get pods pod-podaffinity-required -n lh
NAME                       READY   STATUS    RESTARTS   AGE
pod-podaffinity-required   0/1     Pending   0          1m5s
[root@k8s-master01 ~]# kubectl describe pods pod-podaffinity-required  -n lh
......Events:
  Type     Reason            Age        From               Message
  ----     ------            ----       ----               -------
  Warning  FailedScheduling    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上,然后重新创建pod查看效果

[root@master ~]# vim pod-podaffinity-required.yaml

[root@master ~]# kubectl delete -f  pod-podaffinity-required.yaml
pod "pod-podaffinity-required" deleted
[root@master ~]# kubectl create -f pod-podaffinity-required.yaml
pod/pod-podaffinity-required created
[root@master ~]# kubectl get pods pod-podaffinity-required -n lh
NAME                       READY   STATUS    RESTARTS   AGE   LABELS
pod-podaffinity-required   1/1     Running   0          3m15s    

关于PodAffinity的 preferredDuringSchedulingIgnoredDuringExecution,这里不再演示。
PodAntiAffinity
PodAntiAffinity主要实现以运行的Pod为参照,让新创建的Pod跟参照pod不在一个区域中的功能。
它的配置方式和选项跟PodAffinty是一样的,这里不再做详细解释,直接做一个测试案例。
继续使用上个案例中目标pod

[root@master ~]# kubectl get pods -n lh -o wide --show-labels
NAME                     READY   STATUS    RESTARTS   AGE     IP            NODE    LABELS
pod-podaffinity-required 1/1     Running   0          10m46s   10.244.1.38   node1        
pod-podaffinity-target   1/1     Running   0          17m25s   10.244.1.37   node1   podenv=pro

创建pod-podantiaffinity-required.yaml,内容如下:

apiVersion: v1
kind: Pod
metadata:
  name: pod-podantiaffinity-required
  namespace: lh
spec:
  containers:
  - name: nginx
    image: nginx:latest
  affinity:  
    podAntiAffinity: 
      requiredDuringSchedulingIgnoredDuringExecution: 
      - labelSelector:
          matchExpressions: 
          - key: podenv
            operator: In
            values: ["pro"]
        topologyKey: kubernetes.io/hostname

上面配置表达的意思是:新Pod必须要与拥有标签nodeenv=pro的pod不在同一Node上,运行测试一下。
创建pod

[root@master ~]# kubectl create -f pod-podantiaffinity-required.yaml
pod/pod-podantiaffinity-required created

查看pod 发现调度到了node2上

[root@master ~]# kubectl get pods pod-podantiaffinity-required -n lh -o wide
NAME                           READY   STATUS    RESTARTS   AGE   IP            NODE   .. 
pod-podantiaffinity-required   1/1     Running   0          3m7s   10.244.1.96   node2  ..

你可能感兴趣的:(docker,运维,容器)