COMPREHENSIVE HANDBOOK21 pages + cover

Complete Kubernetes Handbook: Architecture & Core Objects Guide

Illustrated reference for Pods, ReplicaSets, Services, Ingress, Persistent Volumes, and cluster scheduling.

Curated by Vibe DevOps · Published:

Handbook illustration for K8S: 21 pages, visual slides
Handbook Cover Slide (4:5)
PAGE 01: Kubernetes là gì?
Slide 01 / 21↑ TOC

PAGE 01 · Kubernetes là gì?

Kubernetes là gì?

Hệ thống điều phối container trên nhiều máy. Bạn khai báo trạng thái mong muốn, cluster tự đưa hệ thống về đúng trạng thái đó.

K8s làm thay bạn

  • Tự chạy lại container bị chết
  • Scale số bản sao theo tải
  • Rolling update, rollback
  • Cân bằng tải, tìm service

Từ khóa nền tảng

Cluster
nhóm máy chạy K8s
Node
một máy trong cluster
Pod
đơn vị chạy nhỏ nhất
Manifest
file YAML mô tả tài nguyên

Vòng lặp điều khiển

  1. YAML
  2. apply
  3. API server
  4. lưu etcd
  5. controller
  6. so sánh
  7. sửa lệch
PAGE 02: Kiến trúc cluster
Slide 02 / 21↑ TOC

PAGE 02 · Kiến trúc cluster

Kiến trúc cluster

Control plane ra quyết định; worker node chạy Pod thật.

Control plane

kube-apiserver
cửa ngõ duy nhất, mọi lệnh đi qua đây
etcd
kho key-value lưu toàn bộ trạng thái cluster
kube-scheduler
chọn node phù hợp cho Pod mới
controller-manager
chạy các controller giữ đúng trạng thái

Worker node

kubelet
agent nhận lệnh, bảo runtime chạy container
container runtime
containerd hoặc CRI-O
kube-proxy
dựng luật mạng cho Service
PAGE 03: kubectl & context
Slide 03 / 21↑ TOC

PAGE 03 · kubectl & context

kubectl & context

kubectl đọc file kubeconfig để biết cluster, user và namespace mặc định.

Kiểm tra kết nối

$ kubectl version
$ kubectl cluster-info
$ kubectl get nodes -o wide

Đổi cluster

$ kubectl config \
    get-contexts
$ kubectl config \
    use-context prod

Namespace mặc định & tra cứu

$ kubectl config set-context --current --namespace=shop
$ kubectl api-resources                 # mọi loại tài nguyên
$ kubectl explain deployment.spec       # tài liệu từng field
PAGE 04: Pod — đơn vị nhỏ nhất
Slide 04 / 21↑ TOC

PAGE 04 · Pod

Pod — đơn vị nhỏ nhất

Pod chứa một hoặc vài container dùng chung IP, cổng và volume.

pod.yaml

apiVersion: v1
kind: Pod
metadata:
  name: web
  labels: {app: web}
spec:
  containers:
  - name: nginx
    image: nginx:1.27
    ports:
    - containerPort: 80

Trạng thái (phase)

Pending
chưa xếp lịch / đang kéo image
Running
đã có container chạy
Succeeded
chạy xong, thoát 0
Failed
container thoát lỗi
PAGE 05: Manifest & kubectl apply
Slide 05 / 21↑ TOC

PAGE 05 · Manifest & apply

Manifest & kubectl apply

Mọi tài nguyên đều có 4 phần: apiVersion, kind, metadata, spec.

Tạo / cập nhật

$ kubectl apply -f app.yaml
$ kubectl apply -f k8s/
$ kubectl delete -f app.yaml

Xem trước thay đổi

$ kubectl diff -f app.yaml
$ kubectl apply -f app.yaml \
    --dry-run=server

Sinh YAML mẫu thay vì gõ tay

$ kubectl create deployment web --image=nginx:1.27 \
    --dry-run=client -o yaml > web.yaml
