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