第19章学习笔记

78 阅读2分钟

k8s 核心资源 Pod-健康探测之存活探测

Liveness Probe(存活探测) 用于检测 pod 内的容器是否处于运行状态. 当 Liveness Probe 探测失败时, k8s 根据重启策略决定是否重启该容器. 适用于需要在容器发生故障时立即进行重启的应用场景, 比如 Web 服务器和数据库等应用.

Readiness Probe(就绪探测): 用于检测 pod 中的容器是否已经准备好接收流量, 即容器是否已经完成初始化并已经启动了应用程序. 当容器的 Readiness Probe 探测失败时, k8s 强停止将新的流量转发到该容器. 适用于需要应用程序启动较长时间的应用场景, 比如大型 Web 应用程序.

  • kubectl explain pods.spec.containers.livenessProbe: 查看存活探测配置帮助信息.
  • pods.spec.containers 下还有其他探测的配置帮助信息可供查看.

下面这个资源清单演示了如何设置存活探测和就绪探测:

apiVersion: v1
kind: Pod
metadata:
  name: liveness-http
  labels:
    app: nginx
spec:
  containers:
  - name: liveness
    image: nginx
    imagePullPolicy: IfNotPresent
    ports:
    - containerPort: 80
    livenessProbe:
      initialDelaySeconds: 5   #延迟加载时间
      periodSeconds: 10        #重试时间间隔
      timeoutSeconds: 10        #超时时间设置
      httpGet:
        port: 80
        path: /index.html
    readinessProbe:
      httpGet:
        path: /index.html
        port: 80
      initialDelaySeconds: 5
      periodSeconds: 3
  restartPolicy: Always

  • kubectl get pods -l app=nginx -w: 查看 pod 状态.
  • kubectl exec -it liveness-http -- /bin/bash: 进入到容器终端中. 如果删除了 /usr/share/nginx/html/index.html 则会发现存活探测失败.

k8s 核心资源 Pod-健康探测之就绪探测

tcp 方式探测资源清单文件内容如下:

apiVersion: v1
kind: Pod
metadata:
  name: liveness-tcp
  labels:
    app: nginx
spec:
  containers:
  - name: liveness
    image: nginx
    imagePullPolicy: IfNotPresent
    ports:
    - containerPort: 80
    livenessProbe:
      initialDelaySeconds: 5   #延迟加载时间
      periodSeconds: 10        #重试时间间隔
      timeoutSeconds: 10        #超时时间设置
      tcpSocket:
        port: 80

对于 web 服务来说使用 tcp 进行探测不太友好, tcp 端口打开有时并不意味着服务可用. 在其中执行 nginx -s stop 停止 nginx 服务才能检测到服务已停止.

存活探测资源清单如下:

apiVersion: v1
kind: Pod
metadata:
  name: my-pod
  labels:
    app: my-pod
spec:
  containers:
  - name: nginx-container
    image: nginx
    imagePullPolicy: IfNotPresent
    ports:
    - containerPort: 80
    readinessProbe:
      httpGet:
        path: /index.html
        port: 80
      initialDelaySeconds: 60
      periodSeconds: 3
      failureThreshold: 2
      successThreshold: 1

创建服务配置文件 readiness-svc.yaml, 服务目前还没有讲, 只是提到了它可以将请求代理给 pod. 这里先简单的了解一下.

  • kubectl explain svc: 查看服务包含的字段帮助文档.
apiVersion: v1
kind: Service
metadata:
  name: readiness
spec:
  selector:
    app: my-pod
  ports:
  - port: 80
    targetPort: 80
  • kubectl describe svc readiness: 查看服务信息.
  • kubectl get svc: 获取所有服务信息简介.