Working with Pod Lifecycle Hooks

1. Understanding Lifecycle Hooks

HookFires When
postStartImmediately after container created (async with ENTRYPOINT)
preStopBefore container receives SIGTERM during termination
Note: Container will not enter Running until postStart completes; container is killed if postStart fails.

2. Configuring PostStart Hook

lifecycle:
  postStart:
    exec: { command: ["sh","-c","echo started > /tmp/ready"] }
HandlerFormat
execcommand: [...]
httpGetpath, port, host, scheme, httpHeaders
sleep NEWsleep: { seconds: 5 } (1.32+)

3. Configuring PreStop Hook

Example: Graceful nginx drain

lifecycle:
  preStop:
    exec: { command: ["/bin/sh","-c","nginx -s quit; sleep 10"] }
terminationGracePeriodSeconds: 30
SequenceStep
1Pod marked Terminating; removed from Service endpoints
2preStop hook runs
3SIGTERM sent to PID 1
4SIGKILL after terminationGracePeriodSeconds

4. Using Exec Handler

PropertyDetail
Runs inContainer's filesystem & network
FailureExit non-zero treated as hook failure
Best forLocal cleanup, signal sending

5. Using HTTP Handler

lifecycle:
  preStop:
    httpGet:
      path: /shutdown
      port: 8080
      httpHeaders: [{ name: X-Reason, value: drain }]
FieldDefault
schemeHTTP
hostPod IP
Success2xx/3xx response

6. Implementing Graceful Shutdown

Graceful Shutdown Pattern

  1. preStop: mark unready (touch flag, drop from LB)
  2. preStop: sleep N seconds for in-flight requests
  3. SIGTERM: stop accepting new connections
  4. App drains workers, flushes logs, closes DB
  5. App exits cleanly before grace period ends
TipDetail
Sleep lengthCover kube-proxy/iptables update lag (5-10s)
terminationGracePeriodSecondspreStop + drain + buffer
PID 1Use tini/dumb-init to forward SIGTERM

7. Understanding Hook Guarantees

GuaranteeReality
At-least-onceHook may run multiple times on retries
postStart vs ENTRYPOINTNo ordering — race possible
preStop on node failureNot guaranteed to run

8. Setting Termination Grace Period

SettingDefault
terminationGracePeriodSeconds30s
0Force-immediate (SIGKILL); skips preStop
Overridekubectl delete --grace-period=60

9. Debugging Lifecycle Hooks

SymptomCheck
FailedPostStartHookkubectl describe pod events
FailedPreStopHookHook exceeded grace period
Stuck TerminatingFinalizers, kubelet unable to reach node

10. Using Hooks for Deregistration

Example: Deregister from external service mesh

lifecycle:
  preStop:
    exec:
      command: ["sh","-c","curl -X DELETE http://consul:8500/v1/agent/service/deregister/$HOSTNAME; sleep 10"]