技术

mosn有的没的 负载均衡泛谈 《Mysql实战45讲》笔记 单元测试的新解读 《Redis核心技术与实现》笔记 《Prometheus监控实战》笔记 Prometheus 告警学习 calico源码分析 对容器云平台的理解 Prometheus 源码分析 并发的成本 基础设施优化 hashicorp raft源码学习 docker 架构 mosn细节 与微服务框架整合 Java动态代理 编程范式 并发通信模型 《网络是怎样连接的》笔记 go细节 codereview mat使用 jvm 线程实现 go打包机制 go interface及反射 如何学习Kubernetes 《编译原理之美》笔记——后端部分 《编译原理之美》笔记——前端部分 Pilot MCP协议分析 go gc 内存管理玩法汇总 软件机制 istio流量管理 Pilot源码分析 golang io 学习Spring mosn源码浅析 MOSN简介 《datacenter as a computer》笔记 学习JVM Tomcat源码分析 Linux可观测性 学习存储 学计算 Gotty源码分析 kubernetes operator kaggle泰坦尼克问题实践 kubernetes自动扩容缩容 神经网络模型优化 直觉上理解机器学习 knative入门 如何学习机器学习 神经网络系列笔记 TIDB源码分析 《阿里巴巴云原生实践15讲》笔记 Alibaba Java诊断工具Arthas TIDB存储——TIKV 《Apache Kafka源码分析》——简介 netty中的线程池 guava cache 源码分析 Springboot 启动过程分析 Spring 创建Bean的年代变迁 Linux内存管理 自定义CNI IPAM 副本一致性 spring redis 源码分析 kafka实践 spring kafka 源码分析 Linux进程调度 让kafka支持优先级队列 Codis源码分析 Redis源码分析 C语言学习 《趣谈Linux操作系统》笔记 docker和k8s安全机制 jvm crash分析 Prometheus 学习 容器日志采集 Kubernetes 控制器模型 Kubernetes监控 容器狂占cpu怎么办? Kubernetes资源调度——scheduler 时序性数据库介绍及对比 influxdb入门 maven的基本概念 《Apache Kafka源码分析》——server Kubernetes objects 源码分析体会 《数据结构与算法之美》——算法新解 Kubernetes源码分析——controller mananger Kubernetes源码分析——apiserver Kubernetes源码分析——kubelet Kubernetes介绍 ansible学习 Kubernetes源码分析——从kubectl开始 jib源码分析之Step实现 jib源码分析之细节 线程排队 跨主机容器通信 jib源码分析及应用 为容器选择一个合适的entrypoint kubernetes yaml配置 《持续交付36讲》笔记 mybatis学习 程序猿应该知道的 无锁数据结构和算法 CNI——容器网络是如何打通的 为什么很多业务程序猿觉得数据结构和算法没用? 串一串一致性协议 当我在说PaaS时,我在说什么 《数据结构与算法之美》——数据结构笔记 PouchContainer技术分享体会 harbor学习 用groovy 来动态化你的代码 精简代码的利器——lombok 学习 《深入剖析kubernetes》笔记 编程语言的动态性 rxjava3——背压 rxjava2——线程切换 spring cloud 初识 《深入拆解java 虚拟机》笔记 《how tomcat works》笔记 hystrix 学习 rxjava1——概念 Redis 学习 TIDB 学习 分布式计算系统的那些套路 Storm 学习 AQS1——论文学习 Unsafe Spark Stream 学习 linux vfs轮廓 《自己动手写docker》笔记 java8 实践 中本聪比特币白皮书 细读 区块链泛谈 比特币 大杂烩 总纲——如何学习分布式系统 hbase 泛谈 forkjoin 泛谈 看不见摸不着的cdn是啥 《jdk8 in action》笔记 程序猿视角看网络 bgp初识 calico学习 AQS2——粗略的代码分析 我们能用反射做什么 web 跨域问题 《clean code》笔记 硬件对软件设计的影响 《Elasticsearch权威指南》笔记 mockito简介及源码分析 2017软件开发小结—— 从做功能到做系统 《Apache Kafka源码分析》——clients dns隐藏的一个坑 《mysql技术内幕》笔记2 《mysql技术内幕》笔记1 log4j学习 为什么netty比较难懂? 回溯法 apollo client源码分析及看待面向对象设计 学习并发 docker运行java项目的常见问题 Scala的一些梗 OpenTSDB 入门 spring事务小结 事务一致性 javascript应用在哪里 《netty in action》读书笔记 netty对http2协议的解析 ssl证书是什么东西 http那些事 苹果APNs推送框架pushy apple 推送那些事儿 编写java框架的几大利器 java内存模型 java exception Linux IO学习 netty内存管理 测试环境docker化实践 netty在框架中的使用套路 Nginx简单使用 《Linux内核设计的艺术》小结 Go并发机制及语言层工具 Linux网络源代码学习——数据包的发送与接收 《docker源码分析》小结 docker中涉及到的一些linux知识 hystrix学习 Linux网络源代码学习——整体介绍 zookeeper三重奏 数据库的一些知识 Spark 泛谈 链式处理的那些套路 netty回顾 Thrift基本原理与实践(二) Thrift基本原理与实践(一) 回调 异步执行抽象——Executor与Future Docker0.1.0源码分析 java gc Jedis源码分析 Redis概述 机器学习泛谈 Linux网络命令操作 JTA与TCC 换个角度看待设计模式 Scala初识 向Hadoop学习NIO的使用 以新的角度看数据结构 并发控制相关的硬件与内核支持 systemd 简介 quartz 源码分析 基于docker搭建测试环境(二) spring aop 实现原理简述 自己动手写spring(八) 支持AOP 自己动手写spring(七) 类结构设计调整 分析log日志 自己动手写spring(六) 支持FactoryBean 自己动手写spring(九) 总结 自己动手写spring(五) bean的生命周期管理 自己动手写spring(四) 整合xml与注解方式 自己动手写spring(三) 支持注解方式 自己动手写spring(二) 创建一个bean工厂 自己动手写spring(一) 使用digester varnish 简单使用 关于docker image的那点事儿 基于docker搭建测试环境 分布式配置系统 JVM内存与执行 git spring rmi和thrift maven/ant/gradle使用 再看tcp 缓存系统 java nio的多线程扩展 《Concurrency Models》笔记 回头看Spring IOC IntelliJ IDEA使用 Java泛型 vagrant 使用 Go常用的一些库 Python初学 Goroutine 调度模型 虚拟网络 《程序员的自我修养》小结 VPN(Virtual Private Network) Kubernetes存储 访问Kubernetes上的Service Kubernetes副本管理 Kubernetes pod 组件 Go学习 JVM类加载 硬币和扑克牌问题 LRU实现 virtualbox 使用 ThreadLocal小结 docker快速入门

