Jusene's Blog

Kubernetes Pod控制器总结

字数统计: 1.6k阅读时长: 7 min
2018/09/19 Share

Pod

Pod是Kubernetes的最小的原子单位,Pod的创建是分自主式pod资源和Pod控制器创建,首先自主式pod资源清单:

  • apiVersion: kubernetes的master通过apiserver接受jason格式的资源定义,而书写这些资源清单通过yaml的文件定义,apiserver会将这些yaml自动转换jason格式,apiVersion相当于restful的api接口定义:

    1
    ~]# kubectl api-version
    2
    admissionregistration.k8s.io/v1beta1
    3
    apiextensions.k8s.io/v1beta1
    4
    apiregistration.k8s.io/v1
    5
    apiregistration.k8s.io/v1beta1
    6
    apps/v1
    7
    apps/v1beta1
    8
    apps/v1beta2
    9
    authentication.k8s.io/v1
    10
    authentication.k8s.io/v1beta1
    11
    authorization.k8s.io/v1
    12
    authorization.k8s.io/v1beta1
    13
    autoscaling/v1
    14
    autoscaling/v2beta1
    15
    batch/v1
    16
    batch/v1beta1
    17
    certificates.k8s.io/v1beta1
    18
    events.k8s.io/v1beta1
    19
    extensions/v1beta1
    20
    networking.k8s.io/v1
    21
    policy/v1beta1
    22
    rbac.authorization.k8s.io/v1
    23
    rbac.authorization.k8s.io/v1beta1
    24
    scheduling.k8s.io/v1beta1
    25
    storage.k8s.io/v1
    26
    storage.k8s.io/v1beta1
    27
    v1
  • kind: 资源定义

  • metadata: 元数据

  • spec: 期望的状态

  • status: 当前状态,本字段由k8s自己维护

资源的定义字段可以通过以下命令查询:

1
~]# kubectl explain pod.spec

自主式pod

1
apiVersion: v1
2
kind: Pod
3
metadata:
4
  name: pod-daemon
5
  namespace: default
6
  labels:
7
    app: myapp
8
	tier: frontend
9
spec:
10
  containers:
11
    - name: myapp
12
	  image: ikubernetes/myapp:v1
13
	  imagePullPolicy: IfNotPresent
14
	  ports:
15
	  - name: http # 消息型内容
16
	    containerPort: 80
17
	  - name: https
18
	    containerPort: 443
19
    - name: busybox
20
	  image: busybox:latest
21
	  imagePullPolicy: IfNotPresent
22
	  command: ["/bin/sh","-c","sleep 3600"]

创建pod

1
~]# kubectl create -f pod-daemon.yaml
2
~]# kubectl exec -it pod-daemon -c myapp -- /bin/sh # 进入myapp这个容器

资源清单格式:
一级字段:
apiVersion(group/version),kind,metadata(name,namespace,labels,annotations…),spec,status(只读)

Pod资源:

1
spec.containers <[]object>
2
- name: <string>
3
  image: <string>
4
  imagePullPolicy: <string>
5
                   Always,Never,IfNotPresent
6
7
修改镜像的默认应用:
8
  command, args
9
  1. 如果没有command和args,image中的entrypoint和cmd生效
10
  2. 如果存在command没有args,image中的entrypoint和cmd都失效,command生效
11
  3. 如果存在args没有command,image中的entrypoint加args生效
12
  4. 如果存在command和args,images中的entrypoint和cmd失效,command和args生效
13
14
标签:
15
  key=value
16
     key: 字母、数字、_、-、。
17
     value: 可以为空,只能字母或数字开头及结尾,中间可使用
18
  kubectl get pods --show-labels
19
  kubectl get pods -l app --show-labels # 过滤pod对象中app键的pod
20
  kubectl get pods -l app!=dev --show-labels
21
  kubectl get pods -L app,run # 显示对于建的值
22
  kubectl label pods pod-daemon release=dev # 给pod打上标签
23
  kubectl label pods pod-daemon release=qa --overwrite # 给已有标签pod强制打标签
24
25
  等值选择器:
26
      等值关系: =, ==, !=
27
      集合关系: 
28
          KEY in (VALUE1,VALUE2)
29
          KEY notin (VALUE1,VALUE2)
