应用在运行过程不可避免会出现各种问题导致服务不可用的情况发生,K8S的Health Check健康检查机制可以对这些异常服务进行重启、剔除等操作,保障高可用。

一、K8S的健康检查探针

K8S的探针主要有3种,主要是探测的阶段不同:

1、readiness probes:容器就绪检查,用于检查容器是否能接收到流量,只有当状态正常才会加入到services中

2、liveness probes:在线检查机制,用于检查应用是否可用,如出现无法响应、死锁等异常时自动重启容器,能一定程度实现运维自动化

3、starup probes:启动检查机制,避免一些需要长时间启动的容器被前面的探针杀掉。该探针排在首位,直到它工作完成才会进行另外2种探针的探测

二、K8S探针工作方式

1、exec方式:设置一个命令作为探查命令,对其返回结果做判断

该示例会创建⼀个容器,容器启动时创建/tmp/liveness-probe.log,然后10秒后将其删除。通过liveness探针的exec方法去执行命令ls -l /tmp/liveness-probe.log,通过⽂件返回码判断健康状态。如果返回码⾮0会⾃动将该容器重启

cat centos-exec-liveness-probe.yaml
apiVersion: v1
kind: Pod
metadata:
  name: exec-liveness-probe
  annotations:
    kubernetes.io/description: "exec-liveness-probe"
spec:
  containers:
    - name: exec-liveness-probe
      image: centos:latest
      imagePullPolicy: IfNotPresent
      args: #容器启动命令,⽣命周期为30s
      - /bin/sh
      - -c
      - touch /tmp/liveness-probe.log && sleep 10 && rm -f /tmp/liveness-probe.log && sleep 20
      livenessProbe:
        exec: #健康检查机制,通过ls -l /tmp/liveness-probe.log返回码判断容器的健康状态
          command:
          - ls
          - l
          - /tmp/liveness-probe.log
        initialDelaySeconds: 1  #初始探测时间,可以设大一点,防止应用还没启动就被认作失败
        periodSeconds: 5  #每次探测间隔
        timeoutSeconds: 1  #探测超时时间,超时则失败

2、httpGet方式:主要⽤于web场景,对容器内指定的URL发送http请求,然年后根据返回码判断容器健康状态,返回码⼩于4xx即表示健康: 

# 定义⼀个nginx应⽤,通过探测http://:port/index.html的⽅式判断健康状态
cat nginx-httpGet-liveness-readiness.yaml
apiVersion: v1
kind: Pod
metadata:
  name: nginx-httpget-livess-readiness-probe
  annotations:
  kubernetes.io/description: "nginx-httpGet-livess-readiness-probe"
spec:
  containers:
    - name: nginx-httpget-livess-readiness-probe
    image: nginx:latest
    ports:
      - name: http-80-port
      protocol: TCP
      containerPort: 80
  livenessProbe: #健康检查机制,通过httpGet实现实现检查
    httpGet:
      port: 80
      scheme: HTTP
      path: /index.html
    initialDelaySeconds: 3
    periodSeconds: 10
    timeoutSeconds: 3

3、tcp连接:以能否与容器建立tcp连接为判断 

 

 

Logo

K8S/Kubernetes社区为您提供最前沿的新闻资讯和知识内容

更多推荐