0%

k8s学习日记day5

kubernetes的Pod详解二

3 Pod的生命周期

3.1 概述

  • 我们一般将Pod对象从创建到终止的这段时间范围称为Pod的生命周期,它主要包含下面的过程:

    • Pod创建过程。
    • 运行初始化容器(init container)过程。
    • 运行主容器(main container):
      • 容器启动后钩子(post start)、容器终止前钩子(pre stop)。
      • 容器的存活性探测(liveness probe)、就绪性探测(readiness probe)。
    • Pod终止过程。
  • 在整个生命周期中,Pod会出现5种状态(相位),分别如下:

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

3.2 创建和终止

3.2.1 Pod的创建过程

  • ① 用户通过kubectl或其他的api客户端提交需要创建的Pod信息给API Server。

  • ② API Server开始生成Pod对象的信息,并将信息存入etcd,然后返回确认信息至客户端。

  • ③ API Server开始反映etcd中的Pod对象的变化,其它组件使用watch机制来跟踪检查API Server上的变动。

  • ④ Scheduler发现有新的Pod对象要创建,开始为Pod分配主机并将结果信息更新至API Server。

  • ⑤ Node节点上的kubelet发现有Pod调度过来,尝试调度Docker启动容器,并将结果回送至API Server。

  • ⑥ API Server将接收到的Pod状态信息存入到etcd中。

3.2.2 Pod的终止过程

  • ① 用户向API Server发送删除Pod对象的命令。

  • ② API Server中的Pod对象信息会随着时间的推移而更新,在宽限期内(默认30s),Pod被视为dead。

  • ③ 将Pod标记为terminating状态。

  • ④ kubelete在监控到Pod对象转为terminating状态的同时启动Pod关闭过程。

  • ⑤ 端点控制器监控到Pod对象的关闭行为时将其从所有匹配到此端点的service资源的端点列表中移除。

  • ⑥ 如果当前Pod对象定义了preStop钩子处理器,则在其标记为terminating后会以同步的方式启动执行。

  • ⑦ Pod对象中的容器进程收到停止信号。

  • ⑧ 宽限期结束后,如果Pod中还存在运行的进程,那么Pod对象会收到立即终止的信号。

  • ⑨ kubectl请求API Server将此Pod资源的宽限期设置为0从而完成删除操作,此时Pod对于用户已经不可用了。

3.3 初始化容器

  • 初始化容器是在Pod的主容器启动之前要运行的容器,主要是做一些主容器的前置工作,它具有两大特征:

    • ① 初始化容器必须运行完成直至结束,如果某个初始化容器运行失败,那么kubernetes需要重启它直至成功完成。
    • ② 初始化容器必须按照定义的顺序执行,当且仅当前一个成功之后,后面的一个才能运行。
  • 初始化容器有很多的应用场景,下面列出的是最常见的几个:

    • 提供主容器镜像中不具备的工具程序或自定义代码。
    • 初始化容器要先于应用容器串行启动并运行完成,因此可用于延后应用容器的启动直至其依赖的条件得到满足。
  • 接下来做一个案例,模拟下面这个需求:

    • 假设要以主容器来运行Nginx,但是要求在运行Nginx之前要能够连接上MySQL和Redis所在的服务器。
    • 为了简化测试,事先规定好MySQL和Redis所在的IP地址分别为192.168.20.201和192.168.18.202(注意,这两个IP都不能ping通,因为环境中没有这两个IP)。
  • 创建pod-initcontainer.yaml文件,内容如下:

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
[root@master ~]# cat pod-initcontainer.yaml 
apiVersion: v1
kind: Pod
metadata:
name: pod-initcontainer
namespace: dev
labels:
user: xudaxian
spec:
containers: # 容器配置
- name: nginx
image: 192.168.20.119/library/nginx:latest
imagePullPolicy: IfNotPresent
ports:
- name: nginx-port
containerPort: 80
protocol: TCP
resources:
limits:
cpu: "2"
memory: "10Gi"
requests:
cpu: "1"
memory: "10Mi"
initContainers: # 初始化容器配置
- name: test-mysql
image: 192.168.20.119/library/busybox:latest
command: ["sh","-c","until ping 192.168.20.201 -c 1;do echo waiting for mysql ...;sleep 2;done;"]
securityContext:
privileged: true # 使用特权模式运行容器
- name: test-redis
image: 192.168.20.119/library/busybox:latest
command: ["sh","-c","until ping 192.168.20.202 -c 1;do echo waiting for redis ...;sleep 2;done;"]
  • 创建Pod:
