https://drive.google.com/file/d/1HKmo-R__r1_zY8mbeMExjsTqKts86_x2/view?usp=sharing
apiVersion: v1
kind: Pod
metadata:
name: nnappone
namespace: learning
labels:
app: nnappone
spec:
containers:
- name: crackone-app
image: lovelearnlinux/webserver:v1
lifecycle:
postStart:
exec:
command: ["/bin/sh", "-c", "useradd crackone -p redhat"]
preStop:
exec:
command: ["/bin/sh","-c","rm -rf /home/crackone; userdel crackone"]
π Key Insight:
postStart: Runs immediately after container starts (but not guaranteed to run before app starts!)preStop: Runs immediately before container terminates (graceful shutdown)
β οΈ Critical Note:
postStartruns asynchronously with the containerβs main process.β Your app might start before
postStartfinishes!
| Hook | When It Runs | Use Cases |
|---|---|---|
postStart |
After container is created, before app fully starts | - Create users/dirs<br>- Fetch config from remote<br>- Send startup notification |
preStop |
Before container is terminated (during SIGTERM) |
- Drain connections<br>- Flush logs<br>- Cleanup temp files |
π― Your Example:
postStart: Creates a usercrackonepreStop: Deletes the user and home directory
π‘ Why preStop matters:
Without it, user data would linger after Pod deletion (in container filesystem).
# Create namespace
kubectl create namespace learning
# Apply Pod
kubectl apply -f pod-simple-lifecycle-events.yml
# Wait for Pod to be ready
kubectl get pods -n learning
postStart Ran# Check if user was created
kubectl exec nnappone -n learning -- cat /etc/passwd | grep crackone
# β
Expected output:
# cracokone:x:1001:1001::/home/crackone:/bin/sh
# Check home directory
kubectl exec nnappone -n learning -- ls /home
# crackone
preStop (Delete Pod)# Delete Pod (triggers preStop)
kubectl delete pod nnappone -n learning
# Watch termination
kubectl get pods -n learning -w
π How to verify preStop ran?
Since the Pod is deleted, we canβt check directly.
But we can test with a long-running
preStop:
preStop with Delay (Optional)