Kubernetes provides container lifecycle hooks to
trigger commands on Container lifecycle events.
If we recall, container lifecycle had 5 stages,
Created, Running, Paused, Stopped and Deleted.
Out of these 5, kubectl provides lifecycle hooks
for two of the states, which are Created and Stopped.
Let's explore both of these using
lifecycle-pod.yaml file. This is a standard
nginx Pod named lifecyc-pod. And under the
containers spec, we have two lifecycle hooks called
postStart and preStop. These hooks functionality
is pretty much as their name suggests. Both of
them have handlers attached to them, which are
executable commands, postStart hooks handler will
'echo Welcome' to a file called poststart-msg and it
will trigger after the container will enter the
Created state. This is the state where resources
for read-write layer are reserved, but the
container is not running yet. In other words, the
latest cmd or entrypoint instruction is yet to be
executed. The hook works synchronously with the
Pod's container creation process. Which means if
for some reason the handler of the hook hangs or
fails to execute, the pod will remain in container
Created state and won't go into the Running state.
To brief things up, first of all the container will
be created, then the postStart hook will be
handled, and the message will be printed. And then
the container will start running by executing cmd
or entrypoint command. A general use of this hook
is for better debugging, just like try and catch
clause in the programming. But it also brings the
burden of stalling the container if the hook
doesn't get handled properly. So if Pod events and
logs are sufficient for your debugging, you might
want to skip using this hook. Lastly, we have preStop hook,
which triggers before termination of the
container. We are simply quitting the nginx
process before terminating the container. But if
you want to strongly verify this hook, you can
apply SIGKILL to one of the container's crucial
processes and you would find the container exited
with a respective error code. Let's exit the file
and create the Pod.
[No Audio]
30 seconds down and the Pod is ready.
I know we have sold the benefits of
containers a lot, but it is always amusing to see
such a level of managed isolation being created
with such less efforts and within such a short time.
Now let's execute the Pod with kubectl exec
command and run bash on it. cat the file poststart-msg
and bingo the hook was executed successfully.
The message is loud and clear. Well not that loud,
but it is quite clear. In the next lecture,
we will see how to replace container cmd command