四、Kubernetes—资源清单

目录

 

一、K8S中的资源

1、资源的定义

2、资源的种类

二、资源清单

1、简单说明

2、YAML支持的数据结构

三、常用字段解释说明

1、必须存在的属性

2、主要对象

3、额外的参数项

四、容器生命周期

1、 Init容器

2、Init容器的作用

3、使用Init的案例

5、容器探针

6、容器启动、退出动作

7、其它


一、K8S中的资源

1、资源的定义

K8S中所有的内容都抽象为资源,资源实例化后,被称为对象。

2、资源的种类

  • 工作负载型资源(workload):Pod、ReplicaSet、Deployment、StatefulSet、DaemonSet、Job、CronJob(ReplicationController在v1.11版本被废弃)
  • 服务发现及负载均衡型资源(ServiceDiscovery LoadBalance):Service、Ingress、...
  • 配置与存储型资源:Volume(存储卷)、CSI(容器存储接口,可以扩展各种各样的第三方存储卷)
  • 特殊类型的存储卷:ConfigMap(当配置中心来使用的资源类型)、Secret(保存敏感数据)、DownwardAPI(把外部环境中的信息输出给容器)
  • 集群级资源:Namespace、Node、Role、ClusterRole、RoleBinding、ClusterRoleBinding
  • 云数据型资源:HPA、PodTemplate、LimitRange

二、资源清单

在K8S中,一般使用yaml格式的文件来创建符合我们预期期望的pod,这样的yaml文件我们一般称为资源清单。关于yaml语法,下面简单的介绍下

1、简单说明

是一个可读性高,用来表达数据序列的格式。YAML的意思其实是:仍是一种标记语言,但为了强调这种语言以数据做为中心,而不是以标记语言为重点。

基本语法

  • 缩进时不允许使用Tab键,只允许使用空格
  • 缩进的空格数目不重要,只要相同层级的元素左侧对齐即可
  • #标识注释,从这个字符一直到行尾,都会被解释器忽略

2、YAML支持的数据结构

  • 对象:键值对的集合,又称为映射(mapping)/哈希(hashes)/字典(dictionary)
  • 数组:一组按次序排列的值,又称为序列(sequence)/列表(list)
  • 纯量(scalars):单个的,不可再分的值

1)对象类型:对象的一组键值对,使用冒号结构表示

name: Steve
age: 18

Yaml也允许另一种写法,将所有键值对写成一个行内对象

hash: { name: Steve, age: 18 }

2)数组类型:一组连词线开头的行,构成一个数组

animal
- Cat
- Dog

数组也可以采用行内表示法

animal: [Cat, Dog]

复合结构:对象和数组可以结合使用,形成复合结构

languages:
- Ruby
- Perl
- Python

websites:
YAML: yaml.org
Ruby: ruby-lang.org
Python: python.org
Perl: use.perl.org

字符串

字符串默认不适用引号表示

str: 这是一行字符串

如果字符串之中包含空格或特殊字符,需要放在引号之中

str: '内容': 字符串'

单引号和双引号都可以使用,双引号不会对特殊字符转义

s1: '内容\n字符串'
s2: '内容\n字符串'

单引号之中如果还有单引号,需要连续使用两个单引号转义

str: 'labor''s day'

字符串可以写成多行,从第二行开始,必须有一个单空格缩进。换行符会被转成空格

str: 这是一段
 多行
 字符串

三、常用字段解释说明

在k8s中,可以通过命令查看相应资源的属性情况

[root@k8s-master ~]# kubectl  explain pod
KIND:     Pod
VERSION:  v1

DESCRIPTION:
     Pod is a collection of containers that can run on a host. This resource is
     created by clients and scheduled onto hosts.

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's 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

   status	<Object>
     Most recently observed status of the pod. This data may not be up to date.
     Populated by the system. Read-only. More info:
     https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status

如果继续想查看资源下一字段的属性可以继续使用命令

[root@k8s-master ~]# kubectl  explain pod.apiVersion
KIND:     Pod
VERSION:  v1

FIELD:    apiVersion <string>

DESCRIPTION:
     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

1、必须存在的属性

2、主要对象

 

3、额外的参数项

下面就以创建一个pod为例,简单介绍下如果利用yaml文件创建资源对象

首先,编写yaml文件

[root@k8s-master pod]# vim pod.yaml
# 此处故意利用同一个镜像创建两个容器,来验证同一个pod下共享网络栈
apiVersion: v1
kind: Pod
metadata:
  name: myapp-pod
  labels:
    app: myapp
spec:
  containers:
  - name: app
    image: hushensong.com/library/myapp:v1
  - name: test
    image: hushensong.com/library/myapp:v1

 