30
          KEY
31
          !KEY
32
33
  许多资源支持内嵌字段定义其使用的标签选择器:
34
                matchLabels: 直接给定键值
35
                matchExpressions: 基于给定的表达式来定义使用标签选择器,{key: "KEY", operator: "OPERATOR", values: ["VAL1", "VAL2"...]}
36
                    操作符(OPERATOR):In, NotIn: values字段的值必须为非空列表 
37
                                     Exists, NotExists: values字段的值必须为空列表
38
39
  nodeSelector <map[string]string>  
40
            节点标签选择器
41
42
  nodeName: 指定运行那个节点
43
44
  annotaions:
45
            与label不同的地方在于,它不能用于挑选资源对象,仅用于为对象提供‘元数据’。
46
47
  pod的生命周期:
48
            状态:Pending, Running, Faild, Succeeded, Unknown
49
50
            创建Pod: 
51
            Pod生命周期中的重要行为:
52
                初始化容器
53
                容器探测
54
                  liveness # 存活性探测
55
                  readiness # 就绪性探测
56
  restartPolicy:
57
            Always, OnFailure, Never, Default to Always
58
59
  探针类型有三种:
60
            ExecAction、TcpSocketAction、HttpGetAction
61
62
  lifecycle:
63
           postStart:
64
           preStop:
65
        
66
  hostNetwork: 共享主机网络空间

探测

1
apiVersion: v1
2
kind: Pod
3
metadata:
4
  name: liveness-pod
5
  namespace: default
6
spec:
7
  containers:
8
  - name: liveness-exec-container
9
    image: busybox:latest
10
	imagePullPolicy: IfNotPresent
11
	command: ["/bin/sh","-c","touch /tmp/healthy;sleep 3600"]
12
	livenessProbe:
13
	  exec:
14
	    command: ["test","-f","/tmp/healthy"]
15
	  initialDelaySeconds: 3
16
	  periodSeconds: 3
17
	readinessProbe:
18
	  exec:
19
	    command: ["test","-f","/tmp/healthy"]
20
	  initialDelaySeconds: 5
21
	  periodSeconds: 3

存活性探测: 在探测失败的情况下,或根据restartPolicy的规则进行处理,默认Always
就绪性探测: 就绪型探测可以确保服务可用,在service的情况下确保服务可用

Pod控制器

  • ReplicaController
  • ReplicaSet
  • Deployment
  • DaemonSet
  • Job
  • Cronjob
  • StatefulSet

ReplicaSet是ReplicaController是升级版,所以直接使用ReplicaSet来替代ReplicaController。

ReplicaSet

1
apiVersion: apps/v1
2
kind: ReplicaSet
3
metadata:
4
  name: myapp
5
  namespace: default
6
spec:
7
  replicas: 2
8
  selector: 
9
    matchLabels:
10
	  app: myapp
11
	  release: canary
12
  template:
13
    metadata:
14
      name: myapp
15
	  labels:
16
	    app: myapp
17
	    release: canary
18
	    environment: qa
19
    spec:
20
      containers:
21
	  - name: myapp-container
22
	    image: ikubernetes/myapp:v1
23
	    imagePullPolicy: IfNotPresent
24
	    ports;
25
	    - name: http
26
	      containerPort: 80
1
~]# kubectl get rs -o wide
2
NAME                          DESIRED   CURRENT   READY     AGE       CONTAINERS        IMAGES                 SELECTOR
3
myapp                         2         2         2         1d        myapp-container   ikubernetes/myapp:v1   app=myapp,release=canary

ReplicaSet可以根据定义的replicas的pod个数,多减少补,维护块k8s集群中的定义的pod个数。

Deployment

Deployment是定义在ReplicaSet的上一层,通常定义无状态的pod都使用deployment。

1
apiVersion: apps/v1
2
kind: Deployment
3
metadata:
4
  name: myapp-deploy
5
  namespace: default
6
spec:
7
  replicas: 2
8
  selector:
9
    matchLabels:
10
	  app: myapp
11
	  release: canary
12
  template:
13
    metadata:
14
	  labels:
15
		app: myapp
16
		release: canary
17
	spec:
18
	  containers:
19
	  - name: myapp
