liveBook · Manning

Pre-stop hook

As explained in Kubernetes in Action, Second Edition

A pre-stop hook is a Kubernetes container lifecycle action executed before Kubernetes terminates the container.

A pre-stop hook runs just before Kubernetes terminates a container. It gives the container a chance to begin a graceful shutdown or perform another final action without putting that action in the application's shutdown code. Configure it on an individual regular container, not on an init container or on the pod as a whole. section 6.3.2 section 6.3

The hook can execute a command inside the container or send an HTTP GET request to its application. Kubernetes runs the hook before sending SIGTERM to the container's main process. Normally, SIGTERM waits until the hook completes; it is not sent if the hook itself has already caused the process to terminate. section 6.3.2

Let Nginx finish requests

Nginx responds to SIGTERM by immediately closing open connections, which can interrupt requests. A pre-stop hook that runs `nginx -s quit` instead tells Nginx to stop accepting new connections, finish requests already in progress, and quit. Configure the command under the container's `lifecycle.preStop.exec.command` field. section 6.3.2

Listing 6.5 Defining a pre-stop hook for Nginx
    lifecycle:       #1
      preStop:      #1
        exec:               #2
          command:          #2
          - nginx      #3
          - -s         #3
          - quit       #3

See the Pod manifest fragment that configures the Nginx pre-stop command. section 6.3.2

A long-running hook delays its own container's shutdown, not the shutdown of other containers in the pod: their pre-stop hooks are invoked in parallel. The shutdown grace period still limits how long a process has to stop before it is killed. If pod deletion is slow, check whether a process handles SIGTERM; shortening the grace period is not necessarily the right fix. section 6.4.2 section 6.5

How Kubernetes in Action, Second Edition covers it

How deep it goes
Explains handler choices, SIGTERM ordering, and grace-period limits, with a concrete manifest fragment.
Examples
Uses an Nginx `nginx -s quit` hook and a slow pod-deletion scenario.
What it assumes
Builds on init containers and liveness probes while defining lifecycle-hook scope and handlers.
What you can do after
Operate/configure it in a Kubernetes Pod manifest to run a shutdown command before SIGTERM.
How it connects
Connects container lifecycle hooks to post-start hooks, init containers, liveness probes, SIGTERM, and pod termination.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Kubernetes in Action, Second Edition. The section links point to the parts of the book it draws on.