https://drive.google.com/file/d/1HKmo-R__r1_zY8mbeMExjsTqKts86_x2/view?usp=sharing

πŸ” YAML Breakdown

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:

⚠️ Critical Note:

postStart runs asynchronously with the container’s main process.

β†’ Your app might start before postStart finishes!


πŸ“Œ When Lifecycle Hooks Run

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:

πŸ’‘ Why preStop matters:

Without it, user data would linger after Pod deletion (in container filesystem).


πŸ§ͺ k3s Lab: Observe Lifecycle Hooks

πŸ”§ Step 1: Create Namespace & Deploy Pod

# 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

πŸ”§ Step 2: Verify 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

πŸ”§ Step 3: Trigger 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:

πŸ”§ Step 4: Test preStop with Delay (Optional)