20
        image: ikubernetes/myapp:v2
21
		imagePullPolicy: IfNotPresent
22
		ports:
23
		- name: http
24
		  containerPort: 80
1
# 以声明式创建
2
~]# kubectl apply -f myapp-deploy.yaml
3
# 补丁
4
~]# kubectl patch deployment myapp-deploy -p '{"spec": {"replicas": 5}}'
5
# 滚动发布
6
~]# kubectl patch deployment myapp-deploy -p '{"spec": {"template": {"spec": {"containers": [{"name":"myapp","image": "ikubernetes/myapp:v3"}]}}}}'
7
# 金丝雀发布,容器中只更新一个容器,就暂停,等稳定后resume更新全部的容器
8
~]# kubectl patch deployment myapp-deploy -p '{"spec": {"strategy": {"rollingUpdate": {"maxSurge": 1, "maxUnavailable": 0}}}}' && kubectl rollout pause deployment myapp-deploy
9
~]# kubectl rollout resume deployment myapp-deploy
10
# 查看发布的版本,默认会维护ReplicaSet的历史版本,默认10个版本
11
~]# kubectl history deploymnet myapp-deploy
12
# 回滚版本
13
~]# kubectl rollout undo deployment myapp-deploy # 回滚到上一个版本
14
~]# kubectl rollout undo deployment myapp-deploy --to-revision=1 # 回滚到指定版本,被回滚的版本更新到最新的版本
15
# 查看回滚的状态
16
~]# kubectl rollout status deployment myapp-deploy

DaemonSet

DaemonSet能让kubernetes每个节点运行同一个pod,每个节点加入kubernetes集群都会自动运行这个pod,适合运行系统性的应用,如日志收集等。

1
apiVersion: apps/v1
2
kind: DaemonSet
3
metadata:
4
  name: myapp-ds
5
  namespace: default
6
spec:
7
  selector:
8
    matchLabels:
9
	  app: filebeat
10
	  release: stable
11
  template:
12
    metadata:
13
	  labels:
14
	    app: filebeat
15
		release: stable
16
    spec:
17
	  containers:
18
	    - name: filebeat
19
		  image: ikubernetes/filebeat:5.6.5-alpine
20
		  imagePullPolicy: IfNotPresent
21
		  env: 
22
		  - name: REDIS_HOST
23
		    value: redis.default.svc.cluster.local
24
		  - name: REDIS_LOG_LEVEL
25
		    value: info

Job

job和rc或者rs的不同在于,job的pod多用于执行一次性任务,执行完成pod后就会停止。

RestartPolicy
job pod的template的RestartPolicy只能指定Never或OnFailure,当job未完成的情况下:

  • 如果RestartPolicy指定Never,则job会在pod出现故障时创建新的pod,且故障pod不会消失。.status.failed加1。
  • 如果RestartPolicy指定OnFailure,则job会在pod出现故障时其内部重启容器,而不是创建pod。.status.failed不变。
1
apiVersion: batch/v1
2
kind: Job
3
metadata:
4
  name: com
5
  namespace: default
6
spec:
7
  template:
8
    metadata:
9
	  name: com
10
	spec:
11
	  containers:
12
	  - name: com
13
	    image: busybox:latest
14
		imagePullPolicy: IfNotPresent
15
		command: ["/bin/sh","-c","sleep 60"]
16
	  restartPolicy: Never
17
	  activeDeadlineSeconds: 70

Cronjob

cronjob的在于计划性job执行。

1
apiVersion: batch/v1beta1
2
kind: CronJob
3
metadata:
4
  name: test
5
  namespace: default
6
spec:
7
  schedule: "* * * * *"
8
  jobTemplate:
9
    spec:
10
	  template:
11
	    spec:
12
		  containers:
13
		  - name: test
14
		    image: busybox:latest
15
			imagePullPolicy: IfNotPresent
16
			command: ["/bin/sh","-c", "echo 'hello world'"]
17
		  restartPolicy: OnFailure
CATALOG
  1. 1. Pod
    1. 1.1. 探测
  2. 2. Pod控制器
    1. 2.1. ReplicaSet
    2. 2.2. Deployment
  3. 3. DaemonSet
  4. 4. Job
  5. 5. Cronjob