8-9:Kubernetes Pod控制器

8-9:Kubernetes Pod控制器 

Pod控制器:

ReplicaSet: 帮助用户管理无状态的pod资源,并确保pod可以精确反应用户所定义的目标数量

主要有三个资源:
1、用户期望的pod副本,即由replicaset管控的pod副本数量
2、标签选择器,即ReplicaSet判断pod归自己管理的依据;
3、pod模板:假如现存的pod数量不够副本中定义的pod数量,就需要根据pod模板去创建新的pod

Deployment:工作在ReplicaSet之上,Deployment不直接控制pod,而是直接控制ReplicaSet从而控制pod;
DaemonSet:用于确保集群中的每一个节点只运行一个特定的pod副本,通常是实现系统级别的后台任务;
                     Deployment和DaemonSet都是无状态的,同时他们必须的守护进程类的,必须持续的运行在后台,
Job:
Cronjob:
StatefulSet: 实现管理有状态应用,且每一个pod副本都是被单独来管理的,拥有者pod自己独有的标识和独有的数据集,如果新的pod副本替代老的pod,需要做很多初始化操作;
                   StatefulSet可能是有数据有持久化存储的

 

ReplicaSet(简称rs)简单示例:
# kubectl explain rs

KIND:     ReplicaSet
VERSION:  apps/v1

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

FIELDS:
   apiVersion    <string>
     APIVersion defines the versioned schema of this representation of an
     object. Servers should convert recognized schemas to the latest internal
     value, and may reject unrecognized values. More info:
     https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources

   kind    <string>
     Kind is a string value representing the REST resource this object
     represents. Servers may infer this from the endpoint the client submits
     requests to. Cannot be updated. In CamelCase. More info:
     https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds

   metadata    <Object>
     If the Labels of a ReplicaSet are empty, they are defaulted to be the same
     as the Pod(s) that the ReplicaSet manages. Standard objects metadata. More
     info:
     https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata

   spec    <Object>
     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

   status    <Object>
     Status is the most recently observed status of the ReplicaSet. This data
     may be out of date by some window of time. Populated by the system.
     Read-only. More info:
     https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status

 

# kubectl explain rs.spec   //查看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>
     Minimum number of seconds for which a newly created pod should be ready
     without any of its container crashing, for it to be considered available.
     Defaults to 0 (pod will be considered available as soon as it is ready)

   replicas    <integer>
     Replicas is the number of desired replicas. This is a pointer to
     distinguish between explicit zero and unspecified. Defaults to 1. More
     info:
     https://kubernetes.io/docs/concepts/workloads/controllers/replicationcontroller/#what-is-a-replicationcontroller

   selector    <Object> -required-
     Selector is a label query over pods that should match the replica count.
     Label keys and values that must match in order to be controlled by this
     replica set. It must match the pod templates labels. More info:
     https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/#label-selectors

   template    <Object>
     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

 

# kubectl explain rs.spec.template    //查看spec中的template,是pod的模板

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:    //下面是定义pod中的metadata和spec
   metadata    <Object> 
     Standard objects metadata. More info:
     https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata

   spec    <Object>
     Specification of the desired behavior of the pod. More info:
     https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status

 

# kubectl explain rs.spec.template.spec   //包含很多字段