$ kubectl get deploy web -o yaml        # xem bản đang chạy
PAGE 06: Label, selector & namespace
Slide 06 / 21↑ TOC

PAGE 06 · Label & namespace

Label, selector & namespace

Label gắn nhãn tài nguyên; selector dùng nhãn để chọn. Namespace chia cluster thành nhiều khu.

Làm việc với label

$ kubectl get pods \
    -l app=web
$ kubectl get pods \
    --show-labels
$ kubectl label pod web \
    tier=frontend

Namespace

$ kubectl get ns
$ kubectl create ns shop
$ kubectl get pods -n shop
$ kubectl get pods -A

Ai dùng selector?

Deployment
biết Pod nào thuộc về mình
Service
chọn Pod để chuyển traffic tới
NetworkPolicy
chọn Pod áp luật mạng
PAGE 07: Deployment & ReplicaSet
Slide 07 / 21↑ TOC

PAGE 07 · Deployment

Deployment & ReplicaSet

Deployment quản lý ReplicaSet; ReplicaSet giữ đúng số Pod đang chạy.

deployment.yaml

apiVersion: apps/v1
kind: Deployment
metadata: {name: web}
spec:
  replicas: 3
  selector:
    matchLabels: {app: web}
  template:
    metadata: {labels: {app: web}}
    spec:
      containers:
      - {name: web, image: ghcr.io/team/web:1.4.2}
PAGE 08: Rolling update & rollback
Slide 08 / 21↑ TOC

PAGE 08 · Rolling update

Rolling update & rollback

Đổi image là K8s thay dần Pod cũ bằng Pod mới, không gây gián đoạn nếu probe chuẩn.

Cập nhật & theo dõi

$ kubectl set image deploy/web web=ghcr.io/team/web:1.5.0
$ kubectl rollout status deploy/web
$ kubectl rollout history deploy/web

Quay lại

$ kubectl rollout undo \
    deploy/web
$ kubectl rollout undo \
    deploy/web --to-revision=3

Tham số chiến lược

maxSurge
số Pod được tạo dư thêm
maxUnavailable
số Pod được phép thiếu
Recreate
xóa hết rồi tạo lại
PAGE 09: Service — địa chỉ ổn định
Slide 09 / 21↑ TOC

PAGE 09 · Service

Service — địa chỉ ổn định

IP của Pod thay đổi liên tục. Service cho một tên DNS và IP cố định, cân bằng tải tới các Pod khớp selector.

service.yaml

apiVersion: v1
kind: Service
metadata: {name: web}
spec:
  type: ClusterIP
  selector: {app: web}
  ports:
  - port: 80
    targetPort: 8080

Các loại Service

ClusterIP
chỉ trong cluster (mặc định)
NodePort
mở cổng 30000–32767 trên mọi node
LoadBalancer
xin LB của cloud
Headless
clusterIP: None, trả IP từng Pod
PAGE 10: Ingress — HTTP vào cluster
Slide 10 / 21↑ TOC

PAGE 10 · Ingress

Ingress — HTTP vào cluster

Một điểm vào chung, định tuyến theo domain và path tới Service bên trong. Cần cài Ingress controller (vd. ingress-nginx).

ingress.yaml

apiVersion: networking.k8s.io/v1
kind: Ingress
metadata: {name: shop}
spec:
  ingressClassName: nginx
  tls:
  - hosts: [shop.example.com]
    secretName: shop-tls
  rules:
  - host: shop.example.com
    http:
      paths:
      - path: /api
        pathType: Prefix
        backend:
          service: {name: api, port: {number: 80}}
PAGE 11: ConfigMap & Secret
Slide 11 / 21↑ TOC

PAGE 11 · ConfigMap & Secret

ConfigMap & Secret

Tách cấu hình khỏi image: cùng một image, khác cấu hình theo môi trường.

Tạo nhanh

$ kubectl create configmap web-cfg --from-literal=LOG_LEVEL=info
$ kubectl create secret generic db-cred \
    --from-literal=DB_PASSWORD='<mật-khẩu>'

