🔄 Pod Lifecycle Hooks
Pods have lifecycle events. Lifecycle hooks run at specific times. Init, pre-stop, post-start.
📝 Hook Types
apiVersion: v1
kind: Pod
metadata:
name: app
spec:
containers:
- name: app
image: myapp:latest
lifecycle:
postStart:
exec:
command: ["/bin/sh", "-c", "echo 'Container started'"]
preStop:
exec:
command: ["/bin/sh", "-c", "echo 'Container stopping' && sleep 5"]
# postStart
- Runs after container starts
- For initialization
- Non-blocking
# preStop
- Runs before container stops
- Graceful shutdown
- Cleanup tasks
# HTTP Hook
lifecycle:
postStart:
httpGet:
host: localhost
path: /health
port: 8080
🎯 Hook Examples
# Database migration postStart
lifecycle:
postStart:
exec:
command: ["/bin/sh", "-c", "npm run migrate"]
# Graceful shutdown preStop
lifecycle:
preStop:
exec:
command: ["/bin/sh", "-c", "npm run shutdown"]
# Wait for dependencies
lifecycle:
postStart:
exec:
command: ["/bin/sh", "-c", "until nc -z database 5432; do sleep 2; done"]
# Cleanup preStop
lifecycle:
preStop:
exec:
command: ["/bin/sh", "-c", "rm -rf /tmp/* && echo 'Cleaned up'"]
# Log backup preStop
lifecycle:
preStop:
exec:
command: ["/bin/sh", "-c", "cp /app/logs/app.log /backup/ && echo 'Logs backed up'"]
# Hook with timeout
lifecycle:
preStop:
exec:
command: ["/bin/sh", "-c", "sleep 30 && echo 'Shutdown complete'"]
terminationGracePeriodSeconds: 60
# Hook Best Practices
- Use preStop for graceful shutdown
- Use postStart for initialization
- Set appropriate timeouts
- Test hooks thoroughly
- Handle hook failures
đź’ˇ Hook Tips
- Use preStop for graceful shutdown
- Use postStart for initialization
- Set appropriate timeouts
- Test hooks thoroughly
- Handle hook failures
“Lifecycle hooks run at pod events. Init, pre-stop, post-start. Essential for graceful operation.”
