Kubernetes | Any hooks available for Pod restarts?

5/31/2019

Are there any hooks available for Pod lifecycle events? Specifically, I want to run a command to upload logs on pod restart.

-- Mohit Gupta
google-kubernetes-engine
kubectl
kubernetes
kubernetes-pod

1 Answer

5/31/2019

Edit: PreStop hook doesn't work for container restart - please see rest of answer below

As standing in documentation there are PreStop and PostStart events and you can attach to them.

Example from docs:

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

Edit: So I checked with following POC if that preStop hook is executed on container crash and conclusion is: NOT

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

As solution for you I would recommend to override command section for you container this way:

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

so your-logs-upload executable will be executed after your-application-executable crash/end

-- Jakub Bujny
Source: StackOverflow