1
2
[root@master ~]# kubectl create -f pod-initcontainer.yaml 
pod/pod-initcontainer created
  • 查看Pod状态:
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
[root@master ~]# kubectl describe pods pod-initcontainer -n dev
Name: pod-initcontainer
Namespace: dev
Priority: 0
Node: master/192.168.20.119
Start Time: Thu, 26 May 2022 04:58:23 +0000
Labels: user=xudaxian
Annotations: <none>
Status: Pending
IP: 10.244.0.9
IPs:
IP: 10.244.0.9
Init Containers:
test-mysql:
Container ID: docker://17eb2b7998b26557b75100f8ac6dc613b69a1e3113f9deaab18d7914b2b8881f
Image: 192.168.20.119/library/busybox:latest
Image ID: docker-pullable://192.168.20.119/library/busybox@sha256:2ca5e69e244d2da7368f7088ea3ad0653c3ce7aaccd0b8823d11b0d5de956002
Port: <none>
Host Port: <none>
Command:
sh
-c
until ping 192.168.20.201 -c 1;do echo waiting for mysql ...;sleep 2;done;
State: Running
Started: Thu, 26 May 2022 04:58:24 +0000
Ready: False
Restart Count: 0
Environment: <none>
Mounts:
/var/run/secrets/kubernetes.io/serviceaccount from default-token-7sxn4 (ro)
test-redis:
Container ID:
Image: 192.168.20.119/library/busybox:latest
Image ID:
Port: <none>
Host Port: <none>
Command:
sh
-c
until ping 192.168.20.202 -c 1;do echo waiting for redis ...;sleep 2;done;
State: Waiting
Reason: PodInitializing
Ready: False
Restart Count: 0
Environment: <none>
Mounts:
/var/run/secrets/kubernetes.io/serviceaccount from default-token-7sxn4 (ro)
Containers:
nginx:
Container ID:
Image: 192.168.20.119/library/nginx:latest
Image ID:
Port: 80/TCP
Host Port: 0/TCP
State: Waiting
Reason: PodInitializing
Ready: False
Restart Count: 0
Limits:
cpu: 2
memory: 10Gi
Requests:
cpu: 1
memory: 10Mi
Environment: <none>
Mounts:
/var/run/secrets/kubernetes.io/serviceaccount from default-token-7sxn4 (ro)
Conditions:
Type Status
Initialized False
Ready False
ContainersReady False
PodScheduled True
Volumes:
default-token-7sxn4:
Type: Secret (a volume populated by a Secret)
SecretName: default-token-7sxn4
Optional: false
QoS Class: Burstable
Node-Selectors: <none>
Tolerations: node.kubernetes.io/not-ready:NoExecute for 300s
node.kubernetes.io/unreachable:NoExecute for 300s
Events:
Type Reason Age From Message

---- ------ ---- ---- -------

Normal Scheduled 30s default-scheduler Successfully assigned dev/pod-initcontainer to master
Normal Pulling 29s kubelet, master Pulling image "192.168.20.119/library/busybox:latest"
Normal Pulled 29s kubelet, master Successfully pulled image "192.168.20.119/library/busybox:latest"
Normal Created 29s kubelet, master Created container test-mysql
Normal Started 29s kubelet, master Started container test-mysql

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

  • 动态查看Pod:
1
2
3
[root@master ~]# kubectl get pods pod-initcontainer -o wide  -n dev -w
NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES
pod-initcontainer 0/1 Init:0/2 0 4m48s 10.244.0.9 master <none> <none>
  • 接下来,新开一个shell,为当前服务器(192.168.20.119)新增两个IP,观察Pod的变化:
1
2
[root@master ~]# ifconfig eth0:1 192.168.20.201 netmask 255.255.255.0 up 
[root@master ~]# ifconfig eth0:2 192.168.20.202 netmask 255.255.255.0 up

发现pod已经正确运行

1
2
3
4
5
6
[root@master ~]# kubectl get pods pod-initcontainer -o wide  -n dev -w
NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES
pod-initcontainer 0/1 Init:0/2 0 4m48s 10.244.0.9 master <none> <none>
pod-initcontainer 0/1 Init:1/2 0 7m1s 10.244.0.9 master <none> <none>
pod-initcontainer 0/1 PodInitializing 0 7m3s 10.244.0.9 master <none> <none>
pod-initcontainer 1/1 Running 0 7m4s 10.244.0.9 master <none> <none>

3.4 钩子函数

  • 钩子函数能够感知自身生命周期中的事件,并在相应的时刻到来时运行用户指定的程序代码。

  • kubernetes在主容器启动之后和停止之前提供了两个钩子函数:

    • post start:容器创建之后执行,如果失败会重启容器。
    • pre stop:容器终止之前执行,执行完成之后容器将成功终止,在其完成之前会阻塞删除容器的操作。
  • 钩子处理器支持使用下面的三种方式定义动作:

    • ① exec命令:在容器内执行一次命令。
1
2
3
4
5
6
7
8
……
lifecycle:
postStart:
exec:
command:
- cat
- /tmp/healthy
……
    • ② tcpSocket:在当前容器尝试访问指定的socket。
1
2
3
4
5
6
…… 
lifecycle:
postStart:
tcpSocket:
port: 8080
……
    • ③ httpGet:在当前容器中向某url发起HTTP请求。
1
2
3
4
5
6
7
8
9
…… 
lifecycle:
postStart:
httpGet:
path: / #URI地址
port: 80 #端口号
host: 192.168.109.100 #主机地址
scheme: HTTP #支持的协议,http或者https
……
  • 接下来,以exec方式为例,演示下钩子函数的使用,创建pod-hook-exec.yaml文件,内容如下:
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
[root@master ~]# cat pod-hook-exec.yaml 
apiVersion: v1
kind: Pod
metadata:
name: pod-hook-exec
namespace: dev
labels:
user: xudaxian
spec:
containers: # 容器配置
- name: nginx
image: 192.168.20.119/library/nginx:latest
imagePullPolicy: IfNotPresent
ports:
- name: nginx-port
containerPort: 80
protocol: TCP
resources:
limits:
cpu: "2"
memory: "10Gi"
requests:
cpu: "1"
memory: "10Mi"
lifecycle: # 生命周期配置
postStart: # 容器创建之后执行,如果失败会重启容器
exec: # 在容器启动的时候,执行一条命令,修改掉Nginx的首页内容
command: ["/bin/sh","-c","echo postStart ... > /usr/share/nginx/html/index.html"]
preStop: # 容器终止之前执行,执行完成之后容器将成功终止,在其完成之前会阻塞删除容器的操作
exec: # 在容器停止之前停止Nginx的服务
command: ["/usr/sbin/nginx","-s","quit"]
  • 创建Pod:
1
2
3
4
5
[root@master ~]# kubectl create -f pod-hook-exec.yaml 
pod/pod-hook-exec created
[root@master ~]# kubectl get pods pod-hook-exec -n dev -o wide
NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES
pod-hook-exec 1/1 Running 0 24s 10.244.2.7 node1 <none> <none>
  • 访问Pod:
1
2
[root@master ~]# curl 10.244.2.7
postStart ...

