Container life cycle hooks

Life cycle hooks are actions triggered on certain events and performed against containers. They work like a single Kubernetes probing action, but they'll be fired at least once per event during a container's lifetime. Currently, two events are supported:

  • PostStart: This executes right after a container is created. Since this hook and the entry point of a container are fired asynchronously, there's no guarantee that the hook will be executed before the container starts. As such, we're unlikely to use it to initialize resources for a container.
  • PreStop: This executes right before sending SIGTERM to a container. One difference from the PostStart hook is that the PreStop hook is a synchronous call; in other words, SIGTERM is only sent after a PreStop hook exited.

We can easily solve our nginx shutdown problem with a PreStop hook:

...
containers:
- name: main
image: nginx
life cycle:
preStop:
exec:
command: [ "nginx", "-s", "quit" ]
...

An important property of hooks is they can affect the state of a pod in certain ways: a pod won't be running unless its PostStart hook exits successfully. A pod is set to terminate immediately on deletion, but SIGTERM won't be sent unless the PreStop hook exits successfully. Therefore, we can resolve a situation that a pod quits before its proxy rules are removed on the node by the PreStop hook.

The following diagram illustrates how to use the hook to eliminate the unwanted gap:

The implementation is to just add a hook that sleeps for a few seconds:

...
containers:
- name: main
image: my-app
life cycle:
preStop:
exec:
command: [ "/bin/sh", "-c", "sleep 5" ]
...
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset