[Cloud native | Learning Kubernetes from scratch] 14. k8s core technology-Controller

This article has been included in the column " Learn k8s from scratch "
Previous article: Container detection and startup strategy of k8spod Click jump

insert image description here

We have learned about Pod earlier. When we define pod resources, we can directly create an autonomous pod of kind: Pod type, but there is a problem. If the pod is deleted, the pod cannot recover itself, and it will be completely It is very dangerous to be deleted online, so today I will explain the pod controller. The so-called controller is able to manage pods, monitor the running status of pods, and automatically restore pods when pods fail. That is to say, it can manage the pod middle layer on our behalf, and help us to ensure that each pod resource is always in the target state we define or we expect. Once the pod resource fails, the controller will try to restart the pod or the container inside. , if there is a problem with restarting all the time, it may be re-distributed or re-arranged based on a certain strategy; if the number of pod replicas is lower than the target number defined by the user, it will also automatically complete; if it is redundant, it will also automatically Terminate the pod resource.

What is Controller

Controller is the object that manages and runs containers on the cluster, Controller is the actual existence, Pod is the virtual machine

The relationship between Pod and Controller

Pod implements application operation and maintenance through Controller, such as elastic scaling, rolling upgrade, etc.

The relationship between the Pod and the Controller is established through the label label, and the Controller is also called the controller workload

Please add image description

Replicaset Controller

Replication Controller, referred to as RC , is the replication controller in K8S. RC is the earliest API object in the K8S cluster to ensure high availability of Pods. Ensure that a specified number of Pod replicas are running in the cluster by monitoring running Pods. The specified number can be multiple or one; less than the specified number, RC will start a new Pod copy; more than the specified number, RC will kill the redundant Pod copy.

Even when the specified number is 1, it is wiser to run Pods through RC than directly, because RC can also use its high availability capabilities to ensure that there is always a Pod running. RC is an earlier technical concept in K8S, and is only suitable for long-term server-type business types, such as controlling Pods to provide highly available web services.

ReplicaSet is referred to as RS, which is the replica set. RS is a new generation of RC, providing the same high-availability, the main difference is that RS has come from behind and can support more types of matching modes. The replica set object is generally not used alone, but is used as the ideal state parameter of the Deployment

Replicaset overview

ReplicaSet is referred to as RS, which is the replica set. RS is a new generation of RC, providing the same high-availability, the main difference is that RS has come from behind and can support more types of matching modes. The replica set object is generally not used alone, but is used as the ideal state parameter of the Deployment. Its main function is to control the pods managed by it, so that the number of pod replicas is always maintained at the preset number. Its main function is to ensure that a certain number of Pods can run normally in the cluster. It will continuously monitor the running status of these Pods, restart Pods when Pods fail, and re-run a new Pod copy when the number of Pods decreases.

It is officially recommended not to use ReplicaSet directly. Instead, use Deployments. Deployments are a more advanced concept than ReplicaSet. It manages ReplicaSet and provides many other useful features. The most important thing is that Deployments support declarative updates, and the benefits of declarative updates are not Lost historical changes. Therefore, the Deployment controller does not directly manage the Pod objects, but the Deployment manages the ReplicaSet, and then the ReplicaSet is responsible for managing the Pod objects.

How Replicaset Works: How Do I Manage Pods?

The core function of Replicaset is to create a specified number of pod replicas on behalf of users, and to ensure that the pod replicas are always in the number that meets the user's expectations.

The Replicaset controller mainly consists of three parts:

1. The number of pod replicas expected by the user: used to define how many pod replicas are managed by this controller

2. Label selector: Select which pods are managed by yourself. If the number of pod copies selected by the label selector is less than the number we specified, the following components are required

3. Pod resource template: What if the number of existing pods in the cluster is not enough for the expected number of copies we defined, and a new pod needs to be created, which requires a pod template. The new pod is created based on the template.

Replicaset resource manifest file writing skills

#查看定义 Replicaset 资源需要的字段有哪些? 
[root@k8smaster ~]# kubectl explain replicaset
KIND:     ReplicaSet
VERSION:  apps/v1

DESCRIPTION:
     ReplicaSet ensures that a specified number of pod replicas are running at
     any given time.

FIELDS:
   apiVersion	<string>		#当前资源使用的 api 版本,跟 VERSION: apps/v1 保持一致 
	
   kind	<string>				#资源类型,跟 KIND: ReplicaSet 保持一致

   metadata	<Object>			#元数据,定义 Replicaset 名字的 

   spec	<Object>				#定义副本数、定义标签选择器、定义 Pod 模板 

   status	<Object>			#状态信息,不能改 

#查看 replicaset 的 spec 字段如何定义? 
[root@k8smaster ~]# kubectl explain rs.spec
KIND:     ReplicaSet
VERSION:  apps/v1

RESOURCE: spec <Object>

DESCRIPTION:
     Spec defines the specification of the desired behavior of the ReplicaSet.
     More info:
     https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status

     ReplicaSetSpec is the specification of a ReplicaSet.