3.5 容器探测

3.5.1 概述

  • 容器探测用于检测容器中的应用实例是否正常工作,是保障业务可用性的一种传统机制。如果经过探测,实例的状态不符合预期,那么kubernetes就会把该问题实例“摘除”,不承担业务流量。kubernetes提供了两种探针来实现容器探测,分别是:

    • liveness probes:存活性探测,用于检测应用实例当前是否处于正常运行状态,如果不是,k8s会重启容器。
    • readiness probes:就绪性探测,用于检测应用实例是否可以接受请求,如果不能,k8s不会转发流量。

livenessProbe:存活性探测,决定是否重启容器。

readinessProbe:就绪性探测,决定是否将请求转发给容器。

k8s在1.16版本之后新增了startupProbe探针,用于判断容器内应用程序是否已经启动。如果配置了startupProbe探针,就会先禁止其他的探针,直到startupProbe探针成功为止,一旦成功将不再进行探测。

  • 上面两种探针目前均支持三种探测方式:

    • ① exec命令:在容器内执行一次命令,如果命令执行的退出码为0,则认为程序正常,否则不正常。
1
2
3
4
5
6
7
……
livenessProbe:
exec:
command:
- cat
- /tmp/healthy
……
    • ② tcpSocket:将会尝试访问一个用户容器的端口,如果能够建立这条连接,则认为程序正常,否则不正常。
1
2
3
4
5
……
livenessProbe:
tcpSocket:
port: 8080
……
    • ③ httpGet:调用容器内web应用的URL,如果返回的状态码在200和399之前,则认为程序正常,否则不正常。
1
2
3
4
5
6
7
8
……
livenessProbe:
httpGet:
path: / #URI地址
port: 80 #端口号
host: 127.0.0.1 #主机地址
scheme: HTTP #支持的协议,http或者https
……

3.5.2 exec方式

  • 创建pod-liveness-exec.yaml文件,内容如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
[root@master ~]# cat pod-liveness-exec.yaml 
apiVersion: v1
kind: Pod
metadata:
name: pod-liveness-exec
namespace: dev
labels:
user: xudaxian
spec:
containers: # 容器配置
- name: nginx
image: 192.168.20.119/library/nginx:latest
imagePullPolicy: IfNotPresent
ports:
- name: nginx-port
containerPort: 80
protocol: TCP
livenessProbe: # 存活性探针
exec:
command: ["/bin/cat","/tmp/hello.txt"] # 执行一个查看文件的命令,必须失败,因为根本没有这个文件
  • 查看Pod详情:
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
58
[root@master ~]# kubectl create -f pod-liveness-exec.yaml 
pod/pod-liveness-exec created
[root@master ~]# kubectl describe pod pod-liveness-exec -n dev
Name: pod-liveness-exec
Namespace: dev
Priority: 0
Node: node2/192.168.20.124
Start Time: Thu, 26 May 2022 05:22:10 +0000
Labels: user=xudaxian
Annotations: <none>
Status: Running
IP: 10.244.1.6
IPs:
IP: 10.244.1.6
Containers:
nginx:
Container ID: docker://b9a138a73f0e5137efdee4497ee710e9fd7f2ed25608577d0470c4b5a16c90fb
Image: 192.168.20.119/library/nginx:latest
Image ID: docker-pullable://192.168.20.119/library/nginx@sha256:416d511ffa63777489af47f250b70d1570e428b67666567085f2bece3571ad83
Port: 80/TCP
Host Port: 0/TCP
State: Waiting
Reason: CrashLoopBackOff
Last State: Terminated
Reason: Completed
Exit Code: 0
Started: Thu, 26 May 2022 05:25:17 +0000
Finished: Thu, 26 May 2022 05:25:47 +0000
Ready: False
Restart Count: 5
Liveness: exec [/bin/cat /tmp/hello.txt] delay=0s timeout=1s period=10s #success=1 #failure=3
Environment: <none>
Mounts:
/var/run/secrets/kubernetes.io/serviceaccount from default-token-7sxn4 (ro)
Conditions:
Type Status
Initialized True
Ready False
ContainersReady False
PodScheduled True
Volumes:
default-token-7sxn4:
Type: Secret (a volume populated by a Secret)
SecretName: default-token-7sxn4
Optional: false
QoS Class: BestEffort
Node-Selectors: <none>
Tolerations: node.kubernetes.io/not-ready:NoExecute for 300s
node.kubernetes.io/unreachable:NoExecute for 300s
Events:
Type Reason Age From Message
---- ------ ---- ---- -------
Normal Scheduled 3m56s default-scheduler Successfully assigned dev/pod-liveness-exec to node2
Normal Pulled 2m29s (x4 over 3m55s) kubelet, node2 Container image "192.168.20.119/library/nginx:latest" already present on machine
Normal Created 2m29s (x4 over 3m55s) kubelet, node2 Created container nginx
Normal Started 2m29s (x4 over 3m55s) kubelet, node2 Started container nginx
Normal Killing 2m29s (x3 over 3m29s) kubelet, node2 Container nginx failed liveness probe, will be restarted #容器 nginx 探测失败,将被重启
Warning Unhealthy 2m19s (x10 over 3m49s) kubelet, node2 Liveness probe failed: /bin/cat: /tmp/hello.txt: No such file or directory #找不到这个文件
  • 观察上面的信息就会发现nginx容器启动之后就进行了健康检查。

  • 检查失败之后,容器被kill掉,然后尝试进行重启,这是重启策略的作用。

  • 稍等一会之后,再观察Pod的信息,就会看到RESTARTS不再是0,而是一直增长。

  • 查看Pod信息:
1
2
3
[root@master ~]# kubectl get pods pod-liveness-exec -n dev -o wide
NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES
pod-liveness-exec 0/1 CrashLoopBackOff 6 7m23s 10.244.1.6 node2 <none> <none>

3.5.3 tcpSocket方式

  • 创建pod-liveness-tcpsocket.yaml文件,内容如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
[root@master ~]# cat pod-liveness-tcpsocket.yaml 
apiVersion: v1
kind: Pod
metadata:
name: pod-liveness-tcpsocket
namespace: dev
labels:
user: xudaxian
spec:
containers: # 容器配置
- name: nginx
image: 192.168.20.119/library/nginx:latest
imagePullPolicy: IfNotPresent
ports:
- name: nginx-port
containerPort: 80
protocol: TCP
livenessProbe: # 存活性探针
tcpSocket:
port: 8080 # 尝试访问8080端口,必须失败,因为Pod内部只有一个Nginx容器,而且只是监听了80端口
  • 查看Pod详情:
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
58
[root@master ~]# kubectl create -f pod-liveness-tcpsocket.yaml 
pod/pod-liveness-tcpsocket created
[root@master ~]# kubectl describe pod pod-liveness-tcpsocket -n dev
Name: pod-liveness-tcpsocket
Namespace: dev
Priority: 0
Node: node2/192.168.20.124
Start Time: Thu, 26 May 2022 05:32:55 +0000
Labels: user=xudaxian
Annotations: <none>
Status: Running
IP: 10.244.1.7
IPs:
IP: 10.244.1.7
Containers:
nginx:
Container ID: docker://e5dfd067ca2dec264240e256726ed74eacf86ddbb97fa8a4a69ec6420b9d5525
Image: 192.168.20.119/library/nginx:latest
Image ID: docker-pullable://192.168.20.119/library/nginx@sha256:416d511ffa63777489af47f250b70d1570e428b67666567085f2bece3571ad83
Port: 80/TCP
Host Port: 0/TCP
State: Running
Started: Thu, 26 May 2022 05:33:19 +0000
Last State: Terminated
Reason: Completed
Exit Code: 0
Started: Thu, 26 May 2022 05:32:56 +0000
Finished: Thu, 26 May 2022 05:33:18 +0000
Ready: True
Restart Count: 1
Liveness: tcp-socket :8080 delay=0s timeout=1s period=10s #success=1 #failure=3
Environment: <none>
Mounts:
/var/run/secrets/kubernetes.io/serviceaccount from default-token-7sxn4 (ro)
Conditions:
Type Status
Initialized True
Ready True
ContainersReady True
PodScheduled True
Volumes:
default-token-7sxn4:
Type: Secret (a volume populated by a Secret)
SecretName: default-token-7sxn4
Optional: false
QoS Class: BestEffort
Node-Selectors: <none>
Tolerations: node.kubernetes.io/not-ready:NoExecute for 300s
node.kubernetes.io/unreachable:NoExecute for 300s
Events:
Type Reason Age From Message
---- ------ ---- ---- -------
Normal Scheduled 31s default-scheduler Successfully assigned dev/pod-liveness-tcpsocket to node2
Normal Pulled 8s (x2 over 30s) kubelet, node2 Container image "192.168.20.119/library/nginx:latest" already present on machine
Normal Created 8s (x2 over 30s) kubelet, node2 Created container nginx
Warning Unhealthy 8s (x3 over 28s) kubelet, node2 Liveness probe failed: dial tcp 10.244.1.7:8080: connect: connection refused
Normal Killing 8s kubelet, node2 Container nginx failed liveness probe, will be restarted
Normal Started 7s (x2 over 30s) kubelet, node2 Started container nginx

