Kubernetes |是否有任何可用于Pod重新启动的钩子?

时间:2019-05-31 08:22:12

标签: kubernetes google-kubernetes-engine kubectl kubernetes-pod

Pod生命周期事件是否有可用的钩子?具体来说,我想运行一个命令以在Pod重新启动时上传日志。

1 个答案:

答案 0 :(得分:5)

编辑:PreStop挂钩不适用于容器重启-请在下面查看其余答案

documentation中,有PreStopPostStart个事件,您可以附加它们。

文档示例:

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"]

编辑: 所以我检查了以下POC,是否在容器崩溃时执行了preStop挂钩,结论是:

apiVersion: v1
kind: Pod
metadata:
  name: lifecycle-demo
spec:
  containers:
  - name: lifecycle-demo-container
    volumeMounts:
    - mountPath: /data
      name: test-volume
    image: nginx
    command: ["/bin/sh"]
    args: ["-c", "sleep 5; exit 1"]
    lifecycle:
      postStart:
        exec:
          command: ["/bin/sh", "-c", "echo Hello from the postStart handler > /data/postStart"]
      preStop:
        exec:
          command: ["/bin/sh","-c","echo preStop handler! > /data/preStop"]

  volumes:
  - name: test-volume
    hostPath:
      path: /data
      type: Directory

作为您的解决方案,我建议通过以下方式为您的容器覆盖命令部分:

command: ["/bin/sh"]
args: ["-c", "your-application-executable; your-logs-upload"]

因此您的日志上传可执行文件将在您的应用程序可执行崩溃/结束后执行