[root@k8s-master pod]# kubectl  apply -f pod.yaml 
pod/myapp-pod created
[root@k8s-master pod]# 
[root@k8s-master pod]# 
[root@k8s-master pod]# kubectl  get pod
NAME        READY   STATUS   RESTARTS   AGE
myapp-pod   1/2     Error    1          11s

 查看pod的状态时,pod状态异常,查看pod运行详细信息,发现test容器异常

[root@k8s-master pod]# kubectl  describe  pod myapp-pod
Name:         myapp-pod
Namespace:    default
Priority:     0
Node:         k8s-node02/192.168.221.133
Start Time:   Sun, 14 Mar 2021 22:54:53 +0800
Labels:       app=myapp
Annotations:  Status:  Running
IP:           10.244.2.3
IPs:
  IP:  10.244.2.3
Containers:
  app:
    Container ID:   docker://d890fad5c335493db2a133a9cebc6298fd49023e19a1df6e32a2d6d99f054176
    Image:          hushensong.com/library/myapp:v1
    Image ID:       docker-pullable://hushensong.com/library/myapp@sha256:9eeca44ba2d410e54fccc54cbe9c021802aa8b9836a0bcf3d3229354e4c8870e
    Port:           <none>
    Host Port:      <none>
    State:          Running
      Started:      Sun, 14 Mar 2021 22:54:54 +0800
    Ready:          True
    Restart Count:  0
    Environment:    <none>
    Mounts:
      /var/run/secrets/kubernetes.io/serviceaccount from default-token-9ktlc (ro)
  test:
    Container ID:   docker://cb029d05f56c45adbc410171291b4b83be56d9b9704230f5a94c197b8cb0eff8
    Image:          hushensong.com/library/myapp:v1
    Image ID:       docker-pullable://hushensong.com/library/myapp@sha256:9eeca44ba2d410e54fccc54cbe9c021802aa8b9836a0bcf3d3229354e4c8870e
    Port:           <none>
    Host Port:      <none>
    State:          Waiting
      Reason:       CrashLoopBackOff
    Last State:     Terminated
      Reason:       Error
      Exit Code:    1
      Started:      Sun, 14 Mar 2021 22:56:27 +0800
      Finished:     Sun, 14 Mar 2021 22:56:29 +0800
    Ready:          False
    Restart Count:  4
    Environment:    <none>
    Mounts:
      /var/run/secrets/kubernetes.io/serviceaccount from default-token-9ktlc (ro)
Conditions:
  Type              Status
  Initialized       True 
  Ready             False 
  ContainersReady   False 
  PodScheduled      True 
Volumes:
  default-token-9ktlc:
    Type:        Secret (a volume populated by a Secret)
    SecretName:  default-token-9ktlc
    Optional:    false
QoS Class:       BestEffort
Node-Selectors:  <none>
Tolerations:     node.kubernetes.io/not-ready:NoExecute for 300s
                 node.kubernetes.io/unreachable:NoExecute for 300s
Events:
  Type     Reason     Age                 From                 Message
  ----     ------     ----                ----                 -------
  Normal   Scheduled  <unknown>           default-scheduler    Successfully assigned default/myapp-pod to k8s-node02
  Normal   Pulled     115s                kubelet, k8s-node02  Container image "hushensong.com/library/myapp:v1" already present on machine
  Normal   Created    115s                kubelet, k8s-node02  Created container app
  Normal   Started    115s                kubelet, k8s-node02  Started container app
  Normal   Pulled     22s (x5 over 115s)  kubelet, k8s-node02  Container image "hushensong.com/library/myapp:v1" already present on machine
  Normal   Created    22s (x5 over 115s)  kubelet, k8s-node02  Created container test
  Normal   Started    22s (x5 over 115s)  kubelet, k8s-node02  Started container test
  Warning  BackOff    19s (x7 over 109s)  kubelet, k8s-node02  Back-off restarting failed container

 看看具体容器的日志信息,提示端口占用,证明同一个pod中共享网络栈

[root@k8s-master pod]# kubectl  logs  pod myapp-pod  -c test
Error from server (NotFound): pods "pod" not found
[root@k8s-master pod]# kubectl  logs  myapp-pod  -c test
2021/03/14 14:56:27 [emerg] 1#1: bind() to 0.0.0.0:80 failed (98: Address in use)
nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address in use)
2021/03/14 14:56:27 [emerg] 1#1: bind() to 0.0.0.0:80 failed (98: Address in use)
nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address in use)
2021/03/14 14:56:27 [emerg] 1#1: bind() to 0.0.0.0:80 failed (98: Address in use)
nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address in use)
2021/03/14 14:56:27 [emerg] 1#1: bind() to 0.0.0.0:80 failed (98: Address in use)
nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address in use)
2021/03/14 14:56:27 [emerg] 1#1: bind() to 0.0.0.0:80 failed (98: Address in use)
nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address in use)
2021/03/14 14:56:27 [emerg] 1#1: still could not bind()
nginx: [emerg] still could not bind()