观察上面的信息,发现尝试访问8080端口,但是失败了

稍等一会之后,再观察Pod的信息,就会看到RESTARTS不再是0,而是一直增长。

  • 查看Pod信息:
1
2
3
4
5
[root@master ~]# kubectl get pods pod-liveness-tcpsocket -n dev -w
NAME READY STATUS RESTARTS AGE
pod-liveness-tcpsocket 1/1 Running 3 97s
pod-liveness-tcpsocket 1/1 Running 4 114s
pod-liveness-tcpsocket 0/1 CrashLoopBackOff 4 2m24s

3.5.4 httpGet方式

  • 创建pod-liveness-httpget.yaml文件,内容如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
[root@master ~]# cat pod-liveness-httpget.yaml 
apiVersion: v1
kind: Pod
metadata:
name: pod-liveness-httpget
namespace: dev
labels:
user: xudaxian
spec:
containers: # 容器配置
- name: nginx
image: 192.168.20.119/library/nginx:latest
imagePullPolicy: IfNotPresent
ports:
- name: nginx-port
containerPort: 80
protocol: TCP
livenessProbe: # 存活性探针
httpGet: # 其实就是访问http://127.0.0.1:80/hello
port: 80 # 端口号
scheme: HTTP # 支持的协议,HTTP或HTTPS
path: /hello # URI地址
host: 127.0.0.1 # 主机地址
  • 查看Pod详情:
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
[root@master ~]# kubectl create -f pod-liveness-httpget.yaml 
pod/pod-liveness-httpget created
[root@master ~]# kubectl describe pod pod-liveness-httpget -n dev
Name: pod-liveness-httpget
Namespace: dev
Priority: 0
Node: node2/192.168.20.124
Start Time: Thu, 26 May 2022 05:38:43 +0000
Labels: user=xudaxian
Annotations: <none>
Status: Running
IP: 10.244.1.8
IPs:
IP: 10.244.1.8
Containers:
nginx:
Container ID: docker://477faf82ca2bffc2914f103b1c1d11c733c41c55c3ec0978c0b726a51fbf68bc
Image: 192.168.20.119/library/nginx:latest
Image ID: docker-pullable://192.168.20.119/library/nginx@sha256:416d511ffa63777489af47f250b70d1570e428b67666567085f2bece3571ad83
Port: 80/TCP
Host Port: 0/TCP
State: Running
Started: Thu, 26 May 2022 05:38:44 +0000
Ready: True
Restart Count: 0
Liveness: http-get http://127.0.0.1:80/hello delay=0s timeout=1s period=10s #success=1 #failure=3
Environment: <none>
Mounts:
/var/run/secrets/kubernetes.io/serviceaccount from default-token-7sxn4 (ro)
Conditions:
Type Status
Initialized True
Ready True
ContainersReady True
PodScheduled True
Volumes:
default-token-7sxn4:
Type: Secret (a volume populated by a Secret)
SecretName: default-token-7sxn4
Optional: false
QoS Class: BestEffort
Node-Selectors: <none>
Tolerations: node.kubernetes.io/not-ready:NoExecute for 300s
node.kubernetes.io/unreachable:NoExecute for 300s
Events:
Type Reason Age From Message