8-9:Kubernetes Pod控制器
  1 KIND:     ReplicaSet
  2 VERSION:  apps/v1
  3 
  4 RESOURCE: template <Object>
  5 
  6 DESCRIPTION:
  7      Template is the object that describes the pod that will be created if
  8      insufficient replicas are detected. More info:
  9      https://kubernetes.io/docs/concepts/workloads/controllers/replicationcontroller#pod-template
 10 
 11      PodTemplateSpec describes the data a pod should have when created from a
 12      template
 13 
 14 FIELDS:
 15    metadata    <Object>
 16      Standard objects metadata. More info:
 17      https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata
 18 
 19    spec    <Object>
 20      Specification of the desired behavior of the pod. More info:
 21      https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status
 22 
 23 [root@kmaster manifests]# kubectl explain rs.spec.template.spec
 24 KIND:     ReplicaSet
 25 VERSION:  apps/v1
 26 
 27 RESOURCE: spec <Object>
 28 
 29 DESCRIPTION:
 30      Specification of the desired behavior of the pod. More info:
 31      https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status
 32 
 33      PodSpec is a description of a pod.
 34 
 35 FIELDS:
 36    activeDeadlineSeconds    <integer>
 37      Optional duration in seconds the pod may be active on the node relative to
 38      StartTime before the system will actively try to mark it failed and kill
 39      associated containers. Value must be a positive integer.
 40 
 41    affinity    <Object>
 42      If specified, the pods scheduling constraints
 43 
 44    automountServiceAccountToken    <boolean>
 45      AutomountServiceAccountToken indicates whether a service account token
 46      should be automatically mounted.
 47 
 48    containers    <[]Object> -required-
 49      List of containers belonging to the pod. Containers cannot currently be
 50      added or removed. There must be at least one container in a Pod. Cannot be
 51      updated.
 52 
 53    dnsConfig    <Object>
 54      Specifies the DNS parameters of a pod. Parameters specified here will be
 55      merged to the generated DNS configuration based on DNSPolicy.
 56 
 57    dnsPolicy    <string>
 58      Set DNS policy for the pod. Defaults to "ClusterFirst". Valid values are
 59      ClusterFirstWithHostNet, ClusterFirst, Default or None. DNS
 60      parameters given in DNSConfig will be merged with the policy selected with
 61      DNSPolicy. To have DNS options set along with hostNetwork, you have to
 62      specify DNS policy explicitly to ClusterFirstWithHostNet.
 63 
 64    enableServiceLinks    <boolean>
 65      EnableServiceLinks indicates whether information about services should be
 66      injected into pods environment variables, matching the syntax of Docker
 67      links. Optional: Defaults to true.
 68 
 69    ephemeralContainers    <[]Object>
 70      List of ephemeral containers run in this pod. Ephemeral containers may be
 71      run in an existing pod to perform user-initiated actions such as debugging.
 72      This list cannot be specified when creating a pod, and it cannot be
 73      modified by updating the pod spec. In order to add an ephemeral container
 74      to an existing pod, use the pods ephemeralcontainers subresource. This
 75      field is alpha-level and is only honored by servers that enable the
 76      EphemeralContainers feature.
 77 
 78    hostAliases    <[]Object>
 79      HostAliases is an optional list of hosts and IPs that will be injected into
 80      the pods hosts file if specified. This is only valid for non-hostNetwork
 81      pods.
 82 
 83    hostIPC    <boolean>
 84      Use the hosts ipc namespace. Optional: Default to false.
 85 
 86    hostNetwork    <boolean>
 87      Host networking requested for this pod. Use the hosts network namespace.
 88      If this option is set, the ports that will be used must be specified.
 89      Default to false.
 90 
 91    hostPID    <boolean>
 92      Use the hosts pid namespace. Optional: Default to false.
 93 
 94    hostname    <string>
 95      Specifies the hostname of the Pod If not specified, the pods hostname will
 96      be set to a system-defined value.
 97 
 98    imagePullSecrets    <[]Object>
 99      ImagePullSecrets is an optional list of references to secrets in the same
