Chuyển đến nội dung chính

Bài 2: Pods, Workloads & Controllers

Pod lifecycle. Deployments, ReplicaSets, StatefulSets, DaemonSets, Jobs, CronJobs. Labels, selectors, annotations.

Kubernetes Workload Controllers — Deployment, StatefulSet, DaemonSet, Job

1. Pod — Đơn vị nhỏ nhất

Một Pod là nhóm 1 hoặc nhiều containers chia sẻ cùng network namespace (cùng IP, port space) và storage volumes. Pod là đơn vị scheduling trong Kubernetes.

┌─────────────────────────────────────┐
│              POD                    │
│  IP: 10.244.1.5                     │
│  ┌────────────┐  ┌───────────────┐  │
│  │  Container │  │  Sidecar      │  │
│  │   (app)    │  │  (log-agent)  │  │
│  └────────────┘  └───────────────┘  │
│       Shared Volume: /var/log       │
└─────────────────────────────────────┘

Pod Lifecycle

PhaseÝ nghĩaDebug hint
PendingChưa được schedule hoặc đang pull imageCheck events: kubectl describe pod
RunningĐang chạy, ít nhất 1 container đang activeNormal state
SucceededTất cả containers thoát với code 0Job completed
FailedÍt nhất 1 container thoát với lỗikubectl logs --previous
UnknownKhông liên lạc được với nodeNode network issue
CrashLoopBackOffContainer liên tục crash và restartkubectl logs -p

Exam tip: CrashLoopBackOff không phải Pod phase chính thức — nó là Container state trong Waiting. Câu hỏi hay hỏi "pod phase" vs "container state".

2. Workload Controllers

ControllerDùng khiĐặc điểm nổi bật
DeploymentStateless apps (web server, API)Rolling update, rollback, ReplicaSet management
ReplicaSetĐảm bảo N replicas (thường dùng qua Deployment)Label selector, ít dùng trực tiếp
StatefulSetStateful apps (database, Kafka, Elasticsearch)Stable pod names (web-0, web-1), stable storage, ordered deployment
DaemonSetAgent chạy trên mọi node (logging, monitoring, network)1 Pod/node, auto-deploy khi node mới join
JobBatch task chạy đến khi hoàn thànhcompletions, parallelism, backoffLimit
CronJobPeriodic batch taskscron syntax, concurrencyPolicy, schedule

Deployment vs StatefulSet

DEPLOYMENT (Stateless)          STATEFULSET (Stateful)
─────────────────────           ────────────────────────
Pod names: web-a1b2c3            Pod names: web-0, web-1, web-2
Any order scale up/down          Ordered: web-0 first, then web-1...
Shared or no storage             Each Pod gets its own PVC
Pod replaced = new identity      Pod replaced = same identity
Examples: nginx, api-server      Examples: MySQL, MongoDB, Kafka

3. Labels, Selectors & Annotations

ConceptDùng đểVí dụ
LabelsTag resources để select và groupapp: frontend, env: prod
SelectorsQuery resources theo labelsselector: {app: frontend}
AnnotationsMetadata không dùng để select (build info, contact)maintainer: [email protected]

Exam tip: Service tìm Pods qua selector matching Pod labels. Nếu selector không match, Service sẽ có empty Endpoints → traffic không đến được Pod.

4. DaemonSet Use Cases

NODE 1         NODE 2         NODE 3
┌──────┐       ┌──────┐       ┌──────┐
│fluentd│      │fluentd│      │fluentd│  ← Log collector DaemonSet
│ Pod  │       │ Pod  │       │ Pod  │
├──────┤       ├──────┤       ├──────┤
│calico│       │calico│       │calico│  ← CNI network plugin DaemonSet
│ Pod  │       │ Pod  │       │ Pod  │
└──────┘       └──────┘       └──────┘

DaemonSets thường dùng cho: Fluentd/Filebeat (log collection), Prometheus Node Exporter (metrics), kube-proxy (networking), CNI plugins (Calico, Cilium).

5. Cheat Sheet

Câu hỏi examĐáp án
Stateful app, cần stable identity?StatefulSet
1 Pod per node (monitoring agent)?DaemonSet
Stateless app với rolling update?Deployment
One-time batch processing?Job
Scheduled batch (nightly backup)?CronJob
Pod naming pattern cho StatefulSet?name-0, name-1, name-2

6. Practice Questions

Q1: A company needs to deploy a MySQL database on Kubernetes with stable network identity and dedicated storage per replica. Which workload type should they use?

  • A) Deployment with PersistentVolumeClaim
  • B) StatefulSet ✓
  • C) DaemonSet
  • D) ReplicaSet

Explanation: StatefulSet provides stable Pod names (mysql-0, mysql-1), ordered deployment/scaling, and each Pod gets its own PVC via volumeClaimTemplates. These properties are essential for databases.

Q2: Which workload ensures exactly one Pod runs on every node in the cluster, including future nodes that join?

  • A) Deployment with replicas matching node count
  • B) ReplicaSet with nodeSelector
  • C) DaemonSet ✓
  • D) StatefulSet

Explanation: DaemonSet automatically deploys one Pod per node and watches cluster membership — when a new node joins, the DaemonSet controller immediately creates a Pod on it.

Q3: A Pod is in 'Pending' state. What is the MOST likely cause?

  • A) The container application crashed
  • B) No node satisfies the scheduling requirements ✓
  • C) The liveness probe failed
  • D) The container image is corrupted

Explanation: Pending means the Pod has been accepted but hasn't started. Most common reasons: insufficient CPU/memory on nodes, unsatisfied node affinity/taints, or PVC not bound. Check kubectl describe pod events.