---- ------ ---- ---- -------

Normal Scheduled 15s default-scheduler Successfully assigned dev/pod-liveness-httpget to node2
Normal Pulled 14s kubelet, node2 Container image "192.168.20.119/library/nginx:latest" already present on machine
Normal Created 14s kubelet, node2 Created container nginx
Normal Started 14s kubelet, node2 Started container nginx
Warning Unhealthy 6s kubelet, node2 Liveness probe failed: Get http://127.0.0.1:80/hello: dial tcp 127.0.0.1:80: connect: connection refused
  • 查看Pod信息:
1
2
3
[root@master ~]# kubectl get pods pod-liveness-httpget -n dev
NAME READY STATUS RESTARTS AGE
pod-liveness-httpget 0/1 CrashLoopBackOff 6 7m32s

3.5.5 容器探测的补充

  • 上面已经使用了livenessProbe演示了三种探测方式,但是查看livenessProbe的子属性,会发现除了这三种方式,还有一些其他的配置。
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
[root@master ~]# kubectl explain pod.spec.containers.livenessProbe
KIND: Pod
VERSION: v1

RESOURCE: livenessProbe <Object>

DESCRIPTION:
Periodic probe of container liveness. Container will be restarted if the
probe fails. Cannot be updated. More info:
https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle#container-probes

Probe describes a health check to be performed against a container to
determine whether it is alive or ready to receive traffic.

FIELDS:
exec <Object>
One and only one of the following should be specified. Exec specifies the
action to take.

failureThreshold <integer>
Minimum consecutive failures for the probe to be considered failed after
having succeeded. Defaults to 3. Minimum value is 1.

httpGet <Object>
HTTPGet specifies the http request to perform.

initialDelaySeconds <integer>
Number of seconds after the container has started before liveness probes
are initiated. More info:
https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle#container-probes

periodSeconds <integer>
How often (in seconds) to perform the probe. Default to 10 seconds. Minimum
value is 1.

successThreshold <integer>
Minimum consecutive successes for the probe to be considered successful
after having failed. Defaults to 1. Must be 1 for liveness and startup.
Minimum value is 1.

tcpSocket <Object>
TCPSocket specifies an action involving a TCP port. TCP hooks not yet
supported

timeoutSeconds <integer>
Number of seconds after which the probe times out. Defaults to 1 second.
Minimum value is 1. More info:
https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle#container-probes

FIELDS:

exec

tcpSocket

httpGet

initialDelaySeconds # 容器启动后等待多少秒执行第一次探测

timeoutSeconds # 探测超时时间。默认1秒,最小1秒

periodSeconds # 执行探测的频率。默认是10秒,最小1秒

failureThreshold # 连续探测失败多少次才被认定为失败。默认是3。最小值是1

successThreshold # 连续探测成功多少次才被认定为成功。默认是1