删除pod.yaml文件中容器内容,然后删除刚刚创建的pod,重新创建,显示成功

[root@k8s-master pod]# kubectl delete pod  myapp-pod
pod "myapp-pod" deleted
[root@k8s-master pod]# kubectl  create -f pod.yaml 
pod/myapp-pod created
[root@k8s-master pod]# kubectl  get pod
NAME        READY   STATUS    RESTARTS   AGE
myapp-pod   1/1     Running   0          5s
[root@k8s-master pod]# kubectl  get pod -o wide
NAME        READY   STATUS    RESTARTS   AGE   IP           NODE         NOMINATED NODE   READINESS GATES
myapp-pod   1/1     Running   0          13s   10.244.1.2   k8s-node01   <none>           <none>
[root@k8s-master pod]# curl 10.244.1.2
Hello MyApp | Version: v1 | <a href="hostname.html">Pod Name</a>

四、容器生命周期

1、 Init容器

Pod能够具有多个容器,应用运行在容器里面,但是它也可能有一个或多个先于应用容器启动的Init容器。

Init容器于普通的容器非常像,除了如下两点:

  • Init容器总是运行到成功完成为止
  • 每个Init容器都必须在下一个Init容器启动之前成功完成

如果Pod的Init容器失败,Kubernetes会不断的重启该pod,知道Init容器成功为止。然而,如果Pod对应的restartPolicy为Never,它不会重新启动。

2、Init容器的作用

因为Init容器具有与应用程序容器分离的单独镜像,所以它们的启动相关代码具有如下优势:

它们可以包含并运行实用工具,但是出于安全考虑,是不建议在应用程序容器镜像中包含这些实用工具的。

它们可以包含实用工具和定制化代码来安装,但是不能出现在应用程序镜像中。例如,创建镜像没必要FROM另一个镜像,只需要在安装过程中使用类似sed、awk、Python或dig这样的工具。

应用程序镜像可以分离出创建和部署的角色,而没有必要联合它们构建一个单独的镜像。

Init容器使用Linux Namespace,所以相对应用程序容器来说具有不同的文件系统视图。因此,它们能够具有访问Secret的权限,而应用程序容器则不能。

它们必须在应用程序容器启动之前运行完成,而应用程序容器是并行运行的,所以Init容器能够提供了一个简单的阻塞或延迟应用容器的启动的方法,直到满足了一组先决条件。

3、使用Init的案例

首先在工作节点下载busybox镜像,并打标签,防止每次都拉取最新latest镜像

[root@k8s-node02 ~]# docker pull busybox
[root@k8s-node02 ~]# docker tag busybox:latest  busybox:v1
[root@k8s-node02 ~]# docker  rmi busybox:latest
Untagged: busybox:latest

编写pod.yaml

apiVersion: v1
kind: Pod
metadata:
  name: myapp-pod
  labels:
    app: myapp
spec:
  containers:
  - name: myapp-container
    image: busybox:v1
    command: ['sh','-c','echo The app is running! && sleep 3600']
  initContainers:
  - name: init-myservice
    image: busybox
    command: ['sh','-c','until nslookup myservice; do echo waiting for myservice; sleep 2; done;']
  - name: init-mydb
    image: busybox
    command: ['sh','-c','until nslookup mydb; do echo waiting for mydb; sleep 2; done;']
[root@k8s-master pod]# kubectl  create -f pod.yaml 
pod/myapp-pod created
#查看状态为初始镜像在执行
[root@k8s-master pod]# kubectl  get pod
NAME        READY   STATUS     RESTARTS   AGE
myapp-pod   0/1     Init:0/2   0          31s

# 查看pod详细信息,发现在启动init-myservice
[root@k8s-master pod]# kubectl describe pod myapp-pod
Name:         myapp-pod
Namespace:    default
Priority:     0
Node:         k8s-node02/192.168.221.133
Start Time:   Mon, 15 Mar 2021 16:47:30 +0800
Labels:       app=myapp
Annotations:  <none>
Status:       Pending
IP:           10.244.2.4
IPs:
  IP:  10.244.2.4
Init Containers:
  init-myservice:
    Container ID:  docker://d7929095d3df6851e846687051edb361c39d07459018c75ed8c630035b4029e4
    Image:         busybox
    Image ID:      docker-pullable://busybox@sha256:ce2360d5189a033012fbad1635e037be86f23b65cfd676b436d0931af390a2ac
    Port:          <none>
    Host Port:     <none>
    Command:
      sh
      -c
      until nslookup myservice; do echo waiting for myservice; sleep 2; done;
    State:          Running
      Started:      Mon, 15 Mar 2021 16:47:35 +0800
    Ready:          False
    Restart Count:  0
    Environment:    <none>
    Mounts:
      /var/run/secrets/kubernetes.io/serviceaccount from default-token-9ktlc (ro)
  init-mydb:
    Container ID:  
    Image:         busybox
    Image ID:      
    Port:          <none>
    Host Port:     <none>
    Command:
      sh
      -c
      until nslookup mydb; do echo waiting for mydb; sleep 2; done;
    State:          Waiting
      Reason:       PodInitializing
    Ready:          False
    Restart Count:  0
    Environment:    <none>
    Mounts:
      /var/run/secrets/kubernetes.io/serviceaccount from default-token-9ktlc (ro)