架构

Scheduler如何给Node打分 Scheduler扩展 controller 组件介绍 openkruise cloneset学习 kubernetes crd 及kubebuilder学习 pv与pvc实现 csi学习 client-go学习 kubelet 组件分析 调度实践 Pod是如何被创建出来的? 《软件设计之美》笔记 mecha 架构学习 Kubernetes events学习及应用 CRI 《推荐系统36式》笔记 资源调度泛谈 系统设计原则 grpc学习 元编程 以应用为中心 istio学习 下一代微服务Service Mesh 《实现领域驱动设计》笔记 serverless 泛谈 《架构整洁之道》笔记 处理复杂性 那些年追过的并发 服务器端编程 网络通信协议 《聊聊架构》 书评的笔记 如何学习架构 《反应式设计模式》笔记 项目的演化特点 反应式架构摸索 函数式编程的设计模式 服务化 ddd反模式——CRUD的败笔 研发效能平台 重新看面向对象设计 业务系统设计的一些体会 函数式编程 《左耳听风》笔记 业务程序猿眼中的微服务管理 DDD实践——CQRS 项目隔离——案例研究 《编程的本质》笔记 系统故障排查汇总及教训 平台支持类系统的几个点 代码腾挪的艺术 abtest 系统设计汇总 《从0开始学架构》笔记 初级权限系统设计 领域驱动理念入门 现有上传协议分析 移动网络下的文件上传要注意的几个问题 推送系统的几个基本问题 用户登陆 做配置中心要想好的几个基本问题 不同层面的异步 分层那些事儿 性能问题分析 当我在说模板引擎的时候,我在说什么 用户认证问题 资源的分配与回收——池 消息/任务队列

