4.深入理解kubernetes:pod控制器

1.自主pod资源

一级字段:

apiVersion(group/version)

kind

metadata

spec

status

 

2.pod资源

spec.containers

- name

image

imagePullPolicy Always(无论本地有没有都去下载,最常用),Never(有就用,没有就不下载),IfNotPresent(本地不存在就下载)

如果镜像名称标签是latest,叠加策略是IfNotPresent的话等于always

ports: []object,默认TCP协议

- name: http(可以在service中引用该名称)

containerPort: 8080

- name: https

containerPort: 443

command []string (要运行的程序,[]string可以使用[]的 形式)

args []string (传递给command的参数,变量替换使用$(VAR_NAME))

 

 

3.docker中的cmd和entrypoint 与 k8s中的command和args的关系

  • If you do not supply command or args for a Container, the defaults defined in the Docker image are used.
  • If you supply a command but no args for a Container, only the supplied command is used. The default EntryPoint and the default Cmd defined in the Docker image are ignored.
  • If you supply only args for a Container, the default Entrypoint defined in the Docker image is run with the args that you supplied.
  • If you supply a command and args, the default Entrypoint and the default Cmd defined in the Docker image are ignored. Your command is run with your args.

 

 

 

4.标签的艺术

功能标签:前端,后端,数据库.缓存

版本标签:稳定版,开发版,bate版,alpha版.

环境标签:env=qa,prd

标签选择器:

(1)等值

kubectl get pods -l release=stable(有这个标签且值为stable的)

kubectl get pods -l release(有这个标签的)

kubectl get pods -l release=stable,app!=myapp(这两个标签kv都要匹配)

(2)集合关系

key in (v1,v2)

key not in (v1,v2)

!key

key

kubectl get pods -l "release in (v1,v2)"

 

(3)标签的关联

matchLabels:直接给定key

matchExpressions:基于给定的表达式来定义使用标签选择器.{key:"KEY",operator:"OPERATER",values:[v1,v2]}

操作符:in notin,exists,NotExists

 

(4)操作

key:字母,数字下划线,连接线,点

value:可以为空

-L:显示具有app标签的标签值

kubectl get pods -L app

-l:拥有app 标签的:

kubectl get pods -l app --show-labels

修改资源标签

kubectl label pods pod-demo release=canary --overwrite(如果已经存在release标签,需要覆盖)

 

kubectl get nodes --show-labels

节点选择器:

nodeSelector

nodename: 只能运行在指定node上.

annotations:与label不同的地方在于不能挑选资源对象,仅用于为对象提供元数据.

 

apiVersion: v1
kind: Pod
matedata:
    name: myapp
    namespace: default
    labels:(kv随便写)
        app: myapp
        tier: frontend   
spec:
    containers:([]object型的对象写成多个-)
    - name:myapp 
      image: ikube/app:v1
    - name: busybox
      image: busy:latest
      command: 
      - "bin/sh"
      - "-c"
      - "echo ${date} >> /usr/share/nginx/html; sleep 5"
     nodeSelector: (与containers统一目录级别)
       diskType: ssd 
  

5.pod的生命周期

状态:

pending:挂起,条件不满足,比如没有node能满足条件.只能挂起.

Running

Failed

Successed

Unknown

创建pod:

(1)初始化容器

(2)容器探测:

liveness

readiness

6.重启策略restartPolicyy:

  • always;podi里的contaioner挂了就重启.重启策略是不断延时的.容器重启会一直在同一个node上重启
  • OnFailure:
  • Never
  • Default 是always

 

---------------------------------------------------------------------------------------------------------------------------------------

二.pod探针

1.探针:

(1)livenessProbe

exec探测:

 

apiVersion: v1
kind: pod
metadata:
    name: liveness-exec-container
    namespace: default
spec:
    containers: 
    - name: liveness-exec-container
      image: busybox:latest
      imagePullPolicy: IfNotPresent
      command: ["/bin/sh","-c","touch /tmp/healthy;sleep 30;rm -rf /tmp/healthy ;sleep 3600"]
      livenessProbe:
          exec:
              command: ["test","-e","/tmp/healthy"]
          initialDelaySeconds: 1
          periodSeconds: 3    

