kubernetes lifecycle commands not running

5/28/2021

I have been trying to get prestop to run a script before the pod terminates (to prolong the termination until the current job has finished), but command doesn't seem to be executing the commands. I've temporarily added an echo command, which i would expect to see in kubectl logs for the pod, i can't see this either.

This is part of the (otherwise working) deployment spec:

      containers:
        - name: file-blast-app
          image:  my_image:stuff
          imagePullPolicy: Always
          lifecycle:
            preStop:
              exec:
                command: ["echo","PRE STOP!"]

Does anyone know why this would not be working and if i'm correct to expect the logs from hook in kubectl logs for the pod?

-- Happy Machine
kubernetes
kubernetes-pod

1 Answer

5/28/2021

You forgot to mention the shell through which you want this command to be executed.

Try using the following in your YAML.

  containers:
    - name: file-blast-app
      image:  my_image:stuff
      imagePullPolicy: Always
      lifecycle:
        preStop:
          exec:
            command: ["/bin/sh","-c","echo PRE STOP!"]

Also, one thing to note is that a preStop hook only gets executed when a pod is terminated, and not when it is completed. You can read more on this here.

You can also refer to the K8S official documentation for lifecycle hooks here.

-- Abhinav Thakur
Source: StackOverflow