标签


Kubernetes副本管理

2015年03月03日

简介

本文主要来自对https://cloud.google.com/container-engine/docs的摘抄,有删减。

本文主要讲了replication controller(部分地方简称RC) 尤其要注意 replication controller 和 Kubernetes 控制器模型 不是一个范畴的事情。

2018.11.18 补充,内容来自极客时间 《深入剖析Kubernetes》

What is Kubernetes replication for?

Kubernetes Replication Controller, Replica Set and Deployments: Understanding replication options

Typically you would want to replicate your containers (and thereby your applications) for several reasons, including: Reliability、Load balancing、Scaling。也就是说,应用不是启动一个实例就是完事了。如果应用有多个实例,那么弄几个实例,如何更新所有实例。然后随着k8s的演化,先是Replication Controller、然后 ReplicaSets 最后Deployment

  1. The Replication Controller is the original form of replication in Kubernetes. It’s being replaced by Replica Sets.
  2. The major difference is that the rolling-update command works with Replication Controllers, but won’t work with a Replica Set.This is because Replica Sets are meant to be used as the backend for Deployments.
  3. Deployments are intended to replace Replication Controllers. They provide the same replication functions (through Replica Sets) and also the ability to rollout changes and roll them back if necessary.

deployment

《深入剖析Kubernetes》 经典PaaS的记忆:作业副本与水平扩展 小节 未完毕

有了Replication Controller 为什么还整一个 Deployment?因为后者是声明式的。

Replication Controller VS Deployment in Kubernetes

Deployments are a newer and higher level concept than Replication Controllers. They manage the deployment of Replica Sets (also a newer concept, but pretty much equivalent to Replication Controllers), and allow for easy updating of a Replica Set as well as the ability to roll back to a previous deployment.Previously this would have to be done with kubectl rolling-update which was not declarative and did not provide the rollback features.

Deployments A Deployment controller provides declarative updates for Pods and ReplicaSets.You describe a desired state in a Deployment object, and the Deployment controller changes the actual state to the desired state at a controlled rate.

kubernetes yaml配置Every Kubernetes object includes two nested object fields that govern the object’s configuration: the object spec and the object status. 每个kubernetes object 都包括两个部分object spec 和 object status. Deployment 只是在 ReplicaSet 的基础上,添加了 UP-TO-DATE 这个跟版本有关的状态字段(也就是说 spec 部分没改?)。

我们对多个实例的应用(而不是单个实例)有以下操作:

  Deployment controller逻辑 备注
水平扩展/收缩 修改所控制的 ReplicaSet 的 Pod 副本个数 只更改数量,镜像不变
滚动更新/回滚 见下图,逐步减少v1 ReplicaSet 副本数,增加v2 ReplicaSet 的副本数 镜像改变,每次改变算一个“版本”

Kubernetes object 控制器逻辑 备注
Deployment 控制 ReplicaSet 的数目,以及每个 ReplicaSet 的属性 Deployment 实际上是一个两层控制器
ReplicaSet 保证系统中 Pod 的个数永远等于指定的个数(比如,3 个) 一个应用的版本,对应的正是一个 ReplicaSet

What is a replication controller?(逐步弃用)

A replication controller ensures that a specified number of pod “replicas” are running at any one time. If there are too many, the replication controller kills some pods. If there are too few, it starts more. As opposed to just creating singleton pods or even creating pods in bulk, a replication controller replaces pods that are deleted or terminated for any reason, such as in the case of node failure. For this reason, we recommend that you use a replication controller even if your application requires only a single pod.(将Pod维持在一个确定的数量)

A replicationController is only appropriate for pods with RestartPolicy = Always.

How does a replication controller work?

replication controller中的几个概念(与replication controller config file中都有对应),RC与pod之间的关系。

Pod template

A replication controller creates new pods from a template.

Rather than specifying the current desired state of all replicas, pod templates are like cookie cutters(饼干模型切割刀). Once a cookie(饼干) has been cut, the cookie has no relationship to the cutter. Subsequent changes to the template or even a switch to a new template has no direct effect on the pods already created.

Labels

