ReplicaSets
1. Vì sao cần ReplicaSet?
- Pod "trần": chết là mất luôn, không ai tạo lại.
- Có ReplicaSet: Pod chết thì có Pod mới thay (self-healing). Vì vậy dù chỉ cần 1 Pod, production cũng không chạy Pod trần.
- Ngoài ra còn để chạy nhiều bản – chia tải và scale, trải trên nhiều node.
Phân vai
ReplicaSet chỉ giữ đủ số lượng Pod. Việc chia request do Service làm, việc chọn node do kube-scheduler làm.
2. ReplicationController vs ReplicaSet
| ReplicationController | ReplicaSet | |
|---|---|---|
| apiVersion | v1 | apps/v1 |
selector | Không bắt buộc (mặc định = labels trong template) | Bắt buộc, viết dạng matchLabels (hoặc matchExpressions) |
| Trạng thái | Công nghệ cũ | Khuyến nghị dùng |
ReplicationController
apiVersion: v1
kind: ReplicationController
metadata:
name: myapp-rc
spec:
replicas: 3
template: # nguyên phần Pod (trừ apiVersion/kind)
metadata:
name: myapp-pod
labels:
app: myapp
spec:
containers:
- name: nginx
image: nginx
ReplicaSet
apiVersion: apps/v1
kind: ReplicaSet
metadata:
name: myapp-replicaset
spec:
replicas: 3
selector:
matchLabels:
app: myapp # phải khớp labels trong template
template:
metadata:
labels:
app: myapp
spec:
containers:
- name: nginx
image: nginx
| Phần | Vai trò |
|---|---|
replicas | Số Pod mong muốn |
selector | "Pod nào là của tôi" |
template | Khuôn để tạo Pod mới khi thiếu |
3. Labels và Selector
- ReplicaSet theo dõi Pod bằng label, không bằng tên.
- Nó có thể "nhận nuôi" cả Pod đã tồn tại từ trước nếu label khớp selector.
Thí nghiệm
Tạo trước 1 Pod trần có label app=myapp, sau đó tạo ReplicaSet replicas: 3 cùng selector → RS chỉ tạo thêm 2 Pod. Nếu tạo thêm 1 Pod trần có label khớp → RS xóa ngay Pod thừa.
Vậy tại sao vẫn cần template khi đã có Pod sẵn? Vì khi Pod chết, RS cần khuôn để tạo Pod mới.
4. Scale
| Cách | Lệnh | Ghi chú |
|---|---|---|
| Sửa file rồi replace | sửa replicas: 6 → kubectl replace -f rs.yaml | File và cluster khớp nhau |
| Lệnh scale theo file | kubectl scale --replicas=6 -f rs.yaml | ⚠️ File vẫn ghi 3 |
| Lệnh scale theo tên | kubectl scale rs myapp-replicaset --replicas=6 | Nhanh nhất khi thi |
| Sửa trực tiếp | kubectl edit rs myapp-replicaset | Có hiệu lực ngay |
5. Lưu ý: đổi image trong ReplicaSet
ReplicaSet chỉ biết đếm
kubectl set image rs/... hoặc kubectl edit rs đổi image từ 1.26 → 1.27: 3 Pod đang chạy vẫn là 1.26, vì số lượng vẫn đủ. Chỉ Pod được tạo sau này mới dùng 1.27. Muốn áp dụng phải xóa các Pod cũ để RS tạo lại – hoặc dùng Deployment.
6. Lệnh hay dùng
kubectl create -f rs.yaml
kubectl get replicaset # viết tắt: kubectl get rs
kubectl describe rs myapp-replicaset
kubectl delete rs myapp-replicaset # xóa luôn các Pod bên dưới
kubectl explain replicaset