Nạp vào container

    envFrom:
    - configMapRef: {name: web-cfg}
    - secretRef: {name: db-cred}

Khác nhau

ConfigMap

  • Cấu hình không nhạy cảm
  • Lưu dạng text thường

Secret

  • Mật khẩu, token, cert
  • Chỉ encode base64
PAGE 12: PV, PVC & StorageClass
Slide 12 / 21↑ TOC

PAGE 12 · Lưu trữ

PV, PVC & StorageClass

Pod xin ổ đĩa bằng PVC; StorageClass tự cấp PV phù hợp từ hạ tầng.

pvc.yaml

apiVersion: v1
kind: PersistentVolumeClaim
metadata: {name: pgdata}
spec:
  accessModes: [ReadWriteOnce]
  storageClassName: standard
  resources:
    requests: {storage: 10Gi}

Khái niệm

PV
ổ đĩa thật trong cluster
PVC
yêu cầu dung lượng của Pod
StorageClass
loại ổ, tự cấp phát
RWO / RWX
một node / nhiều node ghi

Kiểm tra

$ kubectl get pvc,pv
$ kubectl describe pvc pgdata           # xem vì sao còn Pending
PAGE 13: StatefulSet, DaemonSet & Job
Slide 13 / 21↑ TOC

PAGE 13 · Các loại workload

StatefulSet, DaemonSet & Job

Không phải mọi thứ đều là Deployment. Chọn đúng controller cho đúng loại việc.

Chọn controller nào?

Deployment
app không trạng thái: web, API
StatefulSet
tên Pod cố định, ổ riêng từng Pod: database
DaemonSet
mỗi node một Pod: agent log, monitoring
Job
chạy tới khi xong: migrate, batch
CronJob
Job theo lịch cron

Lệnh nhanh

$ kubectl get sts,ds,jobs,cronjobs -A
$ kubectl create cronjob backup --image=backup:1.0 \
    --schedule="0 2 * * *"           # 2 giờ sáng mỗi ngày
PAGE 14: Requests, limits & QoS
Slide 14 / 21↑ TOC

PAGE 14 · Requests & limits

Requests, limits & QoS

Requests dùng để xếp lịch; limits là trần tài nguyên khi chạy.

Khai báo tài nguyên

resources:
  requests:
    cpu: 250m
    memory: 256Mi
  limits:
    memory: 512Mi

Vượt giới hạn

CPU
bị bóp chậm (throttle)
Memory
bị kill: OOMKilled
250m
0,25 nhân CPU

Lớp QoS

Guaranteed
mọi container có requests = limits cho CPU và RAM
Burstable
có ít nhất một requests hoặc limits
BestEffort
không khai báo gì — bị đuổi đầu tiên khi thiếu RAM
PAGE 15: Health check: probes
Slide 15 / 21↑ TOC

PAGE 15 · Probes

Health check: probes

Kubelet hỏi thăm container để biết khi nào cho traffic vào và khi nào cần khởi động lại.

Ba loại probe

startupProbe
chờ app khởi động chậm; chưa qua thì hoãn hai probe kia
readinessProbe
chưa đạt → bỏ khỏi endpoint của Service
livenessProbe
thất bại liên tục → khởi động lại container

Ví dụ HTTP probe

readinessProbe:
  httpGet: {path: /ready, port: 8080}
  periodSeconds: 5
livenessProbe:
  httpGet: {path: /healthz, port: 8080}
  initialDelaySeconds: 15
  failureThreshold: 3
PAGE 16: Tự scale với HPA
Slide 16 / 21↑ TOC

PAGE 16 · Autoscaling

Tự scale với HPA

HorizontalPodAutoscaler tăng giảm số Pod theo CPU, RAM hoặc metric tùy chỉnh.

Tạo HPA

$ kubectl autoscale deploy web --cpu-percent=70 \
    --min=3 --max=10
$ kubectl get hpa
$ kubectl top pods                      # cần metrics-server

Điều kiện để HPA chạy

  • Đã cài metrics-server
  • Container có khai báo requests.cpu
  • Tỉ lệ % tính trên requests, không phải limits