The population of pods that a replication controller monitors is defined with a label selector(A key:value pair), which creates a loosely coupled relationship between the controller and the pods controlled.(replication controller有一个label,一个replication controller监控的所有pod(controller’s target set)也都包含同一个label,两者以此建立联系)

So that only one replication controller controls any given pod, ensure that the label selectors of replication controllers do not target overlapping(重叠) sets.

To remove a pod from a replication controller’s target set, change the pod’s label(改变一个pod的label,可以将该pod从controller’s target set中移除). Use this technique to remove pods from service for debugging, data recovery, etc. Pods that are removed in this way will be replaced automatically (assuming that the number of replicas is not also changed).

Similarly, deleting a replication controller does not affect the pods it created. To delete the pods in a replication controller’s target set, set the replication controller’s replicas field to 0. (一旦为pod创建replication controller,再想删除这个pod就要修改replication controller的replicas字段了)

Common usage patterns(应用场景)

Rescheduling

Whether you have 1 pod you want to keep running, or 1,000, a replication controller will ensure that the specified number of pods exists, even in the event of node failure or pod termination (e.g., due to an action by another control agent).

Scaling

Replication controllers make it easy to scale the number of replicas up or down, either manually or by an auto-scaling control agent. Scaling is accomplished by updating the replicas field of the replication controller’s configuration file. (很轻松的改变pod的个数)

Rolling updates

Replication controllers are designed to facilitate(促进,帮助,使容易) rolling updates to a service by replacing pods one by one.

The recommended approach is:

  • Create a new replication controller with 1 replica.
  • Resize the new (+1) and old (-1) controllers one by one.
  • Delete the old controller after it reaches 0 replicas.

This predictably updates the set of pods regardless of unexpected failures.

The two replication controllers need to create pods with at least one differentiating label.

(逐步更新pod(现成的命令喔):建立两个Replication controllers,老的replicas减一个,新的replicas加一个,直到老的replicas为0,然后将老的Replication controllers删除)

Multiple release tracks

In addition to running multiple releases of an application while a rolling update is in progress, it’s common to run multiple releases for an extended period of time, or even continuously, using multiple release tracks. The tracks in this case would be differentiated by labels.

For instance, a service might target all pods with tier in (frontend), environment in (prod). Now say you have 10 replicated pods that make up this tier. But you want to be able to ‘canary’ a new version of this component. You could set up a replicationController with replicas set to 9 for the bulk of the replicas, with labels tier=frontend, environment=prod, track=stable, and another replicationController with replicas set to 1 for the canary, with labels tier=frontend, environment=prod, track=canary. Now the service is covering both the canary and non-canary pods. But you can update the replicationControllers separately to test things out, monitor the results, etc.

(多版本长期共存:多个replicationController,不同的track字段值)

Replication Controller Operations

Creating a replication controller

$ kubectl create -f xxx

A successful create request returns the name of the replication controller.

Replication controller configuration file

When creating a replication controller, you must point to a configuration file as the value of the -f flag. The configuration file can be formatted as YAML or as JSON, and supports the following fields:

{
  "id": string,
  "kind": "ReplicationController",
  "apiVersion": "v1beta1",
  "desiredState": {
    "replicas": int,
    "replicaSelector": {string: string},
    "podTemplate": {
      "desiredState": {
         "manifest": {
           manifest object
         }
       },
       "labels": {string: string}
      }},
  "labels": {string: string}
}

Required fields are:

  • id: The name of this replication controller. It must be an RFC1035 compatible value and be unique on this container cluster.
  • kind: Always ReplicationController.
  • apiVersion: Currently v1beta1.
  • desiredState: The configuration for this replication controller. It must contain:

  • replicas: The number of pods to create and maintain.
  • replicaSelector: A key:value pair assigned to the set of pods that this replication controller is responsible for managing. This must match the key:value pair in the podTemplate’s labels field.
  • podTemplate contains the container manifest that defines the container configuration. The manifest is itself contained within a desiredState object.
  • labels: Arbitrary(任意的) key:value pairs used to target or group this replication controller. These labels are not associated with the replicaSelector field or the podTemplate’s labels field. (label标签是为Replication controller分组用的,跟pod没关系)

Manifest

Manifest部分的内容不再赘述(所包含字段,是否必须,以及其意义),可以参见文档

Sample file

