Graceful termination of pods in Kubernetes is essential to prevent data loss, minimize interruptions, and ensure services are stopped in a controlled manner. This process occurs when Kubernetes deletes a pod, whether due to a Deployment update, scaling, eviction for lack of resources, or when the user manually deletes the pod. Understanding how graceful termination works helps you design more robust applications.
When Kubernetes wants to terminate a pod, it gives it the opportunity to shut down gracefully.
- The preStop hook (if it exists) is executed before killing the pod. This is a good place to:
- add code that waits for connections to close
- notify other components
- clean up resources
For example, you can define a preStop hook and configure the grace period (terminationGracePeriodSeconds) in the manifest of a Pod or a Deployment. Below is how to do it in a Deployment, which is the most common resource:
apiVersion: apps/v1
kind: Deployment
metadata:
name: ejemplo-graceful
spec:
replicas: 1
selector:
matchLabels:
app: ejemplo-graceful
template:
metadata:
labels:
app: ejemplo-graceful
spec:
terminationGracePeriodSeconds: 60 # Custom grace period (default is 30 seconds)
containers:
- name: app
image: tu-imagen
lifecycle:
preStop:
exec:
command: ["/bin/sh", "-c", "echo 'Cerrando conexiones...' && sleep 10"]
- Kubernetes marks the pod with status=TERMINATING
- Kubernetes marks the pod as NotReady
- Because it is marked as NotReady, its endpoint is removed from the service endpoints (it no longer receives traffic)
- Then, Kubernetes sends a SIGTERM signal to the main process in each container of the pod.
- This allows a period (default 30 seconds, configurable with terminationGracePeriodSeconds) for the process to terminate by itself.
- If the process does not terminate by itself, Kubernetes sends a SIGKILL signal to the main process in each container of the pod.
In summary, taking advantage of graceful termination mechanisms in Kubernetes allows your applications to properly handle closing connections, notifying other services, and releasing resources. Always configure the grace period according to your application’s needs and use the preStop hook to avoid unnecessary interruptions or data loss.