Containers:
  myapp-container:
    Container ID:  
    Image:         busybox:v1
    Image ID:      
    Port:          <none>
    Host Port:     <none>
    Command:
      sh
      -c
      echo The app is running! && sleep 3600
    State:          Waiting
      Reason:       PodInitializing
    Ready:          False
    Restart Count:  0
    Environment:    <none>
    Mounts:
      /var/run/secrets/kubernetes.io/serviceaccount from default-token-9ktlc (ro)
Conditions:
  Type              Status
  Initialized       False 
  Ready             False 
  ContainersReady   False 
  PodScheduled      True 
Volumes:
  default-token-9ktlc:
    Type:        Secret (a volume populated by a Secret)
    SecretName:  default-token-9ktlc
    Optional:    false
QoS Class:       BestEffort
Node-Selectors:  <none>
Tolerations:     node.kubernetes.io/not-ready:NoExecute for 300s
                 node.kubernetes.io/unreachable:NoExecute for 300s
Events:
  Type    Reason     Age        From                 Message
  ----    ------     ----       ----                 -------
  Normal  Scheduled  <unknown>  default-scheduler    Successfully assigned default/myapp-pod to k8s-node02
  Normal  Pulling    112s       kubelet, k8s-node02  Pulling image "busybox"
  Normal  Pulled     108s       kubelet, k8s-node02  Successfully pulled image "busybox"
  Normal  Created    108s       kubelet, k8s-node02  Created container init-myservice
  Normal  Started    108s       kubelet, k8s-node02  Started container init-myservice


#查看容器日志信息查出问题
[root@k8s-master pod]# kubectl logs myapp-pod  -c init-myservice
Server:		10.96.0.10
Address:	10.96.0.10:53

** server can't find myservice.default.svc.cluster.local: NXDOMAIN

*** Can't find myservice.svc.cluster.local: No answer
*** Can't find myservice.cluster.local: No answer
*** Can't find myservice.localdomain: No answer
*** Can't find myservice.default.svc.cluster.local: No answer
*** Can't find myservice.svc.cluster.local: No answer
*** Can't find myservice.cluster.local: No answer
*** Can't find myservice.localdomain: No answer

创建myservice.yaml创建service服务

[root@k8s-master pod]# vim myservice.yaml
apiVersion: v1
kind: Service
metadata:
  name: myservice
spec:
  ports:
    - protocol: TCP
      port: 80
      targetPort: 9376


[root@k8s-master pod]# kubectl create -f myservice.yaml 
service/myservice created

[root@k8s-master pod]# kubectl get  svc
NAME         TYPE        CLUSTER-IP      EXTERNAL-IP   PORT(S)   AGE
kubernetes   ClusterIP   10.96.0.1       <none>        443/TCP   7d
myservice    ClusterIP   10.104.126.83   <none>        80/TCP    2m33s

[root@k8s-master pod]# kubectl get pod -n kube-system
NAME                                 READY   STATUS    RESTARTS   AGE
coredns-66bff467f8-rwxx2             1/1     Running   5          7d
coredns-66bff467f8-t9ztd             1/1     Running   5          7d
etcd-k8s-master                      1/1     Running   5          7d
kube-apiserver-k8s-master            1/1     Running   5          7d
kube-controller-manager-k8s-master   1/1     Running   5          7d
kube-flannel-ds-7kmrb                1/1     Running   5          7d
kube-flannel-ds-cg77h                1/1     Running   5          7d
kube-flannel-ds-jpphf                1/1     Running   5          7d
kube-proxy-8b4bj                     1/1     Running   5          7d
kube-proxy-kx9fw                     1/1     Running   5          7d
kube-proxy-tb2hw                     1/1     Running   5          7d
kube-scheduler-k8s-master            1/1     Running   5          7d


#再次查看发现初始化容器已就绪了一个
[root@k8s-master pod]# kubectl get pod
NAME        READY   STATUS     RESTARTS   AGE
myapp-pod   0/1     Init:1/2   0          15m

创建mydb.yaml创建service服务

[root@k8s-master pod]# vim mydb.yaml
apiVersion: v1
kind: Service
metadata:
  name: mydb
spec:
  ports:
    - protocol: TCP
      port: 80
      targetPort: 9377

# 再次查看pod的状态时已经处于正常Running 状态
[root@k8s-master pod]# kubectl create -f mydb.yaml
[root@k8s-master pod]# kubectl  get pod
NAME        READY   STATUS    RESTARTS   AGE
myapp-pod   1/1     Running   0          21m

特殊说明

  • 在Pod启动过程中,Init容器会按顺序在网络和数据卷初始化之后启动。每个容器必须在下一个容器启动之前成功退出。
  • 如果由于运行时或失败退出,将导致容器启动失败,它会根据Pod的restartPolicy指定的策略进行重试。然而,如果Pod的restartPolicy设置为Always,Init容器失败时会使用RestartPolicy策略。
  • 在所有的Init容器没有成功之前,Pod将不会变成Ready状态。Init容器的端口将不会在service中进行聚集。正在初始化中的Pod处于Pending状态,但应该会将Initializing状态设置为true。
  • 如果Pod重启,所有Init容器必须重新执行。
  • # 对Init容器spec的修改被限制在容器image字段,修改其他字段都不会生效。更改Init容器的image字段,等价于重启该Pod。
  • Init容器具有应用容器的所有字段。除了readinessProbe,因为Init容器无法定义不同于完成(completion)的就绪(readiness)之外的其他状态。这会在验证过程中强制执行。
  • 在Pod中的每个app和Init容器的名称必须唯一;与任何其他容器共享同一个名称,会在验证时抛出错误。

5、容器探针

探针是由kubelet对容器执行的定期诊断。要执行诊断,kubelet调用由容器实现的Handler。有三种类型的处理程序:

  • ExecAction:在容器内执行指定命令。如果命令退出时返回码为0 ,则认为诊断成功。
  • TCPSocketAction:对指定端口上的容器的IP地址进行TCP检查。如果端口打开,则诊断被认为是成功的。
  • HTTPGetAction:对指定的端口和路径上的容器的IP地址执行HTTP Get请求。如果响应的状态码大于等于200且小于400,则诊断被认为是成功的。

每次探针都将获得以下三个结果之一:

  • 成功:容器通过了诊断
  • 失败:容器未通过诊断
  • 未知:诊断失败,因此不会采取任何行动

探针方式

  • livenessProbe:指示容器是否正在运行。如果存活探测失败,则kubelet会杀死容器,并且容器将受到其重启策略的影响。如果容器不提供存活探针,则默认状态为Success。
  • readinessProbe:指示容器是否准备好服务请求。如果就绪探测失败,端点控制器将从与Pod匹配的所有Service的端点中删除该Pod的IP地址。初始延迟之前的就绪状态默认为Failure。如果容器不提供就绪探针,则默认状态为Success。

下面就给大家演示就绪检测实例readinessProbe-httpget:

创建pod的read.yaml文件

[root@k8s-master pod]# vim read.yaml
apiVersion: v1
kind: Pod
metadata:
  name: readiness-httpget-pod
  namespace: default
spec:
  containers:
  - name: readiness-httpget-container
    image: hushensong.com/library/myapp:v1
    imagePullPolicy: IfNotPresent
    readinessProbe:
      httpGet:
        port: 80
        path: /index1.html
      initialDelaySeconds: 1
      periodSeconds: 3


#状态为Running 但是没有准备
[root@k8s-master pod]# kubectl  get pod
NAME                    READY   STATUS    RESTARTS   AGE
readiness-httpget-pod   0/1     Running   0          104s

#查看原因
[root@k8s-master pod]# kubectl  describe  pod readiness-httpget-pod   
Name:         readiness-httpget-pod
Namespace:    default
Priority:     0
Node:         k8s-node01/192.168.221.132
Start Time:   Mon, 15 Mar 2021 21:33:14 +0800
Labels:       <none>
Annotations:  <none>
Status:       Running
IP:           10.244.1.4
IPs:
  IP:  10.244.1.4
Containers:
  readiness-httpget-container:
    Container ID:   docker://7a6d229e97a6f1a2dc57d6c4feb6cc809f6a5dfa6c43ac8f9e4a36e7ce0993aa
    Image:          hushensong.com/library/myapp:v1
    Image ID:       docker-pullable://hushensong.com/library/myapp@sha256:9eeca44ba2d410e54fccc54cbe9c021802aa8b9836a0bcf3d3229354e4c8870e
    Port:           <none>
    Host Port:      <none>
    State:          Running
      Started:      Mon, 15 Mar 2021 21:33:15 +0800
    Ready:          False
    Restart Count:  0
    Readiness:      http-get http://:80/index1.html delay=1s timeout=1s period=3s #success=1 #failure=3
    Environment:    <none>
    Mounts:
      /var/run/secrets/kubernetes.io/serviceaccount from default-token-9ktlc (ro)
