容器生命周期回调
更新时间:2024-09-25
容器生命周期回调
本文介绍如何使用BCI容器生命周期回调框架,即preStop和postStart函数触发业务自定义代码逻辑执行,详情请见container-lifecycle-hooks
注意:
BCI目前只支持exec形式的hook,httpGet和tcpSocket类型的hook会被忽略。
postStart
这个回调在容器被创建之后立即被执行。 但是不能保证回调会在容器入口点(ENTRYPOINT)之前执行。 没有参数传递给处理程序。
pod示例如下:
Plain Text
1apiVersion: v1
2kind: Pod
3metadata:
4 annotations:
5 myannotation: "myannotation"
6 labels:
7 app: bci-test-vk
8 mylabel: "mylabel"
9 name: poststart-test
10 namespace: default
11spec:
12 enableServiceLinks: false
13 nodeSelector:
14 type: virtual-kubelet
15 tolerations:
16 - effect: NoSchedule
17 key: virtual-kubelet.io/provider
18 operator: Equal
19 value: baidu
20 - effect: NoExecute
21 key: node.kubernetes.io/not-ready
22 operator: Exists
23 tolerationSeconds: 300
24 - effect: NoExecute
25 key: node.kubernetes.io/unreachable
26 operator: Exists
27 tolerationSeconds: 300
28 containers:
29 - image: hub.baidubce.com/cce/nginx-alpine-go
30 imagePullPolicy: IfNotPresent
31 name: c01
32 workingDir: /work
33 ports:
34 - containerPort: 8080
35 protocol: TCP
36 resources:
37 limits:
38 cpu: 250m
39 memory: 512Mi
40 requests:
41 cpu: 250m
42 memory: 512Mi
43 lifecycle:
44 postStart:
45 exec:
46 command: ["/bin/sh","-c","echo postStart hook > /tmp/termination-log"]
preStop
在容器因API请求或者管理事件(诸如存活态探针、启动探针失败、资源抢占、资源竞争等) 而被终止之前,此回调会被调用。如果容器已经处于已终止或者已完成状态,则对preStop回调的调用将失败。在用来停止容器的TERM信号被发出之前,回调必须执行结束。Pod的终止宽限周期在PreStop回调被执行之前即开始计数,所以无论回调函数的执行结果如何,容器最终都会在Pod的终止宽限期内被终止。没有参数会被传递给处理程序。
pod示例如下:
Plain Text
1apiVersion: v1
2kind: Pod
3metadata:
4 annotations:
5 myannotation: "myannotation"
6 labels:
7 app: bci-test-vk
8 mylabel: "mylabel"
9 name: prestop-test
10 namespace: default
11spec:
12 enableServiceLinks: false
13 nodeSelector:
14 type: virtual-kubelet
15 tolerations:
16 - effect: NoSchedule
17 key: virtual-kubelet.io/provider
18 operator: Equal
19 value: baidu
20 - effect: NoExecute
21 key: node.kubernetes.io/not-ready
22 operator: Exists
23 tolerationSeconds: 300
24 - effect: NoExecute
25 key: node.kubernetes.io/unreachable
26 operator: Exists
27 tolerationSeconds: 300
28 containers:
29 - image: hub.baidubce.com/cce/nginx-alpine-go
30 imagePullPolicy: IfNotPresent
31 name: c01
32 workingDir: /work
33 ports:
34 - containerPort: 8080
35 protocol: TCP
36 resources:
37 limits:
38 cpu: 250m
39 memory: 512Mi
40 requests:
41 cpu: 250m
42 memory: 512Mi
43 lifecycle:
44 preStop:
45 exec:
46 command: ["/bin/sh","-c","echo preStop hook > /tmp/termination-log && sleep 30"]