liveBook · Manning

Exec lifecycle hook

As explained in Kubernetes in Action, Second Edition

An exec lifecycle hook runs a command or process inside a container at a configured lifecycle event.

An exec lifecycle hook runs a command inside a regular container at a lifecycle event. A post-start hook runs as the container’s main process starts, so it is not a general readiness mechanism. section 6.3.1

Generate content after startup

A post-start exec hook can run sh -c, install fortune, download quote data, and write a generated quote to /usr/share/nginx/html/quote. The container’s main process and hook run concurrently. section 6.3.1

Listing 6.3 Pod with a post-start lifecycle hook
apiVersion: v1
kind: Pod
metadata:
  name: quote-poststart     #1
spec:
  containers:
  - name: nginx            #2
    image: nginx:alpine    #2
    ports:                   #3
    - name: http             #3
      containerPort: 80      #3
    lifecycle:                    #4
      postStart:                  #4
        exec:                     #4
          command:                #4
          - sh                    #5
          - -c       #6
          - |               #7
            apk add fortune && \                                            #8
            curl -O https://luksa.github.io/kiada/book-quotes.txt && \       #8
            curl -O https://luksa.github.io/kiada/book-quotes.txt.dat && \   #8
            fortune book-quotes.txt > /usr/share/nginx/html/quote            #8

Use the manifest to see lifecycle.postStart.exec.command configured as a shell-based command sequence. section 6.3.1

Account for these operational behaviors:

  • A nonzero command exit causes a PostStartHookError and can cause the container to restart. section 6.3.1
  • Inspect the running hook with kubectl exec and diagnose failures with kubectl logs and Pod events. section 6.3.1
  • Apply lifecycle hooks only to regular containers; init containers cannot use them. section 6.3.1

How Kubernetes in Action, Second Edition covers it

How deep it goes
Explains command configuration, concurrent startup, failure effects, and inspection, but does not develop broader lifecycle-hook design.
Examples
Demonstrates a quote-generating nginx Pod, shell commands, kubectl inspection, and an intentionally failing hook.
What it assumes
Assumes basic Pod and container familiarity while introducing lifecycle configuration and shell-command execution through examples.
What you can do after
Operate/configure a post-start command and diagnose its process, logs, events, and exit-status failures.
How it connects
Connects lifecycle hooks with containers, init containers, liveness probes, and HTTP GET hooks.

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.