Qingular

Pod Lifecycle and Management

·CKAk8s练习

Pod creation, state management, Init containers, Sidecar, Static Pod, deletion and termination

← Back to CKA Practice Index

Overview

Pod is the smallest deployable unit in Kubernetes, containing one or more containers. Understanding the Pod lifecycle is fundamental to the CKA exam.


1. Creating Pods

1.1 Imperative Creation

kubectl run nginx --image=nginx --restart=Never

# With labels
kubectl run nginx --image=nginx --labels="app=web,env=prod"

# Expose a port
kubectl run nginx --image=nginx --port=80

# Specify command and arguments
kubectl run busybox --image=busybox --restart=Never -- sleep 3600

# Generate YAML without creating (--dry-run=client -o yaml)
kubectl run nginx --image=nginx --restart=Never --dry-run=client -o yaml > pod.yaml

1.2 Declarative Creation (YAML)

apiVersion: v1
kind: Pod
metadata:
  name: nginx-pod
  labels:
    app: web
    env: prod
spec:
  containers:
  - name: nginx
    image: nginx:1.25
    ports:
    - containerPort: 80
kubectl apply -f pod.yaml

2. Pod Phases and Status

PhaseDescription
PendingAccepted by the cluster, but containers are not yet running (pulling image, waiting for scheduling)
RunningAt least one container is running
SucceededAll containers exited successfully (Job-type Pods)
FailedAll containers have exited and at least one exited with non-zero code
UnknownUnable to determine Pod status (usually node disconnected)
# View Pod status
kubectl get pods
kubectl get pods -o wide
kubectl describe pod <pod-name>

# View Pod details (including events)
kubectl describe pod <pod-name>

# View container restart reasons
kubectl logs <pod-name>
kubectl logs <pod-name> -c <container-name>
kubectl logs --previous <pod-name>    # View previous container logs

Container States

  • Waiting: Pulling image or waiting to start
  • Running: Running normally
  • Terminated: Container has exited (includes exit code)
# Monitor Pod status changes
kubectl get pods -w

3. Init Containers

Init containers run before app containers and must complete successfully before app containers can start.

Configuration Example

apiVersion: v1
kind: Pod
metadata:
  name: init-pod
spec:
  initContainers:
  - name: init-db-wait
    image: busybox:1.28
    command: ['sh', '-c', 'until nc -z db-service 3306; do echo waiting for db; sleep 2; done']
  - name: init-migrate
    image: busybox:1.28
    command: ['sh', '-c', 'echo running migration && sleep 5']
  containers:
  - name: app
    image: nginx

Use Cases

  • Wait for dependent services to be ready (Database, API)
  • Database schema migration
  • Initialize volume permissions
  • Generate configuration files

Important Notes

  • Init containers do not support readinessProbe
  • Each Init container must complete successfully in sequence
  • When an Init container fails, the default restart policy is Always (controlled by Pod restart policy)
  • Init container resource requests/limits take the maximum across all Init containers for scheduling
# View Init container status
kubectl get pod init-pod
kubectl describe pod init-pod | grep -A 10 Init
kubectl logs init-pod -c init-db-wait

4. Sidecar Container Pattern (Kubernetes 1.29+)

Sidecar containers are an enhancement of Init containers that run continuously throughout the Pod lifecycle but start before app containers.

apiVersion: v1
kind: Pod
metadata:
  name: sidecar-pod
spec:
  initContainers:
  - name: log-collector
    image: fluentd
    restartPolicy: Always    # Sidecar marker
  containers:
  - name: app
    image: nginx

Characteristics:

  • Init containers with restartPolicy: Always are Sidecar containers
  • Start before app containers
  • Run concurrently with app containers
  • Do not block the Pod from entering Ready state
  • Use cases: log collection, proxies, service mesh

5. Static Pods

Managed directly by kubelet, they start automatically when YAML files are created in a specified directory.

Configuration

# Find the Static Pod path
ps aux | grep kubelet | grep -- --pod-manifest-path
# Or check kubelet configuration
cat /var/lib/kubelet/config.yaml | grep staticPodPath
# Default path
ls /etc/kubernetes/manifests/

Creating a Static Pod

# Create a YAML file in the manifests directory
cat <<EOF > /etc/kubernetes/manifests/static-nginx.yaml
apiVersion: v1
kind: Pod
metadata:
  name: static-nginx
spec:
  containers:
  - name: nginx
    image: nginx
EOF
# View the Static Pod (name will have node name suffix)
kubectl get pods -n kube-system | grep static-nginx
kubectl get pods -A | grep <node-name>

Characteristics

  • Managed by kubelet, not created through the API Server
  • Deleting the YAML file stops the Pod
  • kubelet automatically creates a mirror Pod in the API Server (read-only)
  • Cannot be managed through Deployment/ReplicaSet
  • Commonly used for Control Plane components (etcd, apiserver, scheduler, controller-manager)

Exam Tips

# Find Static Pod path
kubectl get pod kube-apiserver-controlplane -n kube-system -o yaml | grep pod-manifest-path

# Find the node running control plane static Pods
kubectl get nodes

