最近发现集群内的POD在删除的时候,不会自动清理某些自定义配置的网络信息。于是使用了Kubernets的一个功能,在删除或者启动POD的时候,去触发自定义的一些处理程序,避免POD在删除的时候遗留某些信息导致的集群异常。示例如下:

  • Kubernetes在启动Container后立即发送postStart事件,并在Container终止之前立即发送preStop事件。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
apiVersion: v1
kind: Pod
metadata:
name: lifecycle-demo
spec:
containers:
- name: lifecycle-demo-container
image: nginx
lifecycle:
postStart:
exec:
command: ["/bin/sh", "-c", "echo Hello from the postStart handler > /usr/share/message"]
preStop:
exec:
command: ["/bin/sh","-c","nginx -s quit; while killall -0 nginx; do sleep 1; done"]
  • 需要注意的是,preStop并不会影响SIGTERM的处理,因此有可能preStop还没有执行完就收到SIGKILL导致容器强制退出。在这里可以设置terminationGracePeriodSeconds,让POD在删除的时候预留执行preStop的时间,来保证你的preStop事件完整处理。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
apiVersion: v1
kind: Pod
metadata:
name: lifecycle-demo
spec:
containers:
- name: lifecycle-demo-container
image: nginx
lifecycle:
postStart:
exec:
command: ["/bin/sh", "-c", "echo Hello from the postStart handler > /usr/share/message"]
preStop:
exec:
command: ["/bin/sh","-c","nginx -s quit; while killall -0 nginx; do sleep 1; done"]
terminationGracePeriodSeconds: 60 # 增加此参数,默认时间为30s

参考: