k8s从入门到放弃之Pod的容器探针检测
在Kubernetes(简称K8s)中,容器探测是指kubelet对容器执行定期诊断的过程,以确保容器中的应用程序处于预期的状态。这些探测是保障应用健康和高可用性的重要机制。Kubernetes提供了两种种类型的探针:存活探针(liveness probes)、就绪探针(readiness probes)
存活探针
资源文档:kubectl explain deploy.spec.template.spec.containers.livenessProbe
livenessProbe:存活探针用于检测容器中的应用是否还在正常运行。如果探测失败,说明容器不健康,kubelet 会杀死该容器,并根据重启策略决定是否重启容器,从而帮助恢复异常的容器。
探测方式:
- exec : 在容器内部执行一个命令,若命令返回结果为 0,则认为探测成功。
- httpGet: 向容器指定路径发起 HTTP 请求,若返回状态码在 200-399 之间,则认为探测成功。
- tcpSocket:尝试与容器的指定端口建立 TCP 连接,若连接成功,则认为探测成功。
存活探针exec案例
apiVersion: apps/v1
kind: Deployment
metadata:
name: nginx
namespace: 21du
spec:
selector:
matchLabels:
app: nginx
template:
metadata:
labels:
app: nginx
spec:
tolerations:
- key: node
operator: "Exists"
effect: NoSchedule
containers:
- name: nginx
image: nginx:1.20.0
livenessProbe:
exec:
command:
- ls
- /usr/share/nginx/html/index.html
ports:
- containerPort: 80
存活探针httpGet案例
apiVersion: apps/v1
kind: Deployment
metadata:
name: nginx
namespace: 21du
spec:
selector:
matchLabels:
app: nginx
template:
metadata:
labels:
app: nginx
spec:
tolerations:
- key: node
operator: "Exists"
effect: NoSchedule
containers:
- name: nginx
image: nginx:1.20.0
livenessProbe:
httpGet:
port: 80
path: /
ports:
- containerPort: 80
存活探针tcpSocket案例
apiVersion: apps/v1
kind: Deployment
metadata:
name: nginx
namespace: 21du
spec:
selector:
matchLabels:
app: nginx
template:
metadata:
labels:
app: nginx
spec:
tolerations:
- key: node
operator: "Exists"
effect: NoSchedule
containers:
- name: nginx
image: nginx:1.20.0
livenessProbe:
tcpSocket:
port: 80
ports:
- containerPort: 80
就绪探针
资源文档:kubectl explain deploy.spec.template.spec.containers.readinessProbe
readinessProbe:就绪探针用于判断容器是否已经准备好接收请求。如果探测失败,Kubernetes会暂停将流量转发给该容器,并将其从服务的负载均衡池中移除,直到探测成功为止。这适用于需要初始化时间或依赖外部服务的应用,防止它们在未准备好的状态下接收请求。
探测方式:
- exec : 在容器内部执行一个命令,若命令返回结果为 0,则认为探测成功。
- httpGet: 向容器指定路径发起 HTTP 请求,若返回状态码在 200-399 之间,则认为探测成功。
- tcpSocket:尝试与容器的指定端口建立 TCP 连接,若连接成功,则认为探测成功。
就绪探针exec案例
apiVersion: apps/v1
kind: Deployment
metadata:
name: redis
namespace: 21du
spec:
selector:
matchLabels:
app: db
template:
metadata:
labels:
app: db
spec:
containers:
- name: redis
image: redis:6.0
readinessProbe:
exec:
command:
- ls
- /etc/os-release
ports:
- containerPort: 6379
就绪探针httpGet案例
apiVersion: apps/v1
kind: Deployment
metadata:
name: nginx
namespace: 21du
spec:
selector:
matchLabels:
app: web
template:
metadata:
labels:
app: web
spec:
containers:
- name: nginx
image: nginx:1.20.0
readinessProbe:
httpGet:
port: 80
path: /
ports:
- containerPort: 80
就绪探针tcpSocket案例
apiVersion: apps/v1
kind: Deployment
metadata:
name: redis
namespace: 21du
spec:
selector:
matchLabels:
app: db
template:
metadata:
labels:
app: db
spec:
containers:
- name: redis
image: redis:6.0
readinessProbe:
tcpSocket:
port: 6379
ports:
- containerPort: 6379