http探测:

 

apiVersion: v1
kind: pod
metadata:
    name: liveness-http-container
    namespace: default
spec:
    containers: 
    - name: liveness-http-container
      image: xxx/myapp:v1
      imagePullPolicy: IfNotPresent
      ports:
      - name: http
        containerPort: 80    
      livenessProbe:
          httpGet:
              path: /index.html
              port: http
          initialDelaySeconds: 1
          periodSeconds: 3    

(2)readinessProbe:就绪性探测

apiVersion: v1
kind: pod
metadata:
    name: readyness-http-container
    namespace: default
spec:
    containers: 
    - name: readyness-http-container
      image: xxx/myapp:v1
      imagePullPolicy: IfNotPresent
      ports:
      - name: http
        containerPort: 80    
      readinessProbe:
          httpGet:
              path: /index.html
              port: http
          initialDelaySeconds: 1
          periodSeconds: 3  

(3)lifeCycle

postStart:启动后执行的动作:注意命令的相互关系,container的command不能与poststart的exec的command有关系.

apiVersion: v1
kind: Pod
metadata:
    name: postStart-pod
spec:
    containers:
    - name: busybox-httpd
      image: busybox:latest
      imagePullPolicy: IfNotPresent
      lifecycle:
          postStart:
              exec:
                  command: ["/bin/sh","-C","mkdir -p /data/web/html;echo aaa >> /data/web/html/index.html"]
      command: ["/bin/httpd"]
      args: ["-f","-h /data/web/html"]  

preStop:终止之前的动作

1.spec:
 	container
nodeSelector
nodeName
restartPolicy:
Always,Never,OnFailure
containers:
name
image
imagePullPolicy:Always.Never,IfNotPresent
ports:
name
containerPort
livenessProbe
readlinessProbe
lifecycle

2.pod控制器

自主式Pod:不受控制器管理的pod。

 

3.ReplicaSet-替代RC

核心资源有:

(1)副本数

(2)标签选择器

(3)pod模板

命令:kubectl explain rs

KIND:     ReplicaSet
VERSION:  extensions/v1beta1
DESCRIPTION:
     DEPRECATED - This group version of ReplicaSet is deprecated by
     apps/v1beta2/ReplicaSet. See the release notes for more information.
     ReplicaSet ensures that a specified number of pod replicas are running at
     any given time.

命令:kubectl explain rs.spec

三个主要资源:

  replicas	
     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	
     Selector is a label query over pods that should match the replica count. If
     the selector is empty, it is defaulted to the labels present on the pod
     template. Label keys and values that must match in order to be controlled
     by this replica set. More info:
     https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/#label-selectors

   template	
     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的spec就是pod的spec。

 

定义一个replicaset:

apiVersion: apps/v1
kind: ReplicaSet
metadata:
  name: myapp
  namespace: default
spec:
  replicas: 2
  selector:
    matchLabels:
      app: myapp
      release: canary
  templete:
    metadata:
      name: myapp-pod
      labels: #这里的标签一定要与上面的matchLabels中的标签选择器一致,否则会一致找不到符合的pod,一直创建下去
        app: myapp
        release: canary
    spec: #创建的pod的spec
      containers:
      - name: myapp-container
        image: ikubernetes/myapp:v1
        ports:
        - name: http
          containerPort: 80

如果修改了rs中定义的pod描述,只有重建或新建的pod才是修改过的,原来存在的pod不会改变。适用于灰度发布。

金丝雀发布 vs 灰度发布

17世纪,英国矿井工人发现,金丝雀对瓦斯这种气体十分敏感。空气中哪怕有极其微量的瓦斯,金丝雀也会停止歌唱;而当瓦斯含量超过一定限度时,虽然鲁钝的人类毫无察觉,金丝雀却早已毒发身亡。当时在采矿设备相对简陋的条件下,工人们每次下井都会带上一只金丝雀作为“瓦斯检测指标”,以便在危险状况下紧急撤离。

