实验手册-10-健康检查

步骤1 创建配置文件

bash

vim healthcheck-1.yaml

配置文件内容:

yaml

apiVersion: v1
kind: Pod
metadata:
  labels:
    test: healthcheck
  name: healthcheck
spec:
  restartPolicy: OnFailure
  containers:
  - name: healthcheck
    image: busybox
    args:
    - /bin/sh
    - -c
    - sleep 10; exit 1
  • restartPolicy 第8行:发生错误时重启
  • 11行:使用 busybox 镜像
  • 15行:休眠10秒后,退出,并返回 1

注:返回的 1 可以被 echo $? 被捕到

步骤2 加载配置文件

bash

kubectl apply -f healthcheck-1.yaml
成功加载文件

步骤3 验证

加载文件成功后,10秒内查看 Pods 状态,可以看到其状态STATUS为Running,重启次数 RESTARTS 为 0

bash

kubectl get pods 
前10秒

我们过几分钟再看看

bash

kubectl get pods 

可以发现,其状态和重启次数都发生了变化:

Pod发生重启

步骤1 删除任务1创建的pod

bash

kubectl delete -f healthcheck-1.yaml

步骤2 创建配置文件

bash

vim healthcheck-2.yaml

配置文件内容:

yaml

apiVersion: v1
kind: Pod
metadata:
  labels:
    test: liveness
  name: liveness
spec:
  restartPolicy: OnFailure
  containers:
  - name: liveness
    image: busybox
    args:
    - /bin/sh
    - -c
    - touch /tmp/healthy; sleep 30; rm -rf /tmp/healthy; sleep 600
    livenessProbe:
      exec:
        command:
        - cat
        - /tmp/healthy
      initialDelaySeconds: 10
      periodSeconds: 5
配置文件

步骤3 加载配置文件

bash

kubectl apply -f healthcheck-2.yaml
加载配置文件

步骤4 验证

验证1 查看 Pod

bash

kubectl get pods 
查看Pod

验证2 查看Pod的详情

bash

kubectl describe pod liveness

看命令输出的最后一部分

Pod详情中的事件部分

再看看 Pod 列表中的信息

bash

kubectl get pods
重启次数

由上图可见,Pod 已经发生两次重启

步骤1 删除上面任务中创建的 Pod

bash

kubectl delete -f healthcheck-2.yaml

步骤2 创建配置文件

bash

vim healthcheck-3.yaml

配置文件内容为:

yaml

apiVersion: v1
kind: Pod
metadata:
  labels:
    test: liveness
  name: liveness
spec:
  restartPolicy: OnFailure
  containers:
  - name: liveness
    image: busybox
    args:
    - /bin/sh
    - -c
    - touch /tmp/healthy; sleep 30; rm -rf /tmp/healthy; sleep 600
    readinessProbe:
      exec:
        command:
        - cat
        - /tmp/healthy
      initialDelaySeconds: 10
      periodSeconds: 5

与上个任务中的配置文件区别为:把第16行的 livenessProbe 改为 readinessProbe

配置文件

步骤2 加载配置文件

bash

kubectl apply -f healthcheck-3.yaml

步骤3 验证

查看Pod

bash

kubectl get pods
查看Pod

对比刚才使用 Liveness 的结果

Liveness

Liveness 重启 Pod Readiness 不重启 Pod,但会将 Ready 状态设置为 “否”