Conditions:
  Type              Status
  Initialized       True 
  Ready             False 
  ContainersReady   False 
  PodScheduled      True 
Volumes:
  default-token-9ktlc:
    Type:        Secret (a volume populated by a Secret)
    SecretName:  default-token-9ktlc
    Optional:    false
QoS Class:       BestEffort
Node-Selectors:  <none>
Tolerations:     node.kubernetes.io/not-ready:NoExecute for 300s
                 node.kubernetes.io/unreachable:NoExecute for 300s
Events:
  Type     Reason     Age                     From                 Message
  ----     ------     ----                    ----                 -------
  Normal   Scheduled  <unknown>               default-scheduler    Successfully assigned default/readiness-httpget-pod to k8s-node01
  Normal   Pulled     4m32s                   kubelet, k8s-node01  Container image "hushensong.com/library/myapp:v1" already present on machine
  Normal   Created    4m32s                   kubelet, k8s-node01  Created container readiness-httpget-container
  Normal   Started    4m32s                   kubelet, k8s-node01  Started container readiness-httpget-container
  Warning  Unhealthy  3m26s (x22 over 4m29s)  kubelet, k8s-node01  Readiness probe failed: HTTP probe failed with statuscode: 404


#进入容器,增加探测文件
[root@k8s-master pod]# kubectl  get pod
NAME                    READY   STATUS    RESTARTS   AGE
readiness-httpget-pod   0/1     Running   0          5m35s
[root@k8s-master pod]# kubectl  exec  readiness-httpget-pod  -it  -- /bin/sh
/usr/share/nginx/html # ls
50x.html    index.html
/usr/share/nginx/html # echo "hello" >> index1.html


#再次查看pod状态,此时变为正常Ready
[root@k8s-master pod]# kubectl  get pod
NAME                    READY   STATUS    RESTARTS   AGE
readiness-httpget-pod   1/1     Running   0          8m13s

接下来给大家演示下探针存活检测livenessProbe-exec:

创建Pod的live-exec.yaml文件

[root@k8s-master pod]# vim live-exec.yaml
apiVersion: v1
kind: Pod
metadata:
  name: liveness-exec-pod
  namespace: default
spec:
  containers:
  - name: liveness-exec-container
    image: busybox:v1
    imagePullPolicy: IfNotPresent
    command: ["/bin/sh","-c","touch /tmp/live ; sleep 60; rm -rf /tmp/live ; sleep 3600"]
    livenessProbe:
      exec:
        command: ["test","-e","/tmp/live"]
      initialDelaySeconds: 1
      periodSeconds: 3

[root@k8s-master pod]# kubectl  create -f live-exec.yaml 
pod/liveness-exec-pod created

[root@k8s-master pod]# kubectl  get pod 
NAME                READY   STATUS    RESTARTS   AGE
liveness-exec-pod   1/1     Running   0          7s

#pod的状态正常,但是过了60s后,文件不存在了将对pod进行重启
[root@k8s-master pod]# kubectl  get pod 
NAME                READY   STATUS    RESTARTS   AGE
liveness-exec-pod   1/1     Running   1          2m6s

接下来给大家演示下探针存活检测livenessProbe-httpget:

[root@k8s-master pod]# vim live-http.yaml
apiVersion: v1
kind: Pod
metadata:
  name: liveness-httpget-pod
  namespace: default
spec:
  containers:
  - name: liveness-httpget-container
    image: hushensong.com/library/myapp:v1
    imagePullPolicy: IfNotPresent
    ports:
    - name: http
      containerPort: 80
    livenessProbe:
      httpGet:
        port: http
        path: /index.html
      initialDelaySeconds: 1
      periodSeconds: 3
      timeoutSeconds: 10

[root@k8s-master pod]# kubectl create -f live-http.yaml 
pod/liveness-httpget-pod created

[root@k8s-master pod]# kubectl get pod -o wide
NAME                   READY   STATUS    RESTARTS   AGE   IP           NODE         NOMINATED NODE   READINESS GATES
liveness-httpget-pod   1/1     Running   0          45s   10.244.2.5   k8s-node02   <none>           <none>

[root@k8s-master pod]# curl  10.244.2.5/index.html
Hello MyApp | Version: v1 | <a href="hostname.html">Pod Name</a>

#删除文件后,无法访问,此时会对pod进行重启,重启后可再次访问
[root@k8s-master pod]# kubectl  exec  liveness-httpget-pod  -it  --  rm -rf /usr/share/nginx/html/index.html
[root@k8s-master pod]# curl  10.244.2.5/index.html
<html>
<head><title>404 Not Found</title></head>
<body bgcolor="white">
<center><h1>404 Not Found</h1></center>
<hr><center>nginx/1.12.2</center>
</body>
</html>


[root@k8s-master pod]# kubectl get pod 
NAME                   READY   STATUS    RESTARTS   AGE
liveness-httpget-pod   1/1     Running   3          4m36s
[root@k8s-master pod]# curl  10.244.2.5/index.html
Hello MyApp | Version: v1 | <a href="hostname.html">Pod Name</a>

接下来给大家演示下探针存活检测livenessProbe-tcp:

创建pod的live-tcp.yaml文件

[root@k8s-master pod]# vim live-tcp.yaml
apiVersion: v1
kind: Pod
metadata:
  name: probe-tcp
spec:
  containers:
  - name: nginx
    image: hushensong.com/library/myapp:v1
    livenessProbe:
      initialDelaySeconds: 5
      timeoutSeconds: 1
      tcpSocket:
        port: 8080
      periodSeconds: 3

#在配置yaml文件是故意将探测端口设置成错误的8080端口,pod将重启
[root@k8s-master pod]# kubectl  create -f live-tcp.yaml 
pod/probe-tcp created

[root@k8s-master pod]# kubectl  get pod
NAME        READY   STATUS    RESTARTS   AGE
probe-tcp   1/1     Running   3          46s

[root@k8s-master pod]# kubectl  get pod
NAME        READY   STATUS             RESTARTS   AGE
probe-tcp   0/1     CrashLoopBackOff   4          114s


[root@k8s-master pod]# kubectl describe pod probe-tcp
Name:         probe-tcp
Namespace:    default
Priority:     0
Node:         k8s-node01/192.168.221.132
Start Time:   Mon, 15 Mar 2021 22:21:57 +0800
Labels:       <none>
Annotations:  <none>
Status:       Running
IP:           10.244.1.6
IPs:
  IP:  10.244.1.6
Containers:
  nginx:
    Container ID:   docker://87517c2bab24a54a3d674f2c5162f826b01919c52f2ac242e4f6eef1a6cfb314
    Image:          hushensong.com/library/myapp:v1
    Image ID:       docker-pullable://hushensong.com/library/myapp@sha256:9eeca44ba2d410e54fccc54cbe9c021802aa8b9836a0bcf3d3229354e4c8870e
    Port:           <none>
    Host Port:      <none>
    State:          Waiting
      Reason:       CrashLoopBackOff
    Last State:     Terminated
      Reason:       Completed
      Exit Code:    0
      Started:      Mon, 15 Mar 2021 22:24:01 +0800
      Finished:     Mon, 15 Mar 2021 22:24:12 +0800
    Ready:          False
    Restart Count:  5
    Liveness:       tcp-socket :8080 delay=5s timeout=1s period=3s #success=1 #failure=3
    Environment:    <none>
    Mounts:
      /var/run/secrets/kubernetes.io/serviceaccount from default-token-9ktlc (ro)
Conditions:
  Type              Status
  Initialized       True 
  Ready             False 
  ContainersReady   False 
  PodScheduled      True 
Volumes:
  default-token-9ktlc:
    Type:        Secret (a volume populated by a Secret)
    SecretName:  default-token-9ktlc
    Optional:    false
QoS Class:       BestEffort
Node-Selectors:  <none>
Tolerations:     node.kubernetes.io/not-ready:NoExecute for 300s
                 node.kubernetes.io/unreachable:NoExecute for 300s
Events:
  Type     Reason     Age                     From                 Message
  ----     ------     ----                    ----                 -------
  Normal   Scheduled  <unknown>               default-scheduler    Successfully assigned default/probe-tcp to k8s-node01
  Normal   Pulled     2m53s (x4 over 3m29s)   kubelet, k8s-node01  Container image "hushensong.com/library/myapp:v1" already present on machine
  Normal   Created    2m53s (x4 over 3m29s)   kubelet, k8s-node01  Created container nginx
  Normal   Started    2m53s (x4 over 3m29s)   kubelet, k8s-node01  Started container nginx
  Normal   Killing    2m53s (x3 over 3m17s)   kubelet, k8s-node01  Container nginx failed liveness probe, will be restarted
  Warning  Unhealthy  2m47s (x10 over 3m23s)  kubelet, k8s-node01  Liveness probe failed: dial tcp 10.244.1.6:8080: connect: connection refused

探针就绪检测和存活检测是可以同时配置在文件中的,如下演示所示:

[root@k8s-master pod]# vim live-httpget-pod.yaml 
apiVersion: v1
kind: Pod
metadata:
  name: liveness-httpget-pod
  namespace: default
spec:
  containers:
  - name: liveness-httpget-container
    image: hushensong.com/library/myapp:v1
    imagePullPolicy: IfNotPresent
    ports:
    - name: http
      containerPort: 80
    readinessProbe:
      httpGet:
        port: 80
        path: /index1.html
      initialDelaySeconds: 1
      periodSeconds: 3
    livenessProbe:
      httpGet:
        port: http
        path: /index.html
      initialDelaySeconds: 1
      periodSeconds: 3
      timeoutSeconds: 10

