kubernetes中的PreStop钩子永远不会执行 [英] PreStop hook in kubernetes never gets executed
问题描述
我试图用两个容器创建一个Pod小示例,这两个容器通过emptyDir卷共享数据.在第一个容器中,我等待了几秒钟才被销毁.
I am trying to create a little Pod example with two containers that share data via an emptyDir volume. In the first container I am waiting a couple of seconds before it gets destroyed.
在postStart中,我将文件名为"started"写入共享卷,在preStop中,我将文件写入名为"finished"的共享卷.
In the postStart I am writing a file to the shared volume with the name "started", in the preStop I am writing a file to the shared volume with the name "finished".
在第二个容器中,我循环了几秒钟,以输出共享卷的内容,但从未创建完成"文件.描述吊舱也不会在钩子上显示任何错误.
In the second container I am looping for a couple of seconds outputting the content of the shared volume but the "finished" file never gets created. Describing the pod doesn't show an error with the hooks either.
也许有人知道我在做什么错
Maybe someone has an idea what I am doing wrong
apiVersion: v1
kind: Pod
metadata:
name: shared-data-example
labels:
app: shared-data-example
spec:
volumes:
- name: shared-data
emptyDir: {}
containers:
- name: first-container
image: ubuntu
command: ["/bin/bash"]
args: ["-c", "for i in {1..4}; do echo Welcome $i;sleep 1;done"]
imagePullPolicy: Never
env:
- name: TERM
value: xterm
volumeMounts:
- name: shared-data
mountPath: /myshareddata
lifecycle:
preStop:
exec:
command: ["/bin/sh", "-c", "echo First container finished > /myshareddata/finished"]
postStart:
exec:
command: ["/bin/sh", "-c", "echo First container started > /myshareddata/started"]
- name: second-container
image: ubuntu
command: ["/bin/bash"]
args: ["-c", "for i in {1..20}; do ls /myshareddata;sleep 1;done"]
imagePullPolicy: Never
env:
- name: TERM
value: xterm
volumeMounts:
- name: shared-data
mountPath: /myshareddata
restartPolicy: Never
推荐答案
之所以发生这种情况,是因为您的pod的最终状态为Completed
,并且容器内的应用程序停止了,而没有任何外部调用.
It is happening because the final status of your pod is Completed
and applications inside containers stopped without any external calls.
Kubernetes仅在pod解析外部信号停止时才运行preStop
挂接.当需要停止Pod内的应用程序时,可以使用钩子来实现正常的自定义关闭.就您而言,您的应用程序已经可以正常停止,因此Kubernetes没有理由调用该钩子.
Kubernetes runs preStop
hook only if pod resolves an external signal to stop. Hooks were made to implement a graceful custom shutdown for applications inside a pod when you need to stop it. In your case, your application is already gracefully stopped by itself, so Kubernetes has no reason to call the hook.
例如,如果要检查挂钩的工作原理,则可以尝试创建Deployment
并通过kubectl rolling-update
更新其图像.在这种情况下,Kubernetes将停止该应用程序的旧版本,并会调用preStop
挂钩.
If you want to check how a hook works, you can try to create Deployment
and update it's image by kubectl rolling-update
, for example. In that case, Kubernetes will stop the old version of the application, and preStop
hook will be called.
这篇关于kubernetes中的PreStop钩子永远不会执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!