RC(ReplicationController)
Replication Controller主要作用是用来确保容器应用的副本数和用户设置的副本数一致。如果用容器异常退出,会自动创建新的Pod来替代,而如果异常多出来的容器则会自动回收。
如下图所示,为某个Pod创建了Replication Controller并且指定3个副本,它会创建3个Pod,并且持续监控它们。如果某个Pod不响应,那么Replication Controller会替换它,保持总数为3.如下面的动画所示:

如果之前不响应的Pod恢复了,现在就有4个Pod了,那么Replication Controller会将其中一个终止保持总数为3。如果在运行中将副本总数改为5,Replication Controller会立刻启动2个新Pod,保证总数为5。还可以按照这样的方式缩小Pod,这个特性在执行滚动升级时很有用。
RS(ReplicaSet)
ReplicaSet 和RC没有本质的不同,唯一的区别是ReplicaSet支持标签选择器(Selector)。
ReplicaSet由3个部分组成:
标签选择器(label selector): 确定 ReplicaSet 作用域中有哪些 Pod
副本个数(replica count): 指定应运行的 Pod 数量
Pod 模板(pod template): 用于创建新的 Pod 副本
eg:
apiVersion: apps/v1kind: ReplicaSetmetadata:name: nginxspec:replicas: 3selector:matchLabels:app: nginxtemplate:metadata:labels:app: nginxspec:containers:- name: nginximage: nginx:latest
执行
$ kubectl create -f nginx-replicaset.yamlreplicaset.apps/nginx created
查看pod
$ kubectl get podsNAME READY STATUS RESTARTS AGEnginx-4cw6k 1/1 Running 0 5m29snginx-54ljh 1/1 Running 0 5m29snginx-m9wct 1/1 Running 0 5m29s
查看rs
$ kubectl get rsNAME DESIRED CURRENT READY AGEnginx 3 3 3 5m52s
查看rs 详细信息
$ kubectl describe rsName: nginxNamespace: defaultSelector: app=nginxLabels: <none>Annotations: <none>Replicas: 3 current / 3 desiredPods Status: 3 Running / 0 Waiting / 0 Succeeded / 0 FailedPod Template:Labels: app=nginxContainers:nginx:Image: nginx:latestPort: <none>Host Port: <none>Environment: <none>Mounts: <none>Volumes: <none>Events:Type Reason Age From Message---- ------ ---- ---- -------Normal SuccessfulCreate 6m37s replicaset-controller Created pod: nginx-4cw6kNormal SuccessfulCreate 6m37s replicaset-controller Created pod: nginx-54ljhNormal SuccessfulCreate 6m37s replicaset-controller Created pod: nginx-m9wct
删除rs, 在删除 nginx ReplicaSet 时也会删除对应匹配的所有 Pod。
$ kubectl delete rs nginxreplicaset.apps "nginx" deleted
注意
尽管RS都可以单独使用,但是一般实际应用中建议使用Deployment来自动管理ReplicaSet,Deployment管理ReplicaSet并为Pod和ReplicaSet提供声明性更新以及许多其他有用的功能,因此在实际使用中,使用Deployment代替ReplicaSet。