[root@k8s-master pod]# kubectl create -f live-httpget-pod.yaml 
pod/liveness-httpget-pod created

[root@k8s-master pod]# kubectl get pod
NAME                   READY   STATUS    RESTARTS   AGE
liveness-httpget-pod   0/1     Running   0          16s

[root@k8s-master pod]# kubectl exec liveness-httpget-pod  -it -- /bin/sh
/ # cd /usr/share/nginx/html/
/usr/share/nginx/html # ls
50x.html    index.html

/usr/share/nginx/html # echo "123"  > index1.html

[root@k8s-master pod]# kubectl get pod
NAME                   READY   STATUS    RESTARTS   AGE
liveness-httpget-pod   1/1     Running   0          92s

[root@k8s-master pod]# kubectl exec liveness-httpget-pod  -it  -- rm -rf /usr/share/nginx/html/index.html

[root@k8s-master pod]# kubectl get pod -w
NAME                   READY   STATUS    RESTARTS   AGE
liveness-httpget-pod   1/1     Running   0          2m26s
liveness-httpget-pod   0/1     Running   1          2m28s



说明:在就绪检测时,由于没有index1.yaml文件,所以READY一直未为0,创建index1.html文件后,pod状态正常,当删除文件index.html后,存活检测失败,对pod进行重启

6、容器启动、退出动作

[root@k8s-master pod]# vim post.yaml
apiVersion: v1
kind: Pod
metadata:
  name: lifecycle-demo
spec:
  containers:
  - name: lifecycle-demo-container
    image: hushensong.com/library/myapp:v1
    lifecycle:
      postStart:
        exec:
          command: ["/bin/sh","-c","echo Hello from the postStart Handler > /usr/share/message"]
      preStop:
        exec:
          command: ["/bin/sh","-c","echo Hello from the poststop handler > /usr/share/message"]

[root@k8s-master pod]# kubectl  create -f post.yaml 
pod/lifecycle-demo created

[root@k8s-master pod]# kubectl get pod
NAME             READY   STATUS    RESTARTS   AGE
lifecycle-demo   1/1     Running   0          6s

[root@k8s-master pod]# kubectl exec lifecycle-demo  -it  -- /bin/sh

/ # cat /usr/share/message
Hello from the postStart Handler

说明:在启动时在/usr/share/mesage中增加内容。

7、其它

1)hook

Pod hook(钩子)时有Kubernetes管理的kubelet发起的,当容器中的进程启动前或者容器中的进程终止之前运行,这是包含在容器的生命周期之中。可以同时为Pod中的所有容器都配置hook。

Hook的类型包括两种:

  • exec:执行一段命令
  • HTTP:发送HTTP请求

2)重启策略

podSpec中有一个restartPolicy字段,可能的值为Always、OnFailure和Never。默认为Always。restartPolicy适用于pod中的所有容器。restartPolicy仅指通过同一节点上的kubelet重新启动容器。失败的容器由kubelet以五分钟为上限的指数退避延迟(10秒,20秒,40秒...)重新启动,并在成功执行十分钟后重置。如Pod文档中所述,一旦绑定到一个节点,Pod将永远不会重新绑定到另一个节点。

3)pod相位(phase)

Pod的status字段是一个podstatus对象,podstatus中有一个phase字段。

pod的相位(phase)是pod在其生命周期中的简单宏观概述。该阶段并不是对容器或pod的综合汇总,也不是为了做为综合状态机。

Pod相位的数量和含义是严格指定的。除了本文档中列举的状态外,不应该再假定pod有其他的phase值。

那么phase有哪些可能存在的状态呢

挂起(Pending):Pod已被kubernetes系统接受,但有一个或者多个容器镜像尚未创建。等待时间包括调度Pod的时间和通过网络下载镜像的时间,这可能需要花点时间。

运行中(Running):该Pod已经绑定到了一个节点上,Pod中所有的容器都已被创建。至少有一个容器正在运行,或者正处于启动或重启状态。

成功(Succeeded):Pod中的所有容器都被成功终止,并且不会再重启。

失败(Failed):Pod中的所有容器都已终止了,并且至少有一个容器是因为失败终止。也就是说,容器以非0状态退出或者被系统终止。

未知(Unknown):因为某些原因无法取得Pod的状态,通常是因为与Pod所在的主机通信失败。


Hello,大家好,我是菜鸟HSS,始终坚信没有天生的高手,更没有永远的菜鸟。专注于Linux云计算和大数据的学习和研究。欢迎扫码关注我的公众号「菜鸟自学大数据Hadoop」,本公众号一切分享、资源皆免费,希望能尽自己一己之力帮助到更多的朋友,同时自己的技术也能得到提升,达到一种双赢的效果。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值