Is there a probe for shutdown or before kill pods in Kubernetes?

3/20/2019

Is there a way to get a trigger to shutdown, so we can close all connections gracefully before shutdown and don't proceed any actions after that probe and keeping the probe ready to kill.

This including flushing logs, keeping any state of the application saved before handing over to the new pod and many more use cases.

-- Kannaiyan
kubernetes

1 Answer

3/20/2019

You have 2 options:

  1. Containers (PID 1) receive SIGTERM before the container (and the pod) is removed. You can trap SIGTERM and act on it.

  2. You can use the preStop lifecycle hook

Important implementation details can be found here: https://kubernetes.io/docs/concepts/workloads/pods/pod/#termination-of-pods

httpGet example

apiVersion: v1
kind: Pod
metadata:
  name: prestop-pod
spec:
  terminationGracePeriodSeconds: 5
  containers:
    - name: nginx
      image: nginx
      lifecycle:
        preStop:
          httpGet:
            # only port is reqired
            port: 80
            path: "?preStop"
            # scheme: HTTP
            # host: ...
            # httpHeaders:
            #   name: ...
            #   value: ...

After kubectl apply -f on this file, run kubectl log -f prestop-pod while executing kubectl delete pod prestop-pod on another terminal. You should see something like:

$ kubectl apply -f prestop.yaml 
pod/prestop-pod created
$ kubectl logs -f prestop-pod
10.244.0.1 - - [21/Mar/2019:09:15:20 +0000] "GET /?preStop HTTP/1.1" 200 612 "-" "Go-http-client/1.1" "-"
-- Janos Lenart
Source: StackOverflow