Chuyển tới nội dung chính

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​

ReplicationControllerReplicaSet
apiVersionv1apps/v1
selectorKhô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áiCô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ầnVai trò
replicasSố Pod mong muốn
selector"Pod nào là của tôi"
templateKhuô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áchLệnhGhi chú
Sửa file rồi replacesửa replicas: 6 → kubectl replace -f rs.yamlFile và cluster khớp nhau
Lệnh scale theo filekubectl scale --replicas=6 -f rs.yaml⚠️ File vẫn ghi 3
Lệnh scale theo tênkubectl scale rs myapp-replicaset --replicas=6Nhanh nhất khi thi
Sửa trực tiếpkubectl edit rs myapp-replicasetCó 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