PAGE 17: Phân quyền RBAC
Slide 17 / 21↑ TOC

PAGE 17 · RBAC

Phân quyền RBAC

Ai (subject) được làm gì (verb) trên tài nguyên nào (resource), trong phạm vi nào.

Thành phần chính

Role
tập quyền trong một namespace
ClusterRole
tập quyền toàn cluster
RoleBinding
gán Role cho user / ServiceAccount
ClusterRoleBinding
gán ClusterRole toàn cluster
ServiceAccount
danh tính của Pod khi gọi API

Tạo & kiểm tra quyền

$ kubectl create role pod-reader -n shop \
    --verb=get,list,watch --resource=pods
$ kubectl create rolebinding ci-read -n shop \
    --role=pod-reader --serviceaccount=shop:ci
$ kubectl auth can-i list pods -n shop \
    --as=system:serviceaccount:shop:ci
PAGE 18: Debug Pod lỗi
Slide 18 / 21↑ TOC

PAGE 18 · Debug Pod lỗi

Debug Pod lỗi

Đọc trạng thái trước, rồi mới đoán nguyên nhân.

Trạng thái hay gặp

Pending
thiếu tài nguyên, PVC chưa bind, taint
ImagePullBackOff
sai tên/tag image, thiếu quyền registry
CrashLoopBackOff
app thoát liên tục — xem log lần trước
OOMKilled
vượt memory limit, exit 137
CreateContainerConfigError
thiếu ConfigMap / Secret

Thứ tự điều tra

  1. get pods
  2. describe
  3. logs
  4. events
  5. exec
PAGE 19: Bộ lệnh debug
Slide 19 / 21↑ TOC

PAGE 19 · Lệnh debug

Bộ lệnh debug

Những lệnh dùng nhiều nhất khi trực sự cố.

Log

$ kubectl logs web-7d4 \
    -f --tail=100
$ kubectl logs web-7d4 \
    --previous
$ kubectl logs deploy/web

Vào bên trong

$ kubectl exec -it \
    web-7d4 -- sh
$ kubectl port-forward \
    svc/web 8080:80

Sự kiện & tài nguyên

$ kubectl get events --sort-by=.lastTimestamp
$ kubectl top nodes
$ kubectl debug -it web-7d4 --image=busybox:1.36 \
    --target=web                        # khi image gốc thiếu shell
PAGE 20: Helm — trình quản lý gói
Slide 20 / 21↑ TOC

PAGE 20 · Helm

Helm — trình quản lý gói

Đóng gói nhiều manifest thành chart có tham số, cài và nâng cấp bằng một lệnh.

Cài chart

$ helm repo add bitnami https://charts.bitnami.com/bitnami
$ helm install pg bitnami/postgresql -n db \
    --create-namespace -f values.yaml

Nâng cấp & quay lại

$ helm upgrade pg bitnami/postgresql -n db -f values.yaml
$ helm history pg -n db
$ helm rollback pg 2 -n db

Xem trước manifest

$ helm template pg bitnami/postgresql -f values.yaml
PAGE 21: Ôn tập phỏng vấn
Slide 21 / 21↑ TOC

PAGE 21 · Câu hỏi phỏng vấn

Ôn tập phỏng vấn

Những câu hay gặp về Kubernetes, trả lời ngắn gọn.

Hỏi nhanh – đáp gọn

Pod vs container?
Pod bọc 1+ container dùng chung mạng và volume
Deployment vs StatefulSet?
app không trạng thái vs tên và ổ cố định
Service để làm gì?
IP/DNS ổn định và cân bằng tải tới Pod
Readiness vs liveness?
nhận traffic hay chưa vs có cần restart
Requests vs limits?
xếp lịch vs trần tài nguyên
CrashLoopBackOff?
app thoát liên tục; xem logs --previous
Secret có an toàn?
chỉ base64; cần RBAC + mã hóa etcd

Found this useful? Save the original post on Facebook for quick reference.