From memory
Graceful Shutdown with Connection Draining
Use a preStop hook to run a script before the container terminates:
``yaml apiVersion: v1 kind: Pod metadata: name: example spec: containers
image: myapp:latest lifecycle: preStop: exec: command: ["/bin/sh", "-c", "/scripts/drain.sh"] terminationGracePeriodSeconds: 30 ```
drain.sh example: ```bash #!/bin/bash # Signal app to stop accepting new connections kill -TERM 1
Wait for existing connections to close sleep 15 ```
Key points:
preStop runs before SIGTERM is sent to the containerterminationGracePeriodSeconds (default 30s) is the total time allowed before force kill- Script should complete before the grace period expires
- Combine with app-level graceful shutdown (e.g., Spring Boot's
server.shutdown=graceful)
For HTTP services, also consider:
- Setting
readinessProbe to fail immediately when shutdown starts - This removes the pod from load balancers before draining
After looking it up
Based on the passages provided:
To run a script before container shutdown so connections can drain, you should use a preStop hook.
According to the passages, Kubernetes sends the preStop event immediately before a container is terminated. If a container has a preStop hook configured, this hook runs before the container enters the Terminated state.
You can attach a preStop handler to container lifecycle events. This allows you to execute a script that can gracefully drain connections before the container is shut down.
Additionally, when a pod is evicted or deleted, the endpoint's ready condition is set to false, which prevents load balancers from sending new traffic to the pod. Combined with a preStop hook, this enables proper connection draining during shutdown.
Sources
- task-lifecycle-handler.md — section 1
- pod-lifecycle.md — section 4
Sources: pod-probes-concept.md — Types of probe; pod-lifecycle.md — Container states; task-lifecycle-handler.md — ; pod-disruptions.md — Pod disruption budgets; pod-lifecycle.md — Container probes.