Pod hooks: postStart and preStop

2 min read | by Jordi Prats

If we need to execute some actions at container startup of before stopping the container we can me use of the container lifecycle hooks

We have the following hooks available:

  • PostStart: This hook is executed immediately after a container is created, but the hook might (or might not) be executed before the container ENTRYPOINT. We can use it, for example, to warm up the container's cache:
apiVersion: apps/v1
kind: Deployment
(...)
  template:
    spec:
(...)  
      containers:
        - name: pet2cattle
(...)
          lifecycle:
            postStart:
              exec:
                command: [ "/usr/local/bin/python", "/code/cachewarmer.py" ]
  • PreStop: This hook is called before a container is terminated via the API, for example by stopping the container using kubectl delete pod or on a probe failure. The Pod's termination grace period countdown begins before the PreStop hook is executed, so the container will eventually terminate. An example could be killing an nginx like so:
apiVersion: v1
kind: Pod
(...)
spec:
  containers:
  - name: lifecycle-demo
(...)
    lifecycle:
      preStop:
        exec:
          command: ["/bin/sh","-c","nginx -s quit; while killall -0 nginx; do sleep 1; done"]

Posted on 24/09/2021