蓝绿发布:

创建另外一个rs,使用不同的标签选择器。让service能关联所有的pod

 

4.deployment

工作在replicaset之上,replicaset来控制pod。只能管控无状态服务。

deployment可以同时控制多个rs,来实现灰度发布的效果。

deploy最多保留10个rs。

还可以控制更新粒度:可以多一个,少一个,也可以两个两个的更新。此时readiness探针很重要。

通过控制节奏,来实现灰度,金丝雀,蓝绿部署。

 

5.DaemonSet:日志收集场景

每个节点一个agent,工作在节点级别,使用DaemonSet来实现。用来实现系统级的守护进程。

 

6.Job:一次性任务,是否重建取决于任务是否正常完成。

 

7.cronJob:周期性任务。

 

8.statefulSet:有状态服务。

拥有自己独有的资源,新加入的pod会继承这些资源。StatefulSet配置服务所需要的操作步骤不一样,需要人为定义一些复杂脚本。

 

9.CDR资源:用户自定义资源 1.8+

 

10.Operator

如普露米修斯,ETCD。

 

11.Helm:类似于conteos中的yum

-----------------------------------------------------------------------------------------------------------------------

pod控制器更新策略总结

1.deploy

更新策略:

(1)kubectl explain deploy.spec.strategy.rollingUpdate

maxSurge: The maximum number of pods that can be scheduled above the desired number

of pods. Value can be an absolute number (ex: 5) or a percentage of desired

pods (ex: 10%).

maxUnavailable:The maximum number of pods that can be unavailable during the update. Value

can be an absolute number (ex: 5) or a percentage of desired pods (ex:

10%)

2.创建一个deploy

apiVersion: apps/v1
kind: Deployment
metadata:
    name: myapp-deploy
spec:
    replicas: 2
    selector:
        matchLabels:
            app: myapp
            release: canary
    templete:
        metadata:
            labels: 
                app: myapp 
                release: canary
        spec:
            containers:
            -   name:myapp
                image: ikubernetes/myapp:v1
                ports:
                - name:http
                  containerPort: 80     

kubectl apply -f deploy-demo.yaml:apply既可以用于创建也可以用于更新操作。

 

3.kubectl path deploy myapp-deploy -p '{"spec":{"replicas":5}}'

查看pod变成了5个。

 

4.kubectl path deploy myapp-deploy -p '{"spec":{"strategy":{“rollingUpdate”:{"maxSurge":1,"maxUnavailable":0}}}}'

 

5.kubectl set image deploy myapp-deploy myapp=ikubernetes/myapp:v3 && kubectl rollout pause deployment myapp-deployment

 

6.回滚:

kubectl rollout undo 回滚到上一版本

kubectl rollout history deployment myapp-deploy

如果有 1,2,3版本

kubectl rollout undo --to-revision=1 回滚到第一版

滚动后第一版没了,变成了只有2,3,4版。

 

7.定义redis和filebeat

apiVersion: apps/v1
kind: Deployment
metadata:
    name: redis
spec:
    replicas: 1
    selector:
      matchLabels:
          app: redis
         role: logstor
     templete:
         metadata:
             labels:
                 app: redis
                 role: logstor
         spec:
             containers:
             -   name: redis
                 image: redis:4.0
                 ports:
                 - name: redis
                   containerPort: 6379
---
apiVersion: apps/v1
kind: DaemonSet
metadata:
  name: myapp-ds
spec:
  selector:
    matchLabels:
      app: filebeat
      release: stable
  templete:
    metadata:
      labels:
        app: filebeat
        release: stable
    spec:
      containers:
      - name: filebeat
        image: ikubernetes/filebeat:5.6.5-alpine
        env:
        - name: REDIS_HOST
          value: redis.default.svc.cluster.local
        - name: REDIS_LOG_LEVEL
          value: info  

 

 

 

你可能感兴趣的:(kubernetes,k8s)