k8s pod 细节

1、pod容器拉取策略 imagePullPolicy

imagePullPolicy: Always       // 总是拉取 pull
imagePullPolicy: IfNotPresent // 默认值,本地有则使用本地镜像,不拉取
imagePullPolicy: Never        // 只使用本地镜像,从不拉取

2、pod生命周期(状态)

pending , running, succeeded, failed, unknown

挂起(Pending):Pod 已被 Kubernetes 系统接受,但有一个或者多个容器镜像尚未创建。等待时间包括调度 Pod 的时间和通过网络下载镜像的时间,这可能需要花点时间。
运行中(Running):该 Pod 已经绑定到了一个节点上,Pod 中所有的容器都已被创建。至少有一个容器正在运行,或者正处于启动或重启状态。
成功(Succeeded):Pod 中的所有容器都被成功终止,并且不会再重启。
失败(Failed):Pod 中的所有容器都已终止了,并且至少有一个容器是因为失败终止。也就是说,容器以非0状态退出或者被系统终止。
未知(Unknown):因为某些原因无法取得 Pod 的状态,通常是因为与 Pod 所在主机通信失败。

3、pod重启策略

当某个容器异常退出或者健康检查失败, kubelet将根据RestartPolicy的设置来进行相应的操作, 重启策略有Always , OnFailure, Never

Always: 当容器失效时, 由kubelet自动重启该容器
OnFailure: 当容器终止运行且退出码不为0时, 由kubelet自动重启该容器
Never: 不论容器运行状态如何, kubelet都不会重启该容器

kubelet重启失效容器的时间间隔以sync-frequency乘以2n来计算, 例如1丶2丶4丶8倍等, 最长延时5min, 并且在重启后的10min后重置该时间
pod的重启策略与控制方式息息相关

RC和DeamonSet必须设置为Always,需要保证该容器持续运行
Job: OnFailure或Never, 确保容器执行完成后不再重启

4、示例

apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx-deployment
spec:
  replicas: 1
  template:
    spec:
      restartPolicy: Always # pod重启策略
      containers:
      - name: nginx
        image: nginx:latest
        imagePullPolicy: IfNotPresent # 镜像拉取策略
        ports:
        - containerPort: 80

5、pod健康检查

容器探针: kubelet 对容器执行的定期诊断

探针执行方式

LivenessProbe:  判断容器是否存活 running状态, 如果不健康kubelet就会杀掉pod,根据重启策略RestartPolicy进行相应的处理
ReadinessProbe: 判断容器是否处于可用Ready状态, 达到ready状态表示pod可以接受请求,  如果不健康, 从service的后端endpoint列表中把pod隔离出去

诊断方式

ExecAction(exec):容器内执行指定命令,状态由命令执行完返回的状态码确定。如果命令退出时返回码为 0 则认为健康,返回非零值,则kubelet会终止容器并重新启动它。
TCPSocketAction(tcpSocket):对指定端口上的容器的 IP 地址进行 TCP 检查。如果端口打开,则诊断被认为是成功的。
HTTPGetAction(httpGet):(推荐使用)对指定的端口和路径上的容器的 IP 地址执行 HTTP Get 请求。如果响应的状态码大于等于200 且小于 400,则诊断被认为是成功的。

参数说明

initialDelaySeconds:容器启动后第一次执行探测是需要等待多少秒。
periodSeconds:执行探测的频率。默认是10秒,最小1秒。
timeoutSeconds:探测超时时间。默认1秒,最小1秒。
successThreshold:探测失败后,最少连续探测成功多少次才被认定为成功。默认是1。对于liveness必须是1。最小值是1。
failureThreshold:探测成功后,最少连续探测失败多少次才被认定为失败。默认是3。最小值是1。
HTTP probe 中可以给 httpGet设置其他配置项:

端口使用说明

ports:
- name: liveness-port
  containerPort: 8080
  hostPort: 8080

livenessProbe:
  httpGet:
  path: /healthz
  port: liveness-port  # 使用命名的ContainerPort作为HTTP或TCP liveness检查:

方式1 ExecAction

apiVersion: apps/v1
kind: Deployment
metadata:
  name: busybox-deployment
spec:
  replicas: 1
  template:
    spec:
      containers:
      - name: busybox
        image: busybox:1.28.4
        imagePullPolicy: IfNotPresent
        ports:
        - containerPort: 80
        args: ["/bin/sh","-c","touch /tmp/healthy;sleep 30; rm -f /tmp/healthy; sleep 3600"]
        livenessProbe:
          exec:
            command: ["cat","/tmp/healthy"]  # /tmp/healthy 文件
          initialDelaySeconds: 5
          periodSeconds: 5
        readinessProbe:
          exec:
            command: ["cat","/tmp/ready"] # /tmp/ready 文件
          initialDelaySeconds: 5
          periodSeconds: 5
运行探测结果
kubectl describe pod busybox-deployment

FirstSeen LastSeen    Count   From            SubobjectPath           Type        Reason      Message
--------- --------    -----   ----            -------------           --------    ------      -------
37s       37s     1   {default-scheduler }                    Normal      Scheduled   Successfully assigned liveness-exec to worker0
36s       36s     1   {kubelet worker0}   spec.containers{liveness}   Normal      Pulling     pulling image "busybox"
36s       36s     1   {kubelet worker0}   spec.containers{liveness}   Normal      Pulled      Successfully pulled image "busybox"
36s       36s     1   {kubelet worker0}   spec.containers{liveness}   Normal      Created     Created container with docker id 86849c15382e; Security:[seccomp=unconfined]
36s       36s     1   {kubelet worker0}   spec.containers{liveness}   Normal      Started     Started container with docker id 86849c15382e
2s        2s      1   {kubelet worker0}   spec.containers{liveness}   Warning     Unhealthy   Liveness probe failed: cat: can't open '/tmp/healthy': No such file or directory
失败后的重启
kubectl get pod
NAME                 READY     STATUS    RESTARTS   AGE
busybox-deployment   1/1       Running   1          1m    # RESTARTS 增加了1

方式2 TCPSocketAction

apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx-deployment
spec:
  replicas: 1
  template:
    spec:
      containers:
      - name: nginx
        image: nginx
        imagePullPolicy: IfNotPresent
        ports:
        - containerPort: 80
        
        
        livenessProbe:
          tcpSocket:
            port: 80
          initialDelaySeconds: 5
          periodSeconds: 3
        readinessProbe:
          tcpSocket:
            port: 80
          initialDelaySeconds: 5
          periodSeconds: 3

方式3 HTTPGetAction

参数说明
host:连接的主机名,默认连接到pod的IP。你可能想在http header中设置"Host"而不是使用IP。
scheme:连接使用的schema,默认HTTP。
path: 访问的HTTP server的path。linenessProbe建议使用 /health   readinessProbe 建议使用/ready
httpHeaders:自定义请求的header。HTTP运行重复的header。
port:访问的容器的端口名字或者端口号。端口号必须介于1和65535之间。
示例
apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx-deployment
spec:
  replicas: 1
  template:
    spec:
      containers:
      - name: nginx
        image: nginx
        imagePullPolicy: IfNotPresent
        ports:
        - containerPort: 
        
        livenessProbe:
          httpGet:
            path: /health
            port: 8090
            httpHeaders:
            - name: X-Custom-Header
              value: hello
          initialDelaySeconds: 5  # first wait time
          periodSeconds: 3        # probe interval
        readinessProbe:
          httpGet:
            path: /ready
            port: 80
            httpHeaders:
            - name: X-Custom-Header
              value: hello
          initialDelaySeconds: 5
          periodSeconds: 3