公司网站运营方案策划,咸阳市建设银行网站,做网站 框架,企业级服务器配置前言
k8s中的Pod由容器组成#xff0c;容器运行的时候可能因为意外情况挂掉。为了保证服务的稳定性#xff0c;在容器出现问题后能进行重启#xff0c;k8s提供了3种探针
k8s的三种探针
为了探测容器状态#xff0c;k8s提供了两个探针: LivenessProbe和ReadinessProbe
L…前言
k8s中的Pod由容器组成容器运行的时候可能因为意外情况挂掉。为了保证服务的稳定性在容器出现问题后能进行重启k8s提供了3种探针
k8s的三种探针
为了探测容器状态k8s提供了两个探针: LivenessProbe和ReadinessProbe
LivenessProbe 存活性探针, 如果探测失败, 就根据Pod重启策略判断是否要重启容器。ReadinessProbe 就绪性探针如果检测失败将Pod的IP:Port从对应endpoint列表中删除防止流量转发到不可用Pod上
对于启动非常慢的应用, LivenessProbe和ReadinessProbe可能会一直检测失败这会导致容器不停地重启。 所以k8s设计了第三种探针StartupProbe解决这个问题
StartupProbe探针会阻塞LivenessProbe和ReadinessProbe, 直到满足StartupProbe(Pod完成启动)再启用LivenessProbe和ReadinessProbe LivenessProbe和ReadinessProbe支持三种探测方法
ExecAction 容器中执行指定的命令退出码为0表示探测成功。HTTPGetAction 通过HTTP GET请求容器如果HTTP响应码在【200400)认为容器健康。TCPSocketAction 通过容器的IP地址和端口号执行TCP检查。如果建立TCP链接则表明容器健康。
可以给探针配置可选字段用来更精确控制LivenessProbe和ReadinessProbe的行为
initialDelaySeconds: 容器启动后等待多少秒后探针才开始工作默认是0秒periodSeconds: 执行探测的时间间隔默认为10秒timeoutSeconds: 探针执行检测请求后等待响应的超时时间默认为1秒failureThreshold: 探测失败的重试次数重试一定次数后认为失败。successThreshold: 探针在失败后被视为成功的最小连续成功数。默认值是 1。 存活和启动探测的这个值必须是 1。最小值是 1。
实例: 添加一个LivenessProbe探针
需求: 给Squid Pod添加一个livenessProbe, 每隔10秒检测一次Squid进程启动状态如果连续3次检测进程异常, 就重启Pod
首先创建一个Squid Pod, 参考: 【k8s实践】 部署Squid
添加一个ExecAction类型的livenessProbe探针
可以通过squid -k check命令检测Squid进程运行状态返回0说明正常, 返回非0值说明进程异常。 实例: 定义一个ExecAction类型的livenessProbe, deployment配置如下:
containers:- name: squidlivenessProbe:exec:command: [squid,-k,check]initialDelaySeconds: 5periodSeconds: 10failureThreshold: 3完整的squid-deployment.yaml如下:
apiVersion: apps/v1
kind: Deployment
metadata:name: squidnamespace: squidlabels:name: squid
spec:replicas: 1selector:matchLabels:app: squidtemplate:metadata:labels:app: squidspec:volumes:- name: squid-volumepersistentVolumeClaim:claimName: squid-claimdnsPolicy: ClusterFirstWithHostNethostNetwork: truecontainers:- name: squidimage: squid:2.0imagePullPolicy: IfNotPresentlivenessProbe: # 添加一个ExecAction类型的探针exec:command: [squid,-k,check] # 如果Squid进程运行, squid -k check返回0; 否则返回非0值initialDelaySeconds: 5periodSeconds: 10failureThreshold: 3resources:limits:memory: 4GivolumeMounts:- mountPath: /var/log/squidname: squid-volume重新部署deployment, 通过kubectl -n squid get deploy squid -o yaml, 确认探针已配置到deployment.
测试 kubectl exec进入容器, 使用squid -k shutdown手动停止Squid。 等30秒左右可以观察到容器自动退出重启, 并且从日志中能看到健康检测失败结果:
[rootk8s-master ~]# kubectl -n squid exec -it squid-8674587b79-29mq8 -- /bin/bash
[rootk8s-master /]# squid -k shutdown
...
[rootk8s-master /]# squid -k check
2024/12/14 04:53:31| FATAL: failed to open /run/squid.pid: (2) No such file or directoryexception location: File.cc(190) open
[rootk8s-master /]# echo $?
1# 等待半分钟左右, 容器自动退出
[rootk8s-master /]# command terminated with exit code 137
[rootk8s-master ~]## 此时宿主机上查看Pod发现RESTARTS次数变为1
[rootk8s-master /]# kubectl -n squid get pods
squid squid-8674587b79-29mq8 1/1 Running 1 (45s ago) 11m# 通过kubectl describe可以查到探针检测失败的LOGkubectl -n squid describe pod squid-8674587b79-29mq8 | grep UnhealthyWarning Unhealthy 2m49s kubelet Liveness probe failed: 2024/12/14 04:53:19| FATAL: failed to open /run/squid.pid: (2) No such file or directoryWarning Unhealthy 2m39s kubelet Liveness probe failed: 2024/12/14 04:53:29| FATAL: failed to open /run/squid.pid: (2) No such file or directoryWarning Unhealthy 2m29s kubelet Liveness probe failed: 2024/12/14 04:53:39| FATAL: failed to open /run/squid.pid: (2) No such file or directory添加一个HttpGet类型的livenessProbe探针
HttpGet探针要求Pod里有一个HTTP的server。 例如请求http://localhost:5000/healthz 探测Pod健康状态deployment设置如下
livenessProbe:httpGet:path: /healthzport: 5000initialDelaySeconds: 5periodSeconds: 10failureThreshold: 3在Pod里写一个HTTP的server, 我这里用的Flask
#!/usr/bin/env python3# logging
import logging
logger logging.getLogger(__name__)
file_handler logging.FileHandler(/var/log/squid/agent.log)
formatter logging.Formatter(%(asctime)s - %(name)s - %(levelname)s - %(message)s)
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)import subprocess
import traceback# Flask
from flask import Flask, jsonify, request
app Flask(__name__)app.route(/healthz, methods[GET])
def health_check():retCode 0try:result subprocess.run([/usr/sbin/squid, -k, check])retCode result.returncodeif retCode 0:return (jsonify({code: 0, msg: OK}), 200)except:logger.error(health_check %r, traceback.format_exc())return (jsonify({code: -1, msg: Fail, msg: Service Unavailable}), 500)return (jsonify({code: retCode, msg: Fail}), 400)if __name__ __main__:app.run(host0.0.0.0, port5000)再把脚本做到镜像里安装python3和pip依赖(flask,requests),重新打包部署
测试
curl localhost:5000/healthz
{code:0,msg:OK}参考
[1] Correct use of k8s probe [2] Configure Liveness, Readiness and Startup Probes