ReplicaSet即副本集控制器,目的是在任何给定时间维护一组稳定的副本Pod。 因此,它通常用于保证指定数量的相同Pod的可用性。ReplicaSet与其Pods的链接是通过Pods的metadata.ownerReferences字段实现的,该字段指定当前对象所拥有的资源。 ReplicaSet获取的所有Pod在其ownerReferences字段中拥有其拥有的ReplicaSet标识信息。 通过此链接,ReplicaSet知道它正在维护的Pod的状态并相应地进行计划更新。

使用场景

ReplicaSet确保在任何给定时间运行指定数量的pod副本。 但是,Deployments是一个更高级别的概念,它管理ReplicaSet并为Pod提供声明性更新以及许多其他有用的功能。 因此,我们建议使用Deployments而不是直接使用ReplicaSet,除非您需要自定义更新编排或根本不需要更新。这实际上意味着我们可能永远不需要配置eplicaSet对象:更多的是直接使用Deployment,并在spec部分中定义我们的程序。

示例

frontend.yaml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
apiVersion: apps/v1
kind: ReplicaSet
metadata:
name: frontend
labels:
app: guestbook
tier: frontend
spec:
# modify replicas according to your case
replicas: 3 # 副本数
selector: # Pod选择器
matchLabels:
tier: frontend
template: # pod模板配置
metadata:
labels:
tier: frontend
spec:
containers:
- name: php-redis
image: gcr.io/google_samples/gb-frontend:v3

创建

1
kubectl apply -f https://kubernetes.io/examples/controllers/frontend.yaml

查看ReplicaSet

1
2
3
4
kubectl get rs

NAME DESIRED CURRENT READY AGE
frontend 3 3 3 6s

查看它维护的Pod

1
2
3
4
5
6
kubectl get Pods

NAME READY STATUS RESTARTS AGE
frontend-9si5l 1/1 Running 0 1m
frontend-dnjpy 1/1 Running 0 1m
frontend-qhloh 1/1 Running 0 1m

水平扩展

1
kubectl scale rs frontend --replicas=4

自动水平扩展

1
kubectl autoscale rs frontend --max=10

结语

k8s中有许多同样具有ReplicaSet功能的更高级别的控制器对象,建议使用如下这些代替ReplicaSet,后面章节我会稍作介绍:

  • Deployment
  • Bare Pods
  • Job
  • DaemonSet
  • ReplicationController