k8s对象 rc rs

ReplicationController

ReplicationController 简称为 RC,同时也是 kubectl 命令的快捷方式简写使用方式,是用来确保容器应用的副本数始终保持在用户定义的副本数。如果有容器异常退出的话,其会自动创建新的 Pod 来替代,而如果有异常多出来的容器也会被自动回收掉的。

当 pod 数量过多时,RC 会终止多余的 pod;

当 pod 数量太少时,RC 将会启动新的 pod。

与手动创建的 pod 不同之处在于,由 RC 创建的 pod 在失败、被删除或被终止时会被自动替换。例如,在中断性维护之后,创建的 pod 会在节点上会重新创建。因此,即使应用程序只需要一个 pod,也应该使用 RC 来创建 Pod。对应 RC 我们可以类似理解为进程管理器,但是 RC 不是监控单个节点上的单个进程,而是监控跨多个节点的多个 pod。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# [ReplicationController]
# .spec.template是.spec的唯一必需字段
# 只允许.spec.template.spec.restartPolicy等于Always

apiVersion: v1
kind: ReplicationController
metadata:
  name: nginx
  namespace: prod
spec:
  replicas: 3
  selector:
    app: nginx
  spec:
    metadata:
      name: nginx
      labels:
        app: nginx
    spec:
      containers:
        - name: nginx
          image: nginx
          ports:
            - containerPort: 80

奇怪的是,我们创建了三个 Pod,但发现此时并没有一个 Pod 正在运行,这是因为可以正在拉取镜像。

1
2
3
4
5
6
7
# 部署服务
$ kubectl apply -f ./replication.yaml
replicationcontroller/nginx created

# 检查RC的状态
$ kubectl describe rc/nginx
Pods Status:    3 Running / 0 Waiting / 0 Succeeded / 0 Failed

ReplicaSet

官方在新版本的 Kubernetes 中建议使用 RS 来取代 RC,而且 RS 跟 RC 的唯一区别是在选择器的支持上。其中 RS 支持集集合(selector)的选择器,其就意味着其支持通过标签进行 Pod 的选择,而 RC 仅支持基于相等选择器。

What is the difference between ReplicaSet and ReplicationController

RS 确保任何时间都有指定数量的 Pod 副本在运行,而且大多数支持 RC 的 kubectl 命令也支持 RS,但是 rolling-update 这个命令是个例外。如果你需要使用滚动更新功能,请考虑使用 Deployment 来创建 Pod。

然而 Deployment 是一个更高级的概念,它管理 RS 并向 Pod 提供声明式的更新以及许多其他有用的功能,用作协调 Pod 创建、删除和更新的机制。当你使用 Deployment 的时候,不必担心还要管理它们创建的 RS 控制器。因此,建议使用 Deployment 而不是直接使用 ReplicaSet,除非你需要自定义更新业务流程或根本不需要更新。

示例任务。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# [ReplicaSet]
# .spec.template是.spec的唯一必需字段
# 只允许.spec.template.spec.restartPolicy等于Always

apiVersion: apps/v1
kind: ReplicaSet
metadata:
  name: frontend
  namespace: prod
  labels:
    app: guestbook
    tier: frontend
spec:
  replicas: 3
  selector:
    matchLabels:
      tier: frontend
  template:
    metadata:
      labels:
        tier: frontend
    spec:
      containers:
      - name: php-redis
        image: gcr.io/google_samples/gb-frontend:v3
        - name: GET_HOSTS_FROM
          value: dns
        ports:
          containerPort: 80
        env:

将此清单保存到 frontend.yaml 中,并将其提交到 Kubernetes 集群,应该就能创建 yaml 文件所定义的 ReplicaSet 及其管理的 Pod。

1
2
3
4
5
6
# 部署服务
$ kubectl create -f ./frontend.yaml
replicaset.apps/frontend created

# 检查RC的状态
$ kubectl describe rs/frontend