100      namespace to use for pulling any of the images used by this PodSpec. If
101      specified, these secrets will be passed to individual puller
102      implementations for them to use. For example, in the case of docker, only
103      DockerConfig type secrets are honored. More info:
104      https://kubernetes.io/docs/concepts/containers/images#specifying-imagepullsecrets-on-a-pod
105 
106    initContainers    <[]Object>
107      List of initialization containers belonging to the pod. Init containers are
108      executed in order prior to containers being started. If any init container
109      fails, the pod is considered to have failed and is handled according to its
110      restartPolicy. The name for an init container or normal container must be
111      unique among all containers. Init containers may not have Lifecycle
112      actions, Readiness probes, Liveness probes, or Startup probes. The
113      resourceRequirements of an init container are taken into account during
114      scheduling by finding the highest request/limit for each resource type, and
115      then using the max of of that value or the sum of the normal containers.
116      Limits are applied to init containers in a similar fashion. Init containers
117      cannot currently be added or removed. Cannot be updated. More info:
118      https://kubernetes.io/docs/concepts/workloads/pods/init-containers/
119 
120    nodeName    <string>
121      NodeName is a request to schedule this pod onto a specific node. If it is
122      non-empty, the scheduler simply schedules this pod onto that node, assuming
123      that it fits resource requirements.
124 
125    nodeSelector    <map[string]string>
126      NodeSelector is a selector which must be true for the pod to fit on a node.
127      Selector which must match a nodes labels for the pod to be scheduled on
128      that node. More info:
129      https://kubernetes.io/docs/concepts/configuration/assign-pod-node/
130 
131    overhead    <map[string]string>
132      Overhead represents the resource overhead associated with running a pod for
133      a given RuntimeClass. This field will be autopopulated at admission time by
134      the RuntimeClass admission controller. If the RuntimeClass admission
135      controller is enabled, overhead must not be set in Pod create requests. The
136      RuntimeClass admission controller will reject Pod create requests which
137      have the overhead already set. If RuntimeClass is configured and selected
138      in the PodSpec, Overhead will be set to the value defined in the
139      corresponding RuntimeClass, otherwise it will remain unset and treated as
140      zero. More info:
141      https://git.k8s.io/enhancements/keps/sig-node/20190226-pod-overhead.md This
142      field is alpha-level as of Kubernetes v1.16, and is only honored by servers
143      that enable the PodOverhead feature.
144 
145    preemptionPolicy    <string>
146      PreemptionPolicy is the Policy for preempting pods with lower priority. One
147      of Never, PreemptLowerPriority. Defaults to PreemptLowerPriority if unset.
148      This field is alpha-level and is only honored by servers that enable the
149      NonPreemptingPriority feature.
150 
151    priority    <integer>
152      The priority value. Various system components use this field to find the
153      priority of the pod. When Priority Admission Controller is enabled, it
154      prevents users from setting this field. The admission controller populates
155      this field from PriorityClassName. The higher the value, the higher the
156      priority.
157 
158    priorityClassName    <string>
159      If specified, indicates the pods priority. "system-node-critical" and
160      "system-cluster-critical" are two special keywords which indicate the
161      highest priorities with the former being the highest priority. Any other
162      name must be defined by creating a PriorityClass object with that name. If
163      not specified, the pod priority will be default or zero if there is no
164      default.
165 
166    readinessGates    <[]Object>
167      If specified, all readiness gates will be evaluated for pod readiness. A
168      pod is ready when all its containers are ready AND all conditions specified
169      in the readiness gates have status equal to "True" More info:
170      https://git.k8s.io/enhancements/keps/sig-network/0007-pod-ready%2B%2B.md
171 
172    restartPolicy    <string>
173      Restart policy for all containers within the pod. One of Always, OnFailure,
174      Never. Default to Always. More info:
175      https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle/#restart-policy
176 
177    runtimeClassName    <string>
178      RuntimeClassName refers to a RuntimeClass object in the node.k8s.io group,
179      which should be used to run this pod. If no RuntimeClass resource matches
180      the named class, the pod will not be run. If unset or empty, the "legacy"
181      RuntimeClass will be used, which is an implicit class with an empty
182      definition that uses the default runtime handler. More info:
183      https://git.k8s.io/enhancements/keps/sig-node/runtime-class.md This is a
184      beta feature as of Kubernetes v1.14.
185 
186    schedulerName    <string>
187      If specified, the pod will be dispatched by specified scheduler. If not
188      specified, the pod will be dispatched by default scheduler.
189 
190    securityContext    <Object>
191      SecurityContext holds pod-level security attributes and common container
192      settings. Optional: Defaults to empty. See type description for default
193      values of each field.
194 
195    serviceAccount    <string>
196      DeprecatedServiceAccount is a depreciated alias for ServiceAccountName.
197      Deprecated: Use serviceAccountName instead.
198 
199    serviceAccountName    <string>
200      ServiceAccountName is the name of the ServiceAccount to use to run this
201      pod. More info:
202      https://kubernetes.io/docs/tasks/configure-pod-container/configure-service-account/
203 
204    shareProcessNamespace    <boolean>
205      Share a single process namespace between all of the containers in a pod.
206      When this is set containers will be able to view and signal processes from
207      other containers in the same pod, and the first process in each container
208      will not be assigned PID 1. HostPID and ShareProcessNamespace cannot both
209      be set. Optional: Default to false.
210 
211    subdomain    <string>
212      If specified, the fully qualified Pod hostname will be
213      "<hostname>.<subdomain>.<pod namespace>.svc.<cluster domain>". If not
214      specified, the pod will not have a domainname at all.
215 
216    terminationGracePeriodSeconds    <integer>
217      Optional duration in seconds the pod needs to terminate gracefully. May be
218      decreased in delete request. Value must be non-negative integer. The value
219      zero indicates delete immediately. If this value is nil, the default grace
220      period will be used instead. The grace period is the duration in seconds
221      after the processes running in the pod are sent a termination signal and
222      the time when the processes are forcibly halted with a kill signal. Set
223      this value longer than the expected cleanup time for your process. Defaults
224      to 30 seconds.
225 
226    tolerations    <[]Object>
227      If specified, the pods tolerations.
228 
229    topologySpreadConstraints    <[]Object>
230      TopologySpreadConstraints describes how a group of pods ought to spread
231      across topology domains. Scheduler will schedule pods in a way which abides
232      by the constraints. This field is only honored by clusters that enable the
233      EvenPodsSpread feature. All topologySpreadConstraints are ANDed.
234 
235    volumes    <[]Object>
236      List of volumes that can be mounted by containers belonging to the pod.
237      More info: https://kubernetes.io/docs/concepts/storage/volumes
View Code

 

# vim rs_damo.yaml   //ReplicaSet(简称rs)简单示例

apiVersion: apps/v1
kind: ReplicaSet
metadata:
    name: myapp
    namespace: default
