Sidecar concept in Kubernetes is very useful ability to run multiple docker images in same pod (Kubernetes unit of execution). One common way to load sidecar is to attach additional container to pod whose only purpose is read stdout/stderror pipes and redirect them to logging system of choice.
Common issue with sidecars is that sometimes it’s expected that they are started/stopped in certain order depending on the case. For logging, we may want to start logging container before main container, and stop it after the app container is stopped, but not before all logs are flushed to external system.
There is a long-standing feature (enhancement) to support this natively but at the time of writing it’s not yet available.
So we’re forced to search for “alternative hacks” which would allow us to delay shutdown of our sidecar container once main app dies.
Using preStop Hook
This hook enables execution of command (or other action, see in docs) before emitting SIGTERM signal to application. This command will wait up to default of 30 seconds.
apiVersion: v1
kind: Pod
metadata:
name: test
namespace: default
spec:
containers:
- name: nginx
image: nginx
lifecycle:
preStop:
exec:
command:
- /bin/sh
Using terminationGracePeriodSeconds
This parameter changes wait time of 30 seconds to given value. So in this case, bash script can sleep up to 200 seconds, and only then will Kubernetes kill the bash container.
One way to use this extension of termination is to emit a “flush&shutdown event” via preStop command and wait up to specified grace period.
apiVersion: v1
kind: Pod
metadata:
name: test
namespace: default
spec:
containers:
- name: nginx
image: nginx
- name: bash
image: bash
lifecycle:
preStop:
exec:
command:
- /bin/sh
args:
- "-c"
- "sleep 200"
terminationGracePeriodSeconds: 200