diff --git a/.vuepress/config-sidebar.js b/.vuepress/config-sidebar.js index 723bb61..41170ef 100644 --- a/.vuepress/config-sidebar.js +++ b/.vuepress/config-sidebar.js @@ -36,6 +36,7 @@ module.exports = { 'install-docker-desktop', ['install-k8s', '安装Kubernetes单Master节点'], 'install-kubernetes', + 'install-node-port-range' ] }, { @@ -155,6 +156,7 @@ module.exports = { 'k8s-intermediate/workload/pod-health.html', 'k8s-intermediate/workload/workload', + 'k8s-intermediate/workload/wl-replicaset/', { title: '控制器 - Deployment', collapsable: true, diff --git a/.vuepress/public/landing.html b/.vuepress/public/landing.html index 9a687ea..3e8a683 100755 --- a/.vuepress/public/landing.html +++ b/.vuepress/public/landing.html @@ -167,7 +167,7 @@ - + - + @@ -203,7 +203,7 @@ target="_blank" href="http://demo.kuboard.cn/#/dashboard?k8sToken=eyJhbGciOiJSUzI1NiIsImtpZCI6IiJ9.eyJpc3MiOiJrdWJlcm5ldGVzL3NlcnZpY2VhY2NvdW50Iiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9uYW1lc3BhY2UiOiJrdWJlLXN5c3RlbSIsImt1YmVybmV0ZXMuaW8vc2VydmljZWFjY291bnQvc2VjcmV0Lm5hbWUiOiJrdWJvYXJkLXZpZXdlci10b2tlbi1mdGw0diIsImt1YmVybmV0ZXMuaW8vc2VydmljZWFjY291bnQvc2VydmljZS1hY2NvdW50Lm5hbWUiOiJrdWJvYXJkLXZpZXdlciIsImt1YmVybmV0ZXMuaW8vc2VydmljZWFjY291bnQvc2VydmljZS1hY2NvdW50LnVpZCI6ImE1YWFiMmQxLTQxMjYtNDU5Yi1hZmNhLTkyYzMwZDk0NTQzNSIsInN1YiI6InN5c3RlbTpzZXJ2aWNlYWNjb3VudDprdWJlLXN5c3RlbTprdWJvYXJkLXZpZXdlciJ9.eYqN3FLIT6xs0-lm8AidZtaiuHeX70QTn9FhJglhEyh5dlyMU5lo8UtR-h1OY8sTSeYdYKJAS83-9SUObKQhp6XNmRgOYAfZblKUy4mvbGVQ3dn_qnzxYxt6zdGCwIY7E34eNNd9IjMF7G_Y4eJLWE7NvkSB1O8zbdn8En9rQXv_xJ9-ugCyr4CYB1lDGuZl3CIXgQ1FWcQdUBrxTT95tzcNTB0l6OUOGhRxOfw-RyIOST83GV5U0iVzxnD4sjgSaJefvCU-BmwXgpxAwRVhFyHEziXXa0CuZfBfJbmnQW308B4wocr4QDm6Nvmli1P3B6Yo9-HNF__d2hCwZEr7eg"> 在线演示 -
  • 开始安装
  • +
  • 查看教程
  • diff --git a/.vuepress/public/statics/learning/replicaset/frontend.yaml b/.vuepress/public/statics/learning/replicaset/frontend.yaml new file mode 100644 index 0000000..741f191 --- /dev/null +++ b/.vuepress/public/statics/learning/replicaset/frontend.yaml @@ -0,0 +1,21 @@ +apiVersion: apps/v1 +kind: ReplicaSet +metadata: + name: frontend + labels: + app: guestbook + tier: frontend +spec: + # modify replicas according to your case + replicas: 3 + selector: + matchLabels: + tier: frontend + template: + metadata: + labels: + tier: frontend + spec: + containers: + - name: nginx + image: nginx diff --git a/.vuepress/public/statics/learning/replicaset/hpa-rs.yaml b/.vuepress/public/statics/learning/replicaset/hpa-rs.yaml new file mode 100644 index 0000000..a838853 --- /dev/null +++ b/.vuepress/public/statics/learning/replicaset/hpa-rs.yaml @@ -0,0 +1,11 @@ +apiVersion: autoscaling/v1 +kind: HorizontalPodAutoscaler +metadata: + name: frontend-scaler +spec: + scaleTargetRef: + kind: ReplicaSet + name: frontend + minReplicas: 3 + maxReplicas: 10 + targetCPUUtilizationPercentage: 50 diff --git a/.vuepress/public/statics/learning/replicaset/pod-rs.yaml b/.vuepress/public/statics/learning/replicaset/pod-rs.yaml new file mode 100644 index 0000000..a9fe66b --- /dev/null +++ b/.vuepress/public/statics/learning/replicaset/pod-rs.yaml @@ -0,0 +1,23 @@ +apiVersion: v1 +kind: Pod +metadata: + name: pod1 + labels: + tier: frontend +spec: + containers: + - name: hello1 + image: nginx:1.7.9 + +--- + +apiVersion: v1 +kind: Pod +metadata: + name: pod2 + labels: + tier: frontend +spec: + containers: + - name: hello2 + image: nginx:1.8.0 diff --git a/.vuepress/public/statics/learning/replicationcontroller/replication.yaml b/.vuepress/public/statics/learning/replicationcontroller/replication.yaml new file mode 100644 index 0000000..6eff0b9 --- /dev/null +++ b/.vuepress/public/statics/learning/replicationcontroller/replication.yaml @@ -0,0 +1,19 @@ +apiVersion: v1 +kind: ReplicationController +metadata: + name: nginx +spec: + replicas: 3 + selector: + app: nginx + template: + metadata: + name: nginx + labels: + app: nginx + spec: + containers: + - name: nginx + image: nginx + ports: + - containerPort: 80 diff --git a/install/install-node-port-range.md b/install/install-node-port-range.md new file mode 100644 index 0000000..2538c73 --- /dev/null +++ b/install/install-node-port-range.md @@ -0,0 +1,139 @@ +--- +vssueId: 15 +# layout: StepLayout +description: Kubernete安装后_默认NodePort的范围是30000-32767_某些情况下_因为您所在公司的网络策略限制_您可能需要修改 NodePort的端口范围_本文描述了具体的操作方法 +meta: + - name: keywords + content: Kubernetes安装,K8S安装,kubeadm,NodePort范围 +--- + +# 修改NodePort的范围 + + + +在 Kubernetes 集群中,[NodePort](/learning/k8s-intermediate/service/service-types.html#nodeport) 默认范围是 30000-32767,某些情况下,因为您所在公司的网络策略限制,您可能需要修改 NodePort 的端口范围,本文描述了具体的操作方法。 + + + +### 修改kube-apiserver.yaml + +使用 kubeadm 安装 K8S 集群的情况下,您的 Master 节点上会有一个文件 `/etc/kubernetes/manifests/kube-apiserver.yaml`,修改此文件,向其中添加 `--service-node-port-range=20000-22767` (请使用您自己需要的端口范围),如下所示: + +``` yaml {38} +apiVersion: v1 +kind: Pod +metadata: + creationTimestamp: null + labels: + component: kube-apiserver + tier: control-plane + name: kube-apiserver + namespace: kube-system +spec: + containers: + - command: + - kube-apiserver + - --advertise-address=172.17.216.80 + - --allow-privileged=true + - --authorization-mode=Node,RBAC + - --client-ca-file=/etc/kubernetes/pki/ca.crt + - --enable-admission-plugins=NodeRestriction + - --enable-bootstrap-token-auth=true + - --etcd-cafile=/etc/kubernetes/pki/etcd/ca.crt + - --etcd-certfile=/etc/kubernetes/pki/apiserver-etcd-client.crt + - --etcd-keyfile=/etc/kubernetes/pki/apiserver-etcd-client.key + - --etcd-servers=https://127.0.0.1:2379 + - --insecure-port=0 + - --kubelet-client-certificate=/etc/kubernetes/pki/apiserver-kubelet-client.crt + - --kubelet-client-key=/etc/kubernetes/pki/apiserver-kubelet-client.key + - --kubelet-preferred-address-types=InternalIP,ExternalIP,Hostname + - --proxy-client-cert-file=/etc/kubernetes/pki/front-proxy-client.crt + - --proxy-client-key-file=/etc/kubernetes/pki/front-proxy-client.key + - --requestheader-allowed-names=front-proxy-client + - --requestheader-client-ca-file=/etc/kubernetes/pki/front-proxy-ca.crt + - --requestheader-extra-headers-prefix=X-Remote-Extra- + - --requestheader-group-headers=X-Remote-Group + - --requestheader-username-headers=X-Remote-User + - --secure-port=6443 + - --service-account-key-file=/etc/kubernetes/pki/sa.pub + - --service-cluster-ip-range=10.96.0.0/12 + - --service-node-port-range=20000-22767 + - --tls-cert-file=/etc/kubernetes/pki/apiserver.crt + - --tls-private-key-file=/etc/kubernetes/pki/apiserver.key + image: registry.cn-hangzhou.aliyuncs.com/google_containers/kube-apiserver:v1.16.0 + imagePullPolicy: IfNotPresent + livenessProbe: + failureThreshold: 8 + httpGet: + host: 172.17.216.80 + path: /healthz + port: 6443 + scheme: HTTPS + initialDelaySeconds: 15 + timeoutSeconds: 15 + ... +``` + + +### 重启apiserver + +执行以下命令,重启 apiserver +``` sh +# 获得 apiserver 的 pod 名字 +export apiserver_pods=$(kubectl get pods --selector=component=kube-apiserver -n kube-system --output=jsonpath={.items..metadata.name}) +# 删除 apiserver 的 pod +kubectl delete pod $apiserver_pods -n kube-system +``` + +### 验证结果 + +执行以下命令,验证修改是否生效: +``` sh +kubectl describe pod $apiserver_pods -n kube-system +``` +输出结果如下所示:(此时,我们可以看到,apiserver 已经使用新的命令行参数启动) +``` {29} +... + Host Port: + Command: + kube-apiserver + --advertise-address=172.17.216.80 + --allow-privileged=true + --authorization-mode=Node,RBAC + --client-ca-file=/etc/kubernetes/pki/ca.crt + --enable-admission-plugins=NodeRestriction + --enable-bootstrap-token-auth=true + --etcd-cafile=/etc/kubernetes/pki/etcd/ca.crt + --etcd-certfile=/etc/kubernetes/pki/apiserver-etcd-client.crt + --etcd-keyfile=/etc/kubernetes/pki/apiserver-etcd-client.key + --etcd-servers=https://127.0.0.1:2379 + --insecure-port=0 + --kubelet-client-certificate=/etc/kubernetes/pki/apiserver-kubelet-client.crt + --kubelet-client-key=/etc/kubernetes/pki/apiserver-kubelet-client.key + --kubelet-preferred-address-types=InternalIP,ExternalIP,Hostname + --proxy-client-cert-file=/etc/kubernetes/pki/front-proxy-client.crt + --proxy-client-key-file=/etc/kubernetes/pki/front-proxy-client.key + --requestheader-allowed-names=front-proxy-client + --requestheader-client-ca-file=/etc/kubernetes/pki/front-proxy-ca.crt + --requestheader-extra-headers-prefix=X-Remote-Extra- + --requestheader-group-headers=X-Remote-Group + --requestheader-username-headers=X-Remote-User + --secure-port=6443 + --service-account-key-file=/etc/kubernetes/pki/sa.pub + --service-cluster-ip-range=10.96.0.0/12 + --service-node-port-range=20000-22767 + --tls-cert-file=/etc/kubernetes/pki/apiserver.crt + --tls-private-key-file=/etc/kubernetes/pki/apiserver.key + State: Running + Started: Mon, 11 Nov 2019 21:31:39 +0800 + Ready: True + Restart Count: 0 + Requests: + cpu: 250m + ... +``` + +::: tip 注意 +* 对于已经创建的NodePort类型的Service,您需要删除重新创建 +* 如果您的集群有多个 Master 节点,您需要逐个修改每个节点上的 `/etc/kubernetes/manifests/kube-apiserver.yaml` 文件,并重启 apiserver +::: diff --git a/learning/README.md b/learning/README.md index 92f3572..1721f94 100644 --- a/learning/README.md +++ b/learning/README.md @@ -12,17 +12,17 @@ meta: # Kubernetes 教程
    -
    - + -
    + -
    +
    @@ -122,9 +122,13 @@ meta: * [容器组 - 生命周期](/learning/k8s-intermediate/workload/pod-lifecycle.html) * [容器组 - 初始化容器](/learning/k8s-intermediate/workload/init-container.html) * [控制器 - 概述](/learning/k8s-intermediate/workload/workload.html) + * [控制器 - ReplicaSet](/learning/k8s-intermediate/workload/wl-replicaset/) + * [控制器 - ReplicationController](/learning/k8s-intermediate/workload/wl-replication-con/) * [控制器 - Deployment](/learning/k8s-intermediate/workload/wl-deployment/) * [控制器 - StatefulSet](/learning/k8s-intermediate/workload/wl-statefulset/) * [控制器 - DaemonSet](/learning/k8s-intermediate/workload/wl-daemonset/) + * [控制器 - 垃圾回收](/learning/k8s-intermediate/workload/gc) + * [控制器 - TTL](/learning/k8s-intermediate/workload/wl-ttl/) * [控制器 - Job](/learning/k8s-intermediate/workload/wl-job/) * [控制器 - CronJob](/learning/k8s-intermediate/workload/wl-cronjob/) * 服务发现、负载均衡、网络 diff --git a/learning/k8s-intermediate/service/service-types.md b/learning/k8s-intermediate/service/service-types.md index 3978606..dfd05b7 100644 --- a/learning/k8s-intermediate/service/service-types.md +++ b/learning/k8s-intermediate/service/service-types.md @@ -45,7 +45,7 @@ ClusterIP 是 ServiceType 的默认值。在 [Iptables 代理模式](service-det ## NodePort -对于 `NodePort` 类型的 Service,Kubernetes 为其分配一个节点端口(对于同一 Service,在每个节点上的节点端口都相同),该端口的范围在初始化 apiserver 时可通过参数 `--service-node-port-range` 指定(默认是:30000-32767)。节点将该端口上的网络请求转发到对应的 Service 上。可通过 Service 的 `.spec.ports[*].nodePort` 字段查看该 Service 分配到的节点端口号。 +对于 `NodePort` 类型的 Service,Kubernetes 为其分配一个节点端口(对于同一 Service,在每个节点上的节点端口都相同),该端口的范围在初始化 apiserver 时可通过参数 `--service-node-port-range` 指定(默认是:30000-32767),参考 [修改NodePort的范围](/install/install-node-port-range.html)。节点将该端口上的网络请求转发到对应的 Service 上。可通过 Service 的 `.spec.ports[*].nodePort` 字段查看该 Service 分配到的节点端口号。 在启动 kube-proxy 时使用参数 `--nodeport-address` 可指定阶段端口可以绑定的 IP 地址段。该参数接收以逗号分隔的 CIDR 作为参数值(例如:10.0.0.0/8,192.0.2.0/25),kube-proxy 将查找本机符合该 CIDR 的 IP 地址,并将节点端口绑定到符合的 IP 地址上。 diff --git a/learning/k8s-intermediate/workload/wl-replicaset/index.md b/learning/k8s-intermediate/workload/wl-replicaset/index.md new file mode 100644 index 0000000..e5bab99 --- /dev/null +++ b/learning/k8s-intermediate/workload/wl-replicaset/index.md @@ -0,0 +1,316 @@ +--- +vssueId: 157 +layout: LearningLayout +description: Kubernetes中_ReplicaSet用来维护一个数量稳定的Pod副本集合_可以保证某种定义一样的Pod始终有指定数量的副本数在运行 +meta: + - name: keywords + content: Kubernetes教程,K8S教程,ReplicaSet +--- + +# 控制器 - ReplicaSet + + + +Kubernetes 中,ReplicaSet 用来维护一个数量稳定的 Pod 副本集合,可以保证某种定义一样的 Pod 始终有指定数量的副本数在运行。 + +[[TOC]] + + + +## ReplicaSet的工作方式 + +ReplicaSet的定义中,包含: +* `selector`: 用于指定哪些 Pod 属于该 ReplicaSet 的管辖范围 +* `replicas`: 副本数,用于指定该 ReplicaSet 应该维持多少个 Pod 副本 +* `template`: Pod模板,在 ReplicaSet 使用 Pod 模板的定义创建新的 Pod + +ReplicaSet 控制器将通过创建或删除 Pod,以使得当前 Pod 数量达到 `replicas` 指定的期望值。ReplicaSet 创建的 Pod 中,都有一个字段 [metadata.ownerReferences](/learning/k8s-intermediate/workload/gc.html#所有者和从属对象) 用于标识该 Pod 从属于哪一个 ReplicaSet。 + +ReplicaSet 通过 `selector` 字段的定义,识别哪些 Pod 应该由其管理。如果 Pod 没有 ownerReference 字段,或者 ownerReference 字段指向的对象不是一个控制器,且该 Pod 匹配了 ReplicaSet 的 `selector`,则该 Pod 的 ownerReference 将被修改为 该 ReplicaSet 的引用。 + +## 何时使用 ReplicaSet + +ReplicaSet 用来维护一个数量稳定的 Pod 副本集合。Deployment 是一个更高级别的概念,可以管理 ReplicaSet,并提供声明式的更新,以及其他的许多有用的特性。因此,推荐用户总是使用 Deployment,而不是直接使用 ReplicaSet,除非您需要一些自定义的更新应用程序的方式,或者您完全不更新应用。 + +这也意味着,您也许永远不会直接操作 ReplicaSet 对象。但是,对其有一定的理解是有必要的,这样您才能更好的理解和使用 Deployment。 + +## Example + +<<< @/.vuepress/public/statics/learning/replicaset/frontend.yaml + +执行命令以创建该 YAML 对应的 ReplicaSet +``` sh +kubectl apply -f https://kuboard.cn/statics/learning/replicaset/frontend.yaml +``` + +执行命令,查看刚才创建的ReplicaSet: +``` sh +kubectl get rs +``` + +输出结果如下所示: +``` +NAME DESIRED CURRENT READY AGE +frontend 3 3 3 6s +``` + +执行命令,查看刚才创建的RelicaSet的详情: +``` sh +kubectl describe rs/frontend +``` + +输出结果如下所示: + +``` +Name: frontend +Namespace: default +Selector: tier=frontend,tier in (frontend) +Labels: app=guestbook + tier=frontend +Annotations: +Replicas: 3 current / 3 desired +Pods Status: 3 Running / 0 Waiting / 0 Succeeded / 0 Failed +Pod Template: + Labels: app=guestbook + tier=frontend + Containers: + php-redis: + Image: nginx:latest + Port: 80/TCP + Requests: + cpu: 100m + memory: 100Mi + Environment: + GET_HOSTS_FROM: dns + Mounts: + Volumes: +Events: + FirstSeen LastSeen Count From SubobjectPath Type Reason Message + --------- -------- ----- ---- ------------- -------- ------ ------- + 1m 1m 1 {replicaset-controller } Normal SuccessfulCreate Created pod: frontend-qhloh + 1m 1m 1 {replicaset-controller } Normal SuccessfulCreate Created pod: frontend-dnjpy + 1m 1m 1 {replicaset-controller } +``` + +执行命令,查看有哪些 Pod 被创建: +```sh +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 +``` + +执行命令,查看 Pod 的 ownerReference: +```sh +# 替换成你自己的 Pod 名称 +kubectl get pods frontend-9si5l -o yaml +``` + +输出结果如下所示,其中 `metadata.ownerReferences` 字段指向了 ReplicaSet `frontend`: + +``` yaml {10,14,15} +apiVersion: v1 +kind: Pod +metadata: + creationTimestamp: 2019-11-08T17:20:41Z + generateName: frontend- + labels: + tier: frontend + name: frontend-9si5l + namespace: default + ownerReferences: + - apiVersion: extensions/v1beta1 + blockOwnerDeletion: true + controller: true + kind: ReplicaSet + name: frontend + uid: 892a2330-257c-11e9-aecd-025000000001 +... +``` + +## 获取Non-Template Pod + +由于您可以直接创建 Pod,Kubernetes 中强烈建议在您直接创建的 Pod 中,其标签不会与任何一个 ReplicaSet 的标签匹配。原因在于,ReplicaSet 不仅仅只管理通过其 podTemplate(`.spec.template`字段)创建的Pod,ReplicaSet 也可能将不是尤其创建的 Pod 纳入到自己的管理中。 + +假设有两个 Pod,其 YAML 文件如下所示: + +<<< @/.vuepress/public/statics/learning/replicaset/pod-rs.yaml {6,19} + +这些 Pod 没有对应的控制器(或者任何其他对象)作为其 ownerReference,且他们都匹配了 ReplicaSet `frontend` 中的选择器(selector),此时他们将立刻被 ReplicaSet `frontend` 接管。 + +假设您先创建你了上面例子中的 ReplicaSet(其 `replicas` 为 3),此时再执行命令,以创建上面YAML文件中的两个 Pod: +```sh +kubectl apply -f https://kuboard.cn/statics/learning/replicaset/pod-rs.yaml +``` +新建的 Pod 将立刻被该 ReplicaSet 接管,并且立刻被终止,否则 ReplicaSet 中的副本数量将超过 `replicas` 指定的值。 + +执行命令查看 Pod: +``` sh +kubectl get pods +``` + +输出结果显示了新创建的 Pod 要么已经被终止了,要么正在终止过程中: +``` +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 +pod2 0/1 Terminating 0 4s +``` + +::: tip 清理 + +执行后面的命令时,可先清理已经创建的 ReplicaSet 和 Pod + +``` sh +kubectl delete -f https://kuboard.cn/statics/learning/replicaset/frontend.yaml +kubectl delete -f https://kuboard.cn/statics/learning/replicaset/pod-rs.yaml +``` + +::: + +如果您先创建 Pod: +```sh +kubectl apply -f https://kuboard.cn/statics/learning/replicaset/pod-rs.yaml +``` +然后创建 ReplicaSet: +``` sh +kubectl apply -f https://kuboard.cn/statics/learning/replicaset/frontend.yaml +``` +您将看到 ReplicaSet 将接管您手工创建的 Pod,并且按照自己的 podTemplate 只创建一个新的 Pod,以达到 `replicas` 字段中指定的副本数量。此时执行命令查看 Pod: +``` sh +kubectl get pods +``` +输出结果如下: +``` +NAME READY STATUS RESTARTS AGE +frontend-pxj4r 1/1 Running 0 5s +pod1 1/1 Running 0 13s +pod2 1/1 Running 0 13s +``` + +这种情况下,ReplicaSet 包含了多个不一样的 Pod + +## ReplicaSet的定义 + +与其他 Kubernetes 对象一样,ReplicaSet需要的字段有: +* `apiVersion`:apps/v1 +* `kind`:始终为 ReplicaSet +* `metadata` +* `spec`: ReplicaSet 的详细定义 + +### PodTemplate + +`.spec.template` 字段是一个 [Pod Template](/learning/k8s-intermediate/workload/pod.html#pod-template),为必填字段,且其中必须定义 `.spec.template.metadata.labels` 字段。在前面的ReplicaSet例子中,定义了 label 为 `tier: frontend`。请小心该字段不要与其他控制器的 selector 重合,以免这些控制器尝试接管该 Pod。 + +`.spec.template.spec.restartPolicy` 的默认值为 `Always` + +### Pod Selector + +`.spec.selector` 字段为一个 [标签选择器](/learning/k8s-intermediate/obj/labels.html#标签选择器),用于识别可以接管哪些 Pod。在前面的例子中,标签选择器为: +```yaml +matchLabels: + tier: frontend +``` +在 ReplicaSet 中, `.spec.template.metadata.labels` 必须与 `.spec.selector` 匹配,否则将不能成功创建 ReplicaSet。 + +::: tip +如果两个 ReplicaSet 指定了相同的 `.spec.selector` 但是不同的 `.spec.template.metadata.labels` 和不同的 `.spec.tempalte.spec` 字段,两个 ReplicaSet 都将忽略另外一个 ReplicaSet 创建的 Pod +::: + +### Replicas + +`.spec.replicas` 字段用于指定同时运行的 Pod 的副本数。ReplicaSet 将创建或者删除由其管理的 Pod,以便使副本数与该字段指定的值匹配。 + +如果不指定,默认值为 1 + +## 使用 ReplicaSet + +### 删除ReplicaSet及其Pod + +使用 `kubectl delete` 可删除 ReplicaSet, [Garbage Collector](/learning/k8s-intermediate/workload/gc.html) 将自动删除该 ReplicaSet 所有从属的 Pod。 + +如果使用 REST API 或者 `client-go` 代码库调用 apiserver 来删除 ReplicaSet,则必须通过 -d 参数指定 `propagationPolicy` 为 `Background` 或 `Foreground`,例如: + +``` sh +kubectl proxy --port=8080 +curl -X DELETE 'localhost:8080/apis/extensions/v1beta1/namespaces/default/replicasets/frontend' \ +> -d '{"kind":"DeleteOptions","apiVersion":"v1","propagationPolicy":"Foreground"}' \ +> -H "Content-Type: application/json" +``` + +### 只删除ReplicaSet + +使用 `kubectl delete --cascade=false` 命令,可以删除 ReplicaSet,但是仍然保留其 Pod。如果使用 REST API 或者 `client-go` 代码库调用 apiserver 来删除 ReplicaSet,则必须通过 -d 参数指定 `propagationPolicy` 为 `Orphan`,例如: + +```sh +kubectl proxy --port=8080 +curl -X DELETE 'localhost:8080/apis/extensions/v1beta1/namespaces/default/replicasets/frontend' \ +> -d '{"kind":"DeleteOptions","apiVersion":"v1","propagationPolicy":"Orphan"}' \ +> -H "Content-Type: application/json" +``` + +一旦原来的 ReplicaSet 被删除,您可以创建新的 ReplicaSet 作为替代。只要新 ReplicaSet 的 `.spec.selector` 字段与旧 ReplicaSet 的 `.spec.selector` 字段相同,则新的 ReplicaSet 将接管旧 ReplicaSet 遗留下来的 Pod。但是,新的 ReplicaSet 中定义的 `.spec.template` 对遗留下来的 Pod 不会产生任何影响。如果要更新 Pod 的 `.spec.template` 内容,请使用 [Deployment](/learning/k8s-intermediate/workload/wl-deployment/),ReplicaSet 并不直接支持滚动更新。 + +### 将Pod从ReplicaSet中隔离 + +修改 Pod 的标签,可以使 Pod 脱离 ReplicaSet 的管理。这个小技巧在如下场景可能非常有用: +* 将 Pod 从 Service 中移除,以便 Debug 或者做数据恢复 +* 其他 + +通过这种方式从 ReplicaSet 移除了 Pod 之后,ReplicaSet 将立刻自动创建一个新的 Pod 以维持其指定的 `replicas` 副本数。 + +### 伸缩ReplicaSet + +ReplicaSet可以轻易的 scale up 或者 scale down,只需要修改 `.spec.replicas` 字段即可。ReplicaSet 控制器将确保与其标签选择器 `.spec.selector` 匹配的 Pod 数量与 `replicas` 指定的数量相等。 + +### ReplicaSet的自动伸缩 + +可以使用 [Horizontal Pod Autoscalers(HPA)](https://kubernetes.io/docs/tasks/run-application/horizontal-pod-autoscale/) 对 ReplicaSet 执行自动的水平伸缩。下面例子中的 HPA 可以用来对前面例子中的 ReplicaSet 执行自动的水平伸缩: + +<<< @/.vuepress/public/statics/learning/replicaset/hpa-rs.yaml {7,8} + +执行命令可创建该 HPA,该HPA将根据CPU的使用情况对ReplicaSet进行自动伸缩 + +``` sh +kubectl apply -f https://kuboard.cn/statics/learning/replicaset/hpa-rs.yaml +``` + +此外,您也可以使用 `kubectl autoscale` 命令达到相同的效果: + +``` sh +kubectl autoscale rs frontend --max=10 +``` + +## ReplicaSet的替代选项 + +### Deployment(推荐) + +[Deployment](/learning/k8s-intermediate/workload/wl-deployment/) 对象包含 ReplicaSet 作为从属对象,并且可通过声明式、滚动更新的方式更新 ReplicaSet 及其 Pod。尽管 ReplicaSet 可以单独使用,但是 ReplicaSet 现在主要是被用作 Deployment 中负责 Pod 创建、删除、更新的一种手段。当您使用 Deployment 时,您无需关心 由 Deployment 创建的 ReplicaSet,Deployment 将处理所有与之相关的细节。 + +::: tip 推荐 +请始终使用 Deployment,而不是 ReplicaSet +::: + +### Bare Pods + +与用户直接创建的 Pod 不同,ReplicaSet 在 Pod 由于任何原因被删除或终止时(例如,节点故障或者节点升级)将创建新的 Pod 作为其替代。不推荐您直接使用 Pod,即便您的应用程序只需要一个 Pod 副本,请使用 Deployment。 + +### Job + +使用 [Job](/learning/k8s-intermediate/workload/wl-job/) 执行批处理任务 + +### DaemonSet + +当您需要提供机器级别的功能时(例如监控节点、[收集节点上的日志](/learning/k8s-advanced/logs/node.html)),使用 [DaemonSet](/learning/k8s-intermediate/workload/wl-daemonset/)。 + +### ReplicationController + +ReplicaSet 是 [ReplicationController](/learning/k8s-intermediate/workload/wl-replication-con/) 的后继者。它们的用途相同,行为相似,区别在于: +* ReplicationController 不支持 [基于集合的选择器](/learning/k8s-intermediate/obj/labels.html#基于集合的选择方式),因此,推荐使用 ReplicaSet 而不是 ReplicationController diff --git a/learning/k8s-intermediate/workload/wl-replication-con/index.md b/learning/k8s-intermediate/workload/wl-replication-con/index.md new file mode 100644 index 0000000..5f7cbd5 --- /dev/null +++ b/learning/k8s-intermediate/workload/wl-replication-con/index.md @@ -0,0 +1,218 @@ +--- +vssueId: 157 +layout: LearningLayout +description: Kubernetes中_ReplicationController确保在任何时候某个Pod的副本数都是指定的数量 +meta: + - name: keywords + content: Kubernetes教程,K8S教程,ReplicaSet +--- + +# 控制器 - ReplicationController + + + +> 参考文档: [ReplicationController](https://kubernetes.io/docs/concepts/workloads/controllers/replicationcontroller/) + +::: tip +推荐使用 [Deployment](/learning/k8s-intermediate/workload/wl-deployment/) +::: + +ReplicationController 确保在任何时候某个 Pod 的副本数都是指定的数量。 + +[[TOC]] + + + +## ReplicationController如何工作 + +如果存在过多的 Pod,RelicationCotroller 将终止多余的 Pod;如果数量不够,则启动新的 Pod。不同于手工创建Pod的做法,当Pod失败、被删除或者终止时,ReplicationController 将立刻自动创建新的 Pod 作为替代。例如,假设您要升级节点的操作系统内核,此时该节点上的 Pod 将被驱逐或者终止,如果 Pod 是通过 ReplicationController 创建的,ReplicationController 将能够自动在其他节点上创建新的Pod,以确保集群中该Pod的副本数保持在指定的数字。 + +ReplicationController 经常被缩写为 `rc`,在 kubectl 命令中也可以使用此缩写,例如 `kubectl get rc` + +## 运行一个ReplicationController的例子 + +下面的 Example YAML文件中,运行了一个 nginx 服务的三个副本: + +<<< @/.vuepress/public/statics/learning/replicationcontroller/replication.yaml + +执行命令创建该 ReplicationController: +``` sh +kubectl apply -f https://kuboard.cn/statics/learning/replicationcontroller/replication.yaml +``` +执行命令检查刚才创建的 ReplicationController 的状态: +``` sh +kubectl describe replicationcontrollers/nginx +``` +输出结果如下所示: +``` {7} +Name: nginx +Namespace: default +Selector: app=nginx +Labels: app=nginx +Annotations: +Replicas: 3 current / 3 desired +Pods Status: 0 Running / 3 Waiting / 0 Succeeded / 0 Failed +Pod Template: + Labels: app=nginx + Containers: + nginx: + Image: nginx + Port: 80/TCP + Environment: + Mounts: + Volumes: +Events: + FirstSeen LastSeen Count From SubobjectPath Type Reason Message + --------- -------- ----- ---- ------------- ---- ------ ------- + 20s 20s 1 {replication-controller } Normal SuccessfulCreate Created pod: nginx-qrm3m + 20s 20s 1 {replication-controller } Normal SuccessfulCreate Created pod: nginx-3ntk0 + 20s 20s 1 {replication-controller } Normal SuccessfulCreate Created pod: nginx-4ok8v +``` +此时,有3个Pod被创建,但是都还未进入 Running 状态,因为正在抓取镜像。稍等一会儿,执行同样的命令,此处的结果将变为: +``` +Pods Status: 3 Running / 0 Waiting / 0 Succeeded / 0 Failed +``` +下面的命令可以获取 ReplicationController 的 Pod 列表,并存入到环境变量: +``` sh +pods=$(kubectl get pods --selector=app=nginx --output=jsonpath={.items..metadata.name}) +echo $pods +``` +输出结果如下所示: +``` +nginx-3ntk0 nginx-4ok8v nginx-qrm3m +``` +此命令中,使用了与 ReplicationController 中相同的 label selector。 + +## ReplicationController的定义 + +与其他 Kubernetes 对象一样,ReplicationController 需要以下字段: +* `apiVersion` +* `kind` +* `metadata` + +ReplicationController 还需要 `.spec` 字段 + + +### PodTemplate + +`.spec.template` 字段是一个 [Pod Template](/learning/k8s-intermediate/workload/pod.html#pod-template),为必填字段,且其中必须定义 `.spec.template.metadata.labels` 字段。请小心该字段不要与其他控制器的 selector 重合,以免这些控制器尝试接管该 Pod。 + +`.spec.template.spec.restartPolicy` 的默认值为 `Always` + +### Pod Selector + +`.spec.selector` 字段为一个 [标签选择器](/learning/k8s-intermediate/obj/labels.html#标签选择器),用于识别可以接管哪些 Pod。 + +在 ReplicationController 中, `.spec.template.metadata.labels` 必须与 `.spec.selector` 匹配,否则将不能成功创建 ReplicationController。 + +同时,您也要避免通过其他方式创建的 Pod(例如,手工创建、使用另外一个 ReplicationController 创建、或者使用其他控制器如Job等创建)的标签与 ReplicationController 的标签选择器匹配。如果发生这种情况,ReplicationController 将认为这个 Pod 是由它创建的。Kubernetes并不能阻止你进行这种明显错误的操作。如果确实发生了这种情况,您需要手工删除相关的控制器和Pod。 + +### Replicas + +`.spec.replicas` 字段用于指定同时运行的 Pod 的副本数。ReplicaSet 将创建或者删除由其管理的 Pod,以便使副本数与该字段指定的值匹配。 + +如果不指定,默认值为 1 + +## 使用ReplicationController + +### 删除ReplicationController及其Pod + +使用 `kubectl delete` 命令可以删除 ReplicationController 及其 Pod。kubectl 会先将 ReplicationController 伸缩到 0 个副本,待其删除了所有的 Pod 之后,再删除 ReplicationController 对象。如果这个命令中断了,可以重新执行。 + +当使用 REST API 或者 go 语言客户端代码库时,您需要执行如下步骤: +* 伸缩 ReplicationController 的副本数为 0 +* 等待 Pod 被删除 +* 删除 ReplicationController + +### 仅删除ReplicationController + +您可以只删除 ReplicationController,而保留其创建的 Pod,只需要在 kubectl delete 命令中指定选项 --cascade=false,如 +```sh +kubectl delete --cascade=false rc nginx +``` + +当使用 REST API 或者 go 语言客户端代码库时,只需要直接删除 ReplicationController 即可。 + +删除原有的 ReplicationController 之后,您可以在创建新的 ReplicationController 作为替代。只要新 ReplicationController 的 `.spec.selector` 字段与之前相同,则新的 ReplicationController 将接管原 ReplicationController 创建的 Pod。但是,此时原 ReplicationController 已经创建的 Pod 的模板将保持不变。如果需要更新所有 Pod 的模板,请参考 [滚动更新](#滚动更新) + +### 将Pod从ReplicationController中隔离 + +通过修改 Pod 的标签,可以将其从 ReplicationController 的管理列表中移除。这个小技巧在如下场景可能非常有用: +* 将 Pod 从 Service 中移除,以便 Debug 或者做数据恢复 +* 其他 + +通过这种方式从 ReplicationController 移除了 Pod 之后,ReplicationController 将立刻自动创建一个新的 Pod 以维持其指定的 `replicas` 副本数。 + +## 使用模式 + +### Rescheduling + +不管您是想要保持 1 个 Pod 副本,还是由 1000 个 Pod 副本需要运行,ReplicationController 将确保指定的数量的 Pod 副本一直存在,即使是在节点故障、或者 Pod 被人为删除的情况下。 + +### Scaling + +ReplicationController 使得水平伸缩这件事情变得非常简单,只需要修改 `replicas` 字段即可。可以手工修改该字段,也可以通过一个自动化的控制器修改。 + +### 滚动更新 + +ReplicationController 可以用逐个替换 Pod 的方式来滚动更新某个服务,具体的做法是: +* 创建一个新的 ReplicationController 其副本数为 1 +* 逐个跟新 Pod + * 将旧的 ReplicationController `replicas` -1 + * 将新的 ReplicationController `replicas` +1 + * 直到旧的 ReplicationController `replicas` 为 0 +* 删除旧的 ReplicationController + +理想情况下,滚动更新控制器应该考虑应用程序是否就绪,且确保任何时刻都有足够数量的 Pod 是可用的。 + +滚动更新过程中的两个 ReplicationController 在创建 Pod 时,需要使用至少一个不同的标签(例如Pod中主要容器的镜像的 Tag)。 + +ReplicationController 的滚动更新可以通过 [kubectl rolling-update](https://kubernetes.io/docs/reference/generated/kubectl/kubectl-commands#rolling-update) 命令实现,具体使用方法可参考 [Perform Rolling Update Using a Replication Controller](https://kubernetes.io/docs/tasks/run-application/rolling-update-replication-controller/) + +### 多版本(multiple release tracks) + +在滚动更新的过程中,应用程序实际会运行多个版本。实际上,在一个更长的时间段内,也经常会运行同一个应用程序的不同版本(release track),通过标签来区分。 + +例如,Service 可能会选中所有带 `tier in (frontend), environment in (prod)` 标签的 Pod 作为其后端 Pod。此时,假设您有 10 个 Pod 副本为此 Service 服务。您也许想要通过金丝雀发布的方式发布该组件,此时可以: +* 设置主要 ReplicationController 的 `replicas` 为 9,且标签为 `tier=frontend, environment=prod, track=stable` +* 另一个 ReplicationController 的 `replicas` 为 1,作为金丝雀测试用途,标签为 `tier=frontend, environment=prod, track=canary` + +在这种情况下,Service将覆盖金丝雀 Pod 以及非金丝雀 Pod。同时,您可以通过两个 ReplicationController 将不同的 Pod 区分开,监控金丝雀 Pod 的运行效果,验证测试结果等。 + +### 同Service一起使用ReplicationController + +一个 Service 可以对应多个 ReplicationController,例如,一部分流量进入旧的版本,一部分流量进入新的版本。 + +ReplicationController 不会自己终止,但是,其生命周期通常比 Service 要短: +* Service 可以映射到由不同 ReplicationController 创建的 Pod 上 +* Service 的整个生命周期过程中,通常会有多个 ReplicationController 被创建或者销毁(例如,对 Service 的 Pod 执行滚动更新) + +ReplicationController 对 Service 以及 Service 的客户端来说,都是透明不可见的。 + +## 为Replication编写程序 + +ReplicationController 创建的 Pod 应该都是可替代的,且语义上是完全相同的,尽管其配置在不同的时间可能存在差异。ReplicationController 非常适用于无状态应用的管理,也可以用来维护主节点选举(master-elected)、分片的(sharded)、工作节点池(worker-pool)类型的应用。此类应用程序应该 使用动态负载分配的机制(dynamic work assignment mechanism),例如 [RabbitMQ work queues](https://www.rabbitmq.com/tutorials/tutorial-two-python.html),而不是为每一个 Pod 做静态的一次性的配置。 + +任何对 Pod 定义的修改都应该由另一个控制器或者脚本程序执行,而不是由 ReplicationController 自己执行,例如自动调整 Pod 的资源使用(cpu/memory等), + +## 替代选择 + +### ReplicaSet + +`ReplicaSet` 是 ReplicationController 的替代品,请在任何情况下使用 ReplicaSet,而不是 ReplicationController。ReplicaSet 主要是用作 [Deployment](/learning/k8s-intermediate/workload/wl-deployment/) 中创建、删除、更新 Pod 的手段。同时,我们也推荐始终使用 Deployment 而不是 ReplicaSet,除非您需要自定义 Deployment 中的某些行为。 + +### Deployment 推荐 + +[Deployment](/learning/k8s-intermediate/workload/wl-deployment/) 是一个高阶的 API 对象,可以更新其管理的 ReplicaSet 和 Pod,是推荐的用法。 + +### Bare Pods + +与用户直接创建的 Pod 不同,ReplicationController 在 Pod 由于任何原因被删除或终止时(例如,节点故障或者节点升级)将创建新的 Pod 作为其替代。不推荐您直接使用 Pod,即便您的应用程序只需要一个 Pod 副本,请使用 Deployment。 + +### Job + +使用 [Job](/learning/k8s-intermediate/workload/wl-job/) 执行批处理任务 + +### DaemonSet + +当您需要提供机器级别的功能时(例如监控节点、[收集节点上的日志](/learning/k8s-advanced/logs/node.html)),使用 [DaemonSet](/learning/k8s-intermediate/workload/wl-daemonset/)。