spec:  
    replicas: 2   //创建pod资源数
    selector:     //是一个对象,表示rs所使用的标签来选择pod
        matchLabels:
            app: myapp     这两个标签是逻辑与,即必须符合这两个标签的pod才能被选中
            release: canary      //以上是rs的,以下是定义rs模板,即定义pod的
    template:   //此模板嵌套的对象有两个,一个人metadata,一个是spec
        metadata:  //表示pod的元数据
            name: myapp-pod
            labels:   //这里必须创建标签,且符合rs标签选择器中的标准
                app: myapp
                release: canary
        spec:
            containers:
            - name: myapp-container
              image: ikubernetes/myapp:v1
              ports:  //pod暴露的端口
              - name: http
                containerPort: 80

 

# kubectl get rs

NAME    DESIRED   CURRENT   READY   AGE
myapp   2         2         2       30s

 

# kubectl get pods

NAME                    READY   STATUS    RESTARTS   AGE
myapp-jl49s             1/1     Running   0          2m13s    //这里pod的名称是: myapp(控制器的名称)+一段随机串
myapp-jzmsf             1/1     Running   0          2m13s

 

目前rs的副本数量是2,如果新加的一个其他pod的标签正好符合rs的标签选择器的选择标准,那么这个新加的pod就会被加进rs中,同时之前的rs由于副本数是2,所以会导致rs从原来的2个pod副本数中下掉一个

8-9:Kubernetes Pod控制器

 

service和ReplicaSet之间的关系:

ReplicaSet创建一组pod资源后,需要被客户端访问,这时访问就需要不受pod资源生命周期的影响,即pod可能出现故障被删除,控制器就会创建另外一下pod,这时pod的名称和地址可能已经改变;所以为了让用户能有一个固定访问端点,就需要添加一个service,service也是根据标签选择器关联到pod资源,才能把客户端的资源请求端口代理至后端的pod上;
但是service和ReplicaSet之间并不是一一对应的关系,比如ReplicaSet-1有两个标签,ReplicaSet-2也有两个标签,但是两者标签不同,但是service只有一个标签,且包含在两个rs的标签中,那个rs1和rs2下的pod都可以被service选中的,即可以关联至service下;
所以service和replicaset之间没有关系,只是service可以使用replicaset创建的pod资源作为后端而已,而且service后端的pod资源可能来自多个replicaset中的pod副本,这取决于service的标签选择器;

8-9:Kubernetes Pod控制器

 

# kubectl edit rs myapp    //实时动态修改,可以动态扩缩容,也可以修改版本

8-9:Kubernetes Pod控制器

# kubectl get rs -o wide

AME    DESIRED   CURRENT   READY   AGE     CONTAINERS        IMAGES                 SELECTOR
myapp   4         4         4       3h58m   myapp-container   ikubernetes/myapp:v2   app=myapp,release=canary

# curl 10.246.2.17   //但是此时的pod版本仍然是V1,所以改了pod控制器即replicaset,但是pod资源不会被重置的,只有pod资源被重建,版本才是新版本

Hello MyApp | Version: v1 | <a href="hostname.html">Pod Name</a>

 # kubectl delete pods myapp-jl49s   //删除其中一个pod,pod控制器就会重新构建一下

#  curl 10.246.1.29    //重新构建后,就是V2的版本了

Hello MyApp | Version: v2 | <a href="hostname.html">Pod Name</a>

以上共有四个pod,可以手动一个一个删除,然后replicaset会重新构建,这就是灰度发布

另外一种方法就是创建另外一个rs,新的rs的标签选择器跟老的标签选择器不完全相同,但是符合service的标签选择器标准,新的rs中包含的pod副本的版本是v2,这些高版本的pod通关关联至service中;

同样,可以先创建rs2,rs2上的pod资源的标签也可以不符合现有service的标签选择器的标准,等到rs2上的所有pod资源都已经ready的时候,就修改service的标签跟rs2上的pod标签一致; 

8-9:Kubernetes Pod控制器

9、Kubernetes Pod控制器

# kubectl explain deploy

KIND:     Deployment
VERSION:  apps/v1

DESCRIPTION:
     Deployment enables declarative updates for Pods and ReplicaSets.

FIELDS:
   apiVersion    <string>
     APIVersion defines the versioned schema of this representation of an
     object. Servers should convert recognized schemas to the latest internal
     value, and may reject unrecognized values. More info:
     https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources

   kind    <string>
     Kind is a string value representing the REST resource this object
     represents. Servers may infer this from the endpoint the client submits
     requests to. Cannot be updated. In CamelCase. More info:
     https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds

   metadata    <Object>
     Standard object metadata.

   spec    <Object>
     Specification of the desired behavior of the Deployment.

   status    <Object>
     Most recently observed status of the Deployment.

 

# kubectl explain deploy.spec.strategy    //启动策略

 

8-9:Kubernetes Pod控制器

上一篇:Github创建仓库并上传本地项目


下一篇:SSM 整合笔记