{
  "id": "frontend-controller",
  "kind": "ReplicationController",
  "apiVersion": "v1beta1",
  "desiredState": {
    "replicas": 2,
    "replicaSelector": {"name": "frontend"},
    "podTemplate": {
      "desiredState": {
        "manifest": {
          "version": "v1beta1",
          "id": "frontendController",
          "containers": [{
            "name": "php-redis",
            "image": "dockerfile/redis",
            "ports": [{"containerPort": 80, "hostPort": 8000}]
          }]
        }
      },
      "labels": {"name": "frontend"}
    }},
  "labels": {"name": "serving"}
}

Updating replication controller pods

Google Container Engine provides a rolling update mechanism for replication controllers. The rolling update works as follows:

  • A new replication controller is created, according to the specifications in the configuration file.

  • The replica count on the new and old controllers is increased/decreased by one respectively until the desired number of replicas is reached.

If the number of replicas in the new controller is greater than the original, the old controller is first resized to 0 (by increasing/decreasing replicas one at a time), then the new controller is resized to the final desired size.

If the number of replicas in the new controller is less than the original, the controllers are resized until the new one has reached its final desired replica count. Then, the original controller is resized to 0 to delete the remaining pods.

$ kubectl rollingupdate NAME -f FILE \
    [--poll-interval DURATION] \
    [--timeout DURATION] \
    [--update-period DURATION]

Required fields are:

  • NAME: The name of the replication controller to update.
  • -f FILE: A replication controller configuration file, in either JSON or YAML format. The configuration file must specify a new top-level id value and include at least one of the existing replicaSelector key:value pairs.

Optional fields are:

  • –poll-interval DURATION: The time between polling the controller status after update. Valid units are ns (nanoseconds), us or µs (microseconds), ms (milliseconds), s (seconds), m (minutes), or h (hours). Units can be combined (e.g. 1m30s). The default is 3s.
  • –timeout DURATION: The maximum time to wait for the controller to update a pod before exiting. Default is 5m0s. Valid units are as described for –poll-interval above.
  • –update-period DURATION: The time to wait between updating pods. Default is 1m0s. Valid units are as described for –poll-interval above.

If the timeout duration is reached during a rolling update, the operation will fail with some pods belonging to the new replication controller, and some to the original controller. In this case, you should retry using the same command, and rollingupdate will pick up where it left off.

(更新过程有很多时间限制,如果更新失败,下一次更新命令将继续完成上一次遗留的工作)

Resizing a replication controller

$ kubectl --replicas COUNT resize rc NAME \
    [--current-replicas COUNT] \
    [--resource-version VERSION]

Required fields are:

  • NAME: The name of the replication controller to update.
  • –replicas COUNT: The desired number of replicas.

Optional fields are:

  • –current-replicas COUNT: A precondition for current size. If specified, the resize will only take place if the current number of replicas matches this value.
  • –resource-version VERSION: A precondition for resource version. If specified, the resize will only take place if the current resource version matches this value. Resource versions are specified in a resource’s labels field, as a key:value pair with a key of version. For example:

      "labels": {
        "version": "canary"
      }
    

Viewing replication controllers

 $ kubectl get rc

A successful get command returns all replication controllers on the specified cluster in the specified zone (cluster names may be re-used in different zones). For example:

CONTROLLER            CONTAINER(S)   IMAGE(S)           SELECTOR        REPLICAS
frontend-controller   php-redis      dockerfile/redis   name=frontend   2

You can also use kubectl get rc NAME to return information about a specific replication controller.

To view detailed information about a specific replication controller, use the container kubectl describe sub-command:

$ kubectl describe rc NAME A successful describe request returns details about the replication controller:

Name:        frontend-controller
Image(s):    dockerfile/redis
Selector:    name=frontend
Labels:      name=serving
Replicas:    2 current / 2 desired
Pods Status: 2 Running / 0 Waiting / 0 Succeeded / 0 Failed
No events.

Deleting replication controllers

To delete a replication controller as well as the pods that it controls, use the container kubectl stop command:

$ kubectl stop rc NAME

The kubectl stop resizes the controller to zero before deleting it. To delete a replication controller without deleting its pods, use container kubectl delete:

$ kubectl delete rc NAME

A successful delete request returns the name of the deleted resource.