k8s-pod回调hook钩子

Pod回调HOOK钩子,postStart-preStop

	实际上 Kubernetes 为我们的容器提供了生命周期钩子的,就是我们说的Pod Hook,Pod Hook 是由 kubelet 发起的,当容器中的进程启动前或者容器中的进程终止之前运行,这是包含在容器的生命周期之中。我们可以同时为 Pod 中的所有容器都配置 hook。

Kubernetes 为我们提供了两种钩子函数:

	PostStart:这个钩子在容器创建后立即执行。但是,并不能保证钩子将在容器ENTRYPOINT之前运行,因为没有参数传递给处理程序。主要用于资源部署、环境准备等。不过需要注意的是如果钩子花费太长时间以至于不能运行或者挂起, 容器将不能达到running状态。

	PreStop:这个钩子在容器终止之前立即被调用。它是阻塞的,意味着它是同步的, 所以它必须在删除容器的调用发出之前完成。主要用于优雅关闭应用程序、通知其他系统等。如果钩子在执行期间挂起, Pod阶段将停留在running状态并且永不会达到failed状态。

如果PostStart或者PreStop钩子失败, 它会杀死容器。所以我们应该让钩子函数尽可能的轻量。当然有些情况下,长时间运行命令是合理的, 比如在停止容器之前预先保存状态。

例子1:

kind: Deployment
apiVersion: apps/v1
metadata:
  name: lifecycle
spec:
  selector:
    matchLabels:
      app: cycle
  template:
    metadata:
      labels:
        app: cycle
    spec:
      nodeName: sg-15
      containers:
        - name: nginx
          image: nginx
          lifecycle:
            postStart:  // 开始回调钩子
              exec:
                command:
                  - "/bin/bash"
                  - "-c"
                  - "echo 'This is lifecycle postStart' > /home/index.log"
            preStop:  // 结束回调钩子
              exec:
                command:
                  - "/bin/bash"
                  - "-c"
                  - "echo 'This is lifecycle preStop' > /home/index.log"

例子2

apiVersion: v1
kind: Pod
metadata:
  name: hook-demo1
spec:
  containers:
    - name: hook-demo1
      image: nginx
      lifecycle:
        postStart:
          exec:
            command: ["/bin/sh", "-c", "echo Hello from the postStart handler > /usr/share/message"]

posted @ 2021-11-30 14:45  Jeff的技术栈  阅读(602)  评论(0编辑  收藏  举报
回顶部