FIELDS:
   minReadySeconds	<integer>
   
   replicas	<integer>				#定义的 pod 副本数,根据我们指定的值创建对应数量的 pod 

   selector	<Object> -required-		#用于匹配 pod 的标签选择器 

   template	<Object>				#定义 Pod 的模板,基于这个模板定义的所有 pod 是一样的 

#查看 replicaset 的 spec.template 字段如何定义? 
#对于 template 而言,其内部定义的就是 pod,pod 模板是一个独立的对象 
[root@k8smaster ~]# kubectl explain rs.spec.template 
KIND:     ReplicaSet
VERSION:  apps/v1

RESOURCE: template <Object>

DESCRIPTION:
     Template is the object that describes the pod that will be created if
     insufficient replicas are detected. More info:
     https://kubernetes.io/docs/concepts/workloads/controllers/replicationcontroller#pod-template

     PodTemplateSpec describes the data a pod should have when created from a
     template

FIELDS:
   metadata	<Object>
   
   spec	<Object>

[root@k8smaster ~]# kubectl explain rs.spec.template.spec 
 
通过上面可以看到,ReplicaSet 资源中有两个 spec 字段。第一个 spec 声明的是 ReplicaSet 定义多少个 Pod 副本(默认将仅部署 1 个 Pod)、匹配 Pod 标签的选择器、创建 pod 的模板。第二个 spec 是spec.template.spec,主要用于 Pod 里的容器属性等配置。 
.spec.template 里的内容是声明 Pod 对象时要定义的各种属性,所以这部分也叫做 PodTemplate(Pod 模板)。还有一个值得注意的地方是:在.spec.selector 中定义的标签选择器必须能够匹配到 spec.template.metadata.labels 里定义的 Pod 标签,否则 Kubernetes 将不允许创建 ReplicaSet。 

3、Replicaset 使用案例:部署 Guestbook 留言板 
[root@k8snode2 ~]# docker pull konradkleine/docker-registry-frontend:v2
[root@k8snode ~]# docker pull konradkleine/docker-registry-frontend:v2
#编写一个 ReplicaSet 资源清单
[root@k8smaster node]# vim replicaset.yaml 
apiVersion: apps/v1
kind: ReplicaSet
metadata:
  name: frontend
  labels:
    app: guestbook
    tier: frontend
spec:
  replicas: 3
  selector:
    matchLabels:
      tier: frontend
  template:
    metadata:
      labels:
        tier: frontend
    spec:
      containers:
      - name: php-redis
        image: konradkleine/docker-registry-frontend:v2
        imagePullPolicy: IfNotPresent
        command: ["/bin/bash","-ce","tail -f /dev/null"]
[root@k8smaster node]# kubectl apply -f replicaset.yaml 
replicaset.apps/frontend created
[root@k8smaster node]# kubectl get rs 
NAME              DESIRED   CURRENT   READY   AGE
frontend          3         3         3       17s
[root@k8smaster node]# kubectl get pods
NAME                    READY   STATUS    RESTARTS   AGE
frontend-6x5gl          1/1     Running   0          28s
frontend-ncgcj          1/1     Running   0          28s
frontend-z74hg          1/1     Running   0          28s
#pod 的名字是由控制器的名字-随机数组成的 如果yaml怕写错可以explain rs 看一下字段或者复制

#资源清单详细说明 
apiVersion: apps/v1 #ReplicaSet 这个控制器属于的核心群组 
kind: ReplicaSet #创建的资源类型 
metadata: 
 name: frontend #控制器的名字 
 labels: 
 app: guestbook 
 tier: frontend 
spec:
 replicas: 3 #管理的 pod 副本数量 
 selector: 
 matchLabels: 
 tier: frontend #管理带有 tier=frontend 标签的 pod 
 template: #定义 pod 的模板 
 metadata: 
 labels: 
 tier: frontend 
#pod 标签,一定要有,这样上面控制器就能找到它要管理的 pod 是哪些了 
 spec: 
 containers: #定义 pod 里运行的容器 
 - name: php-redis #定义容器的名字 
 image:  konradkleine/docker-registry-frontend:v2
 ports: #定义端口 
- name: http #定义容器的名字 
containerPort: 80 #定义容器暴露的端口

Replicaset manages pods: scaling up, scaling down, updating

#Replicaset 实现 pod 的动态扩容 
ReplicaSet 最核心的功能是可以动态扩容和回缩,如果我们觉得两个副本太少了,想要增加,只需要修改配置文件 replicaset.yaml 里的 replicas 的值即可,原来 replicas: 3,现在变成 replicaset: 5,修改之后,执行如下命令更新
[root@k8smaster node]# kubectl apply -f replicaset.yaml 
replicaset.apps/frontend configured
[root@k8smaster node]# kubectl get pods
NAME                    READY   STATUS    RESTARTS   AGE
frontend-6x5gl          1/1     Running   0          61m
frontend-fk5vl          1/1     Running   0          8s
frontend-lvclg          1/1     Running   0          8s
frontend-ncgcj          1/1     Running   0          61m
frontend-z74hg          1/1     Running   0          61m
[root@k8smaster node]# kubectl get rs
NAME              DESIRED   CURRENT   READY   AGE
frontend          5         5         5       61m
 #也可以直接编辑控制器实现扩容 
