ReplicationController 和 ReplicaSet

ReplicationController(也简称为 rc)用来确保容器应用的副本数始终保持在用户定义的副本数,即如果有容器异常退出,会自动创建新的 Pod 来替代;而异常多出来的容器也会自动回收。ReplicationController 的典型应用场景包括确保健康 Pod 的数量、弹性伸缩、滚动升级以及应用多版本发布跟踪等。

在新版本的 Kubernetes 中建议使用 ReplicaSet(也简称为 rs)来取代 ReplicationController。ReplicaSet 跟 ReplicationController 没有本质的不同,只是名字不一样,并且 ReplicaSet 支持集合式的 selector(ReplicationController 仅支持等式)。

虽然也 ReplicaSet 可以独立使用,但建议使用 Deployment 来自动管理 ReplicaSet,这样就无需担心跟其他机制的不兼容问题(比如 ReplicaSet 不支持 rolling-update 但 Deployment 支持),并且还支持版本记录、回滚、暂停升级等高级特性。Deployment 的详细介绍和使用方法见 这里

API 版本对照表

Kubernetes 版本 ReplicaSet API 版本 ReplicationController 版本
v1.5-v1.7 extensions/v1beta1 core/v1
v1.8 apps/v1beta2 core/v1
v1.9 apps/v1 core/v1

ReplicationController 示例

  1. apiVersion: v1
  2. kind: ReplicationController
  3. metadata:
  4. name: nginx
  5. spec:
  6. replicas: 3
  7. selector:
  8. app: nginx
  9. template:
  10. metadata:
  11. name: nginx
  12. labels:
  13. app: nginx
  14. spec:
  15. containers:
  16. - name: nginx
  17. image: nginx
  18. ports:
  19. - containerPort: 80

ReplicaSet 示例

  1. apiVersion: extensions/v1beta1
  2. kind: ReplicaSet
  3. metadata:
  4. name: frontend
  5. # these labels can be applied automatically
  6. # from the labels in the pod template if not set
  7. # labels:
  8. # app: guestbook
  9. # tier: frontend
  10. spec:
  11. # this replicas value is default
  12. # modify it according to your case
  13. replicas: 3
  14. # selector can be applied automatically
  15. # from the labels in the pod template if not set,
  16. # but we are specifying the selector here to
  17. # demonstrate its usage.
  18. selector:
  19. matchLabels:
  20. tier: frontend
  21. matchExpressions:
  22. - {key: tier, operator: In, values: [frontend]}
  23. template:
  24. metadata:
  25. labels:
  26. app: guestbook
  27. tier: frontend
  28. spec:
  29. containers:
  30. - name: php-redis
  31. image: gcr.io/google_samples/gb-frontend:v3
  32. resources:
  33. requests:
  34. cpu: 100m
  35. memory: 100Mi
  36. env:
  37. - name: GET_HOSTS_FROM
  38. value: dns
  39. # If your cluster config does not include a dns service, then to
  40. # instead access environment variables to find service host
  41. # info, comment out the 'value: dns' line above, and uncomment the
  42. # line below.
  43. # value: env
  44. ports:
  45. - containerPort: 80