3.6 重启策略

  • 在容器探测中,一旦容器探测出现了问题,kubernetes就会对容器所在的Pod进行重启,其实这是由Pod的重启策略决定的,Pod的重启策略有3种,分别如下:

    • Always:容器失效时,自动重启该容器,默认值。
    • OnFailure:容器终止运行且退出码不为0时重启。
    • Never:不论状态如何,都不重启该容器。
  • 重启策略适用于Pod对象中的所有容器,首次需要重启的容器,将在其需要的时候立即进行重启,随后再次重启的操作将由kubelet延迟一段时间后进行,且反复的重启操作的延迟时长以此为10s、20s、40s、80s、160s和300s,300s是最大的延迟时长。

  • 创建pod-restart-policy.yaml文件,内容如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
[root@master ~]# cat pod-restart-policy.yaml 
apiVersion: v1
kind: Pod
metadata:
name: pod-restart-policy
namespace: dev
labels:
user: xudaxian
spec:
containers: # 容器配置
- name: nginx
image: 192.168.20.119/library/nginx:latest
imagePullPolicy: IfNotPresent
ports:
- name: nginx-port
containerPort: 80
protocol: TCP
livenessProbe: # 存活性探测
httpGet:
port: 80
path: /hello
host: 127.0.0.1
scheme: HTTP
restartPolicy: Never # 重启策略
  • 查看Pod详情,发现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
[root@master ~]# kubectl create -f pod-restart-policy.yaml 
pod/pod-restart-policy created
[root@master ~]# kubectl describe pod pod-restart-policy -n dev
Name: pod-restart-policy
Namespace: dev
Priority: 0
Node: node2/192.168.20.124
Start Time: Thu, 26 May 2022 05:50:27 +0000
Labels: user=xudaxian
Annotations: <none>
Status: Succeeded
IP: 10.244.1.9
IPs:
IP: 10.244.1.9
Containers:
nginx:
Container ID: docker://b0adcc8f6fccad320ba37dd747b3c41e41a4f34b86a0a57612c5da45020b562c
Image: 192.168.20.119/library/nginx:latest
Image ID: docker-pullable://192.168.20.119/library/nginx@sha256:416d511ffa63777489af47f250b70d1570e428b67666567085f2bece3571ad83
Port: 80/TCP
Host Port: 0/TCP
State: Terminated
Reason: Completed
Exit Code: 0
Started: Thu, 26 May 2022 05:50:29 +0000
Finished: Thu, 26 May 2022 05:50:51 +0000
Ready: False
Restart Count: 0
Liveness: http-get http://127.0.0.1:80/hello delay=0s timeout=1s period=10s #success=1 #failure=3
Environment: <none>
Mounts:
/var/run/secrets/kubernetes.io/serviceaccount from default-token-7sxn4 (ro)
Conditions:
Type Status
Initialized True
Ready False
ContainersReady False
PodScheduled True
Volumes:
default-token-7sxn4:
Type: Secret (a volume populated by a Secret)
SecretName: default-token-7sxn4
Optional: false
QoS Class: BestEffort
Node-Selectors: <none>
Tolerations: node.kubernetes.io/not-ready:NoExecute for 300s
node.kubernetes.io/unreachable:NoExecute for 300s
Events:
Type Reason Age From Message
---- ------ ---- ---- -------
Normal Scheduled 38s default-scheduler Successfully assigned dev/pod-restart-policy to node2
Normal Pulled 36s kubelet, node2 Container image "192.168.20.119/library/nginx:latest" already present on machine
Normal Created 36s kubelet, node2 Created container nginx
Normal Started 36s kubelet, node2 Started container nginx
Warning Unhealthy 14s (x3 over 34s) kubelet, node2 Liveness probe failed: Get http://127.0.0.1:80/hello: dial tcp 127.0.0.1:80: connect: connection refused
Normal Killing 14s kubelet, node2 Stopping container nginx
  • 查看Pod:
1
2
3
[root@master ~]# kubectl get pod pod-restart-policy -n dev
NAME READY STATUS RESTARTS AGE
pod-restart-policy 0/1 Completed 0 103s

多等一会,观察Pod的重试次数,发现一直是0,并未重启。