Docker Kubernetes 健康检查
- 官方文档:https://kubernetes.io/docs/tasks/configure-pod-container/configure-liveness-readiness-probes/
提供Probe探测机制,有以下两种类型:
- livenessProbe:如果检查失败,将杀死容器,然后根据Pod的重启策略来决定是否重启(根据Pod的restartPolicy来操作)。
- readinessProbe:如果检查失败,Kubernetes会把Pod从服务代理的分发后端剔除。
Probe支持以下三种检查方法:
- httpGet
- 发送HTTP请求,返回200-400范围状态码为成功。
- exec
- 执行Shell命令返回状态码是0为成功。
- tcpSocket
- 发起TCP Socket建立成功。判断端口有没有打开
环境:
- 系统:Centos 7.4 x64
- Docker版本:18.09.0
- Kubernetes版本:v1.8
- 管理节点:192.168.1.79
- 工作节点:192.168.1.78
- 工作节点:192.168.1.77
案例一
1、管理节点:创建yaml文件
vim check.yaml
apiVersion: v1
kind: Pod
metadata:
name: nginx-pod
labels:
app: nginx
spec:
containers:
- name: nginx
image: nginx:1.10
ports:
- containerPort: 80
livenessProbe:
httpGet:
path: /index.html
port: 80
# api版本
apiVersion: v1
# 指定创建资源对象
kind: Pod
# 源数据、可以写name,命名空间,对象标签
metadata:
# 服务名称
name: nginx-pod
# 标签
labels:
# 标签名
app: nginx
# 容器资源信息
spec:
# 容器管理
containers:
# 容器名称
- name: nginx
# 容器镜像
image: nginx:1.10
# 端口管理
ports:
# 指定暴露端口
- containerPort: 80
# 健康检查模式(httpGet、exec、tcpSocket)
livenessProbe:
# 选择健康检查类型
httpGet:
# 选择检查文件
path: /index.html
# 选择检查暴露端口
port: 80
文件注释
2、管理节点:创建Pod
kubectl create -f check.yaml
命令:kubectl describe pods nginx-pod # 探测端口为80,探测文件名index.html,timeout超市时间为一秒,period每10秒探测一次
Liveness: http-get http://:80/index.html delay=0s timeout=1s period=10s #success=1 #failure=3
查看健康检查pod状态
案例二
语法格式
# 语法格式
apiVersion: v1
kind: Pod
metadata:
labels:
test: liveness
name: liveness-exec
spec:
containers:
- name: liveness
image: k8s.gcr.io/busybox
args:
- /bin/sh
- -c
- touch /tmp/healthy; sleep 30; rm -rf /tmp/healthy; sleep 600
livenessProbe:
exec:
command:
- cat
- /tmp/healthy
# 在容器启动五秒之后开始执行健康检查
initialDelaySeconds: 5
# 每隔多长时间执行一次
periodSeconds: 5
1、通过官方实例测试健康检查
apiVersion: v1
kind: Pod
metadata:
labels:
test: liveness
name: liveness-exec
spec:
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: 5
periodSeconds: 5
vim pod4.yaml
2、执行
kubectl create -f pod4.yaml
3、查看测试
kubectl get pods
经过一段时间检查重启
4、查看事件
kubectl describe pod liveness-exec
....
Events:
Type Reason Age From Message
---- ------ ---- ---- -------
Normal Scheduled 5m8s default-scheduler Successfully assigned default/liveness-exec to 192.168.1.110
Normal Pulled 2m35s (x3 over 5m7s) kubelet, 192.168.1.110 Successfully pulled image "busybox"
Normal Created 2m35s (x3 over 5m6s) kubelet, 192.168.1.110 Created container
Normal Started 2m34s (x3 over 5m6s) kubelet, 192.168.1.110 Started container
Warning Unhealthy 112s (x9 over 4m32s) kubelet, 192.168.1.110 Liveness probe failed: cat: can't open '/tmp/healthy': No such file or directory
Normal Pulling 81s (x4 over 5m7s) kubelet, 192.168.1.110 pulling image "busybox"
Normal Killing 6s (x4 over 3m51s) kubelet, 192.168.1.110 Killing container with id docker://liveness:Container failed liveness probe.. Container will be killed and recreated.