6. Pod Deletion and Termination

Graceful Termination

kubectl delete pod <pod-name>

Process:

  1. Pod enters Terminating state
  2. Execute preStop callback (if configured)
  3. Send SIGTERM to the main process (PID 1)
  4. Wait for terminationGracePeriodSeconds (default 30s)
  5. Send SIGKILL after timeout
# Custom graceful termination
spec:
  terminationGracePeriodSeconds: 60
  containers:
  - name: app
    image: nginx
    lifecycle:
      preStop:
        exec:
          command: ["/bin/sh", "-c", "sleep 10 && nginx -s quit"]

Force Delete

# Force immediate deletion (skip graceful termination)
kubectl delete pod <pod-name> --grace-period=0 --force

# Delete all Evicted/Terminating Pods
kubectl delete pod --all
kubectl delete pods --field-selector=status.phase=Failed

Delete All Pods

kubectl delete pods --all -n <namespace>
kubectl delete pods --all --all-namespaces  # Use with caution

7. Useful Command Summary

# Query resource definitions
kubectl explain pod
kubectl explain pod.spec
kubectl explain pod.spec.containers
kubectl explain pod.spec.containers.resources

# Generate Pod YAML
kubectl run test --image=nginx --restart=Never --dry-run=client -o yaml
kubectl run test --image=busybox --restart=Never --dry-run=client -o yaml -- sleep 3600

# Pod interaction
kubectl exec -it <pod-name> -- /bin/sh
kubectl exec <pod-name> -- env
kubectl logs -f <pod-name>

# Temporary Pod (for debugging)
kubectl run debug --image=nicolaka/netshoot --restart=Never --rm -it -- /bin/bash
kubectl run busybox --image=busybox --restart=Never --rm -it -- wget -O- <service-ip>

🧪 Complete Hands-On Example: Create a Pod with Init Containers and Observe the Lifecycle

Scenario

Create a Pod containing init containers and a main container, and observe the state changes at each phase.

Prerequisites

  • A working Kubernetes cluster (kubeadm/minikube)
  • kubectl configured to connect to the cluster

Steps

Step 1: Create Init Container Pod YAML

cat <<'EOF' > init-pod-demo.yaml
apiVersion: v1
kind: Pod
metadata:
  name: init-pod-demo
spec:
  initContainers:
  - name: init-wait
    image: busybox:1.28
    command: ['sh', '-c', 'echo "Init: Step 1 - Waiting for 10s..."; sleep 10; echo "Init: Step 1 done"']
  - name: init-check
    image: busybox:1.28
    command: ['sh', '-c', 'echo "Init: Step 2 - Checking config..."; sleep 5; echo "Init: Step 2 done"']
  containers:
  - name: main-app
    image: nginx
    ports:
    - containerPort: 80
EOF
# Expected output: none (file created successfully)

Step 2: Create Pod and Observe Initial State

kubectl apply -f init-pod-demo.yaml
# Expected output: pod/init-pod-demo created

kubectl get pod init-pod-demo
# Expected output: NAME            READY   STATUS     RESTARTS   AGE
#                  init-pod-demo   0/1     Init:0/2   0          <seconds>
# STATUS shows Init:0/2 indicating 2 Init containers not yet completed

Step 3: Observe Init Container Execution Process

# Real-time status monitoring
kubectl get pod init-pod-demo -w
# Expected output (sequential changes):
# init-pod-demo   0/1   Init:0/2    0     0s
# init-pod-demo   0/1   Init:1/2    0     10s    ← first init completed
# init-pod-demo   0/1   Init:1/2    0     10s    ← second init started
# init-pod-demo   0/1   PodInitializing   0     15s   ← all init containers completed
# init-pod-demo   1/1   Running          0     17s   ← main container running

Step 4: View Init Container Logs

# View first Init container logs
kubectl logs init-pod-demo -c init-wait
# Expected output:
# Init: Step 1 - Waiting for 10s...
# Init: Step 1 done

# View second Init container logs
kubectl logs init-pod-demo -c init-check
# Expected output:
# Init: Step 2 - Checking config...
# Init: Step 2 done

Step 5: Verify Main Container is Running

kubectl get pod init-pod-demo
# Expected output: NAME            READY   STATUS    RESTARTS   AGE
#                  init-pod-demo   1/1     Running   0          <minutes>

kubectl describe pod init-pod-demo | grep -A 5 Init
# Expected output shows Init containers completed

Verification

# Confirm main container web service is working
kubectl exec init-pod-demo -- curl -s -o /dev/null -w "%{http_code}" localhost
# Expected output: 200

# Clean up
kubectl delete pod init-pod-demo
# Expected output: pod "init-pod-demo" deleted

Exam Tips

  • In the CKA exam, Init container YAML format must be precise: initContainers is under spec and alongside containers
  • Each Init container must complete successfully before the next one can start
  • The exam often uses the busybox:1.28 image — small size, fast startup
  • Using kubectl describe pod to check Init container status and events is the most reliable troubleshooting method
  • Note that Init containers do not support readinessProbe, but do support resources and securityContext