#这个是我们把请求提交给了 apiserver,实时修改 
[root@k8smaster node]# kubectl edit rs frontend
replicaset.apps/frontend edited
#可以开两个窗口 动态查看
[root@k8smaster node]# kubectl get pods -w

#Replicaset 实现 pod 的动态缩容 
如果我们觉得 5 个 Pod 副本太多了,想要减少,只需要修改配置文件 replicaset.yaml 里的replicas 的值即可,把 replicaset:4 变成 replicas: 3,修改之后,执行如下命令更新
[root@k8smaster node]# kubectl apply -f replicaset.yaml 
[root@k8smaster node]# kubectl get rs
NAME              DESIRED   CURRENT   READY   AGE
frontend          3         3         3       64m
[root@xianchaomaster1 ~]# kubectl get pods 
NAME READY STATUS RESTARTS AGE 
frontend-j6twz 1/1 Running 0 70m 
frontend-lcnq6 1/1 Running 0 70m

#Replicaset 实现 pod 的更新
#修改镜像变成image: nginx,修改之后保存退出 
[root@k8smaster node]# vim replicaset.yaml 
#把里面 command: ["/bin/bash","-ce","tail -f /dev/null"]删除 并且image改成nginx
[root@k8smaster node]# kubectl get rs -o wide
NAME              DESIRED   CURRENT   READY   AGE   CONTAINERS   IMAGES   SELECTOR
frontend          3         3         3       67m   php-redis    nginx    tier=frontend
#上面可以看到镜像变成了 nginx,说明滚动升级成功了 
[root@k8smaster node]# kubectl get pods -o wide
NAME                    READY   STATUS    RESTARTS   AGE   IP            NODE       NOMINATED NODE   READINESS GATES
frontend-6x5gl          1/1     Running   0          68m   10.244.1.11   k8snode2   <none>           <none>
frontend-ncgcj          1/1     Running   0          68m   10.244.2.26   k8snode    <none>           <none>
frontend-z74hg          1/1     Running   0          68m   10.244.1.12   k8snode2   <none>           <none>
#虽然镜像已经更新了,但是原来的 pod 使用的还是之前的镜像,新创建的 pod 才会使用最新的镜像
[root@k8smaster node]# kubectl delete pods frontend-6x5gl			第一个终端删除
pod "frontend-6x5gl" deleted
[root@k8smaster node]# kubectl get pods -w							第二个终端
NAME                    READY   STATUS    RESTARTS   AGE
frontend-6x5gl          1/1     Running   0          71m
frontend-ncgcj          1/1     Running   0          71m
frontend-z74hg          1/1     Running   0          71m
frontend-6x5gl          1/1     Terminating   0          71m
frontend-t8x72          0/1     Pending       0          0s
frontend-t8x72          0/1     Pending       0          0s
frontend-t8x72          0/1     ContainerCreating   0          0s
frontend-t8x72          1/1     Running             0          1s
#重新生成了一个新的 pod:frontend-t8x72
[root@k8smaster node]# curl 10.244.2.30
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
<style>
html {
    
     color-scheme: light dark; }
body {
    
     width: 35em; margin: 0 auto;
font-family: Tahoma, Verdana, Arial, sans-serif; }
</style>
</head>
<body>
<h1>Welcome to nginx!</h1>
<p>If you see this page, the nginx web server is successfully installed and
working. Further configuration is required.</p>

<p>For online documentation and support please refer to
<a href="http://nginx.org/">nginx.org</a>.<br/>
Commercial support is available at
<a href="http://nginx.com/">nginx.com</a>.</p>

<p><em>Thank you for using nginx.</em></p>
</body>
</html>
#新生成的 pod 的镜像已经变成了nginx 的,说明更新完成了 

If the production environment is upgraded, one pod can be deleted, and another pod can be deleted after observing for a period of time, but this requires manual intervention for many times; the actual production environment is generally released in blue and green, there is one rs1, and another rs2 (controller) Controller), by modifying the service label, modifying the service can match the controller of rs2, so that is blue-green release, this also requires our careful deployment planning, we have a controller built on top of rs, called Deployment .

write at the end

It is not easy to create, if you think the content is helpful to you, please give me a three-link follow to support me! If there are any mistakes, please point them out in the comments and I will change them in time!
The series that is currently being updated: learn k8s from scratch.
Thank you for watching. The article is mixed with personal understanding. If there is any error, please contact me and point it out~
insert image description here

Guess you like

Origin blog.csdn.net/qq_45400861/article/details/126403560