Skip to main content

☑️ Ensure each container has a configured pre-stop hook

Once Kubernetes has decided to terminate one of your pods, it will proceed to send a SIGTERM signal to it. If your application doesn't gracefully shut down when receiving a SIGTERM, this can cause undesired behavior and loss of data.
For this and other reasons, Kubernetes provides containers with lifecycle hooks that enable them to be aware of events in their management lifecycle and run code implemented in a handler when the corresponding lifecycle hook is executed.
The preStop hook is called immediately before a container is terminated, allowing you to properly clean up your application and ensure a graceful shutdown.

tip

Note that the output/result of the code running within the hook will not affect the termination, which will happen regardless.

Targeted objects by this rule (types of kind): Deployment / Pod / DaemonSet / StatefulSet / ReplicaSet / CronJob / Job

Complexity: hard (What does this mean?)

Policy as code identifier: CONTAINERS_MISSING_PRESTOP_KEY


This rule will fail

If a container doesn't have a preStop hook configured

spec:
containers:
- name: myApp
image: nginx:1.19.8

Rule output in the CLI

$ datree test *.yaml

>> File: failExample.yaml
❌ Ensure each container has a configured pre-stop hook [1 occurrence]
💡 Missing property object `preStop` - set to ensure graceful shutdown of the container

How to fix this failure

spec:
containers:
- name: myNginxApp
lifecycle:
preStop:
exec:
command: [
# Gracefully shutdown nginx
"/usr/sbin/nginx", "-s", "quit"
]

Read more