
正如前几天提及Kubernetes可以侦测到pod的生命周期去调整Kubernetes cluster中其它组件的状态。然而有些时候,虽然pod还在运行,但在pod中的web app container可能因为某些原因已经停止运行,或是资源被其它container占用,导致我们发送的request无法正常回应。幸好,Kubernetes也帮我们想到这点了,它提供health check帮我们去侦测pod中container是否都还正常运行,确保服务本身也能正常运行。
今天的学习笔记内容如下:
Kubernetes中的health check有哪些
实操: 如何在pod中加入health check
小提醒: 今天的源代码都可以在demo-health-check上找到。
在Kubernetes,有两种常见的health check,
定期的通过命令去访问container,
定期发送一个http request给container
如果我当我们设定的health check检测到异常时,Kubernetes会restart container,确保应用服务可正常运行(available)。
在今天的实操中,我们将使用my-deployment-with-health-check.yaml来创建一个Deployment对象,并通过定期发送一个HTTP request给container的方式,来判断目前web app container是否还正常运行。
my-deployment-with-health-checks.yaml 内容如下:
apiVersion: apps/v1beta2 # for kubectl versions >= 1.9.0 use apps/v1 kind: Deployment metadata: name: hello-deployment spec: replicas: 3 selector: matchLabels: app: my-deployment template: metadata: labels: app: my-deployment spec: containers: - name: webapp image: demouser/docker-demo ports: - name: webapp-port containerPort: 3000 livenessProbe: httpGet: path: / port: webapp-port initialDelaySeconds: 15 periodSeconds: 15 timeoutSeconds: 30 successThreshold: 1 failureThreshold: 3
可以看到在my-deployment-with-health-check.yaml中多了livenessProbe设置。
在 livenessProbe 中我们可以做以下设置,
httpGet.path
设置health check要访问的路径
httpGet.port
制定我们要访问的port,这里port number是3000
initialDelaySeconds
设置service刚启动时,要延迟几秒再开始做health check
periodSeconds
代表每隔几秒访问一次,默认值为10s
successThreshold
可以设置访问几次就代表目前service还正常运行
failureThreshold
代表service返回值不符合预期时,在Kubernetes放弃该container之前,会尝试的次数,默认为3次。
通常在实际场景中(production environment),我们会有一个专门来响应health check的endpoint,例如/health来确认application是否在正常运行。
在了解livenessProbe的各项配置项之后,我们可以在终端输入kubectl create命令,创建一个名为hello-deployment的对象。
$ kubectl create -f ./my-deployment-with-health-checks.yaml deployment "hello-deployment" created
接着,通过kubectl get来查看hello-deployment,
$ kubectl get deploy NAME DESIRED CURRENT UP-TO-DATE AVAILABLE AGE hello-deployment 3 3 3 3 23s
以及pod的状态,
$ kubectl get pod NAME READY STATUS RESTARTS AGE hello-deployment-6d56dd6494-9sckr 1/1 Running 0 1m hello-deployment-6d56dd6494-kgm8c 1/1 Running 0 1m hello-deployment-6d56dd6494-mx5jk 1/1 Running 0 1m
我们可以使用kubectl describe看其中一个pod的详细信息,以hello-deployment为例,
$ kubectl describe pod hello-deployment-6b56dd6494-mx5jk
可以在liveness列里面,清楚看到目前health check的设置状态。当container无法正常响应health check时,Kubernetes就会视为该container失去功能并重启。
虽然今天的学习笔记只有分享,如何设置定期访问的http request;然而 使用命令或TCP定期访问服务也是health check常见的方式。若有兴趣的读者,不妨参考官方提供的范例 ,相信也会有所收获!