K8S 调试运行中报错的 Pod

发布于:2024-04-27 ⋅ 阅读:(28) ⋅ 点赞:(0)

开始调试有问题的 Pod

准备环境

创建一个例子用于测试:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx-deployment
  namespace: apps
spec:
  selector:
    matchLabels:
      app: nginx
  replicas: 2
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
      - name: nginx
        image: nginx
        resources:
          limits:
            memory: "128Mi"
            cpu: "500m"
        ports:
        - containerPort: 80

创建好以后查看状态

kubectl get po -n apps
NAME                                READY   STATUS    RESTARTS     AGE
nginx-deployment-765cb4ff6b-72kmj   1/1     Running   0            5m40s
nginx-deployment-765cb4ff6b-986t6   1/1     Running   0            5m40s

查看 Pod 详细状态

kubectl describe po -n apps nginx-deployment-765cb4ff6b-72kmj

这里就不再展示了,太长了。

调试 Pending 状态的 Pod

为了测试咱们手动修改Pod 请求资源,修改cpu 请求为8核心 5个副本,根据我这个集群上现有的资源最少有一个Pod是无法调度的。

[root@master01 yaml]# kubectl get po -n apps -owide
NAME                                READY   STATUS    RESTARTS     AGE     IP               NODE       NOMINATED NODE   READINESS GATES
nginx-deployment-765cb4ff6b-47jbj   1/1     Running   0            4m54s   172.18.71.17     master03   <none>           <none>
nginx-deployment-765cb4ff6b-5lzcc   1/1     Running   0            4m54s   172.29.55.36     node01     <none>           <none>
nginx-deployment-765cb4ff6b-72kmj   1/1     Running   0            31m     172.21.231.131   node02     <none>           <none>
nginx-deployment-765cb4ff6b-986t6   1/1     Running   0            31m     172.31.112.159   master01   <none>           <none>
nginx-deployment-779898f6f5-fmmph   0/1     Pending   0            4m54s   <none>           <none>     <none>           <none>
nginx-deployment-779898f6f5-p7hfw   0/1     Pending   0            4m53s   <none>           <none>     <none>           <none>

查看 nginx-deployment-779898f6f5-fmmph 没有调度的原因

kubectl describe po -n apps nginx-deployment-779898f6f5-fmmph

输出如下:

## 只是粘贴了  部分代码
Events:
  Type     Reason            Age                   From               Message
  ----     ------            ----                  ----               -------
  Warning  FailedScheduling  7m15s                 default-scheduler  0/5 nodes are available: 5 Insufficient cpu. preemption: 0/5 nodes are available: 5 No preemption victims found for incoming pod..
  Warning  FailedScheduling  104s (x2 over 7m14s)  default-scheduler  0/5 nodes are available: 5 Insufficient cpu. preemption: 0/5 nodes are available: 5 No preemption victims found for incoming pod..

提示集群中没有可用的节点,因为所有5个节点都缺乏足够的 CPU 资源来运行这个 Pod。

查看集群中发生的事件

 kubectl get events -n apps

除了 kubectl describe pod 以外,另一种获取 Pod 额外信息(除了 kubectl get pod)的方法 是给 kubectl get pod 增加 -o yaml 输出格式参数。 该命令将以 YAML 格式为你提供比 kubectl describe pod 更多的信息 —— 实际上是系统拥有的关于 Pod 的所有信息。 在这里,你将看到注解(没有标签限制的键值元数据,由 Kubernetes 系统组件在内部使用)、 重启策略、端口和卷等。

kubectl get po -n apps nginx-deployment-765cb4ff6b-47jbj -oyaml
apiVersion: v1
kind: Pod
metadata:
  annotations:
    k8tz.io/injected: "true"
    k8tz.io/timezone: Asia/Shanghai
  creationTimestamp: "2024-04-25T07:43:58Z"
  generateName: nginx-deployment-765cb4ff6b-
  labels:
    app: nginx
    pod-template-hash: 765cb4ff6b
  name: nginx-deployment-765cb4ff6b-47jbj
  namespace: apps
  ownerReferences:
  - apiVersion: apps/v1
    blockOwnerDeletion: true
    controller: true
    kind: ReplicaSet
    name: nginx-deployment-765cb4ff6b
    uid: 8b5e6ae0-c6a1-4e99-8816-f8411b4f878a
  resourceVersion: "12533713"
  uid: 58703bd6-59de-4899-aeb1-3cd2605426f7
spec:
  containers:
  - env:
    - name: TZ
      value: Asia/Shanghai
    image: nginx
    imagePullPolicy: Always
    name: nginx
    ports:
    - containerPort: 80
      protocol: TCP
    resources:
      limits:
        cpu: 500m
        memory: 128Mi
      requests:
        cpu: 500m
        memory: 128Mi
    terminationMessagePath: /dev/termination-log
    terminationMessagePolicy: File
    volumeMounts:
    - mountPath: /var/run/secrets/kubernetes.io/serviceaccount
      name: kube-api-access-8p4c2
      readOnly: true
    - mountPath: /etc/localtime
      name: k8tz
      readOnly: true
      subPath: Asia/Shanghai
    - mountPath: /usr/share/zoneinfo
      name: k8tz
      readOnly: true
  dnsPolicy: ClusterFirst
  enableServiceLinks: true
  initContainers:
  - args:
    - bootstrap
    image: quay.io/k8tz/k8tz:0.16.0
    imagePullPolicy: IfNotPresent
    name: k8tz
    resources: {}
    securityContext:
      allowPrivilegeEscalation: false
      capabilities:
        drop:
        - ALL
      seccompProfile:
        type: RuntimeDefault
    terminationMessagePath: /dev/termination-log
    terminationMessagePolicy: File
    volumeMounts:
    - mountPath: /mnt/zoneinfo
      name: k8tz
    - mountPath: /var/run/secrets/kubernetes.io/serviceaccount
      name: kube-api-access-8p4c2
      readOnly: true
  nodeName: master03
  preemptionPolicy: PreemptLowerPriority
  priority: 0
  restartPolicy: Always
  schedulerName: default-scheduler
  securityContext: {}
  serviceAccount: default
  serviceAccountName: default
  terminationGracePeriodSeconds: 30
  tolerations:
  - effect: NoExecute
    key: node.kubernetes.io/not-ready
    operator: Exists
    tolerationSeconds: 300
  - effect: NoExecute
    key: node.kubernetes.io/unreachable
    operator: Exists
    tolerationSeconds: 300
  volumes:
  - name: kube-api-access-8p4c2
    projected:
      defaultMode: 420
      sources:
      - serviceAccountToken:
          expirationSeconds: 3607
          path: token
      - configMap:
          items:
          - key: ca.crt
            path: ca.crt
          name: kube-root-ca.crt
      - downwardAPI:
          items:
          - fieldRef:
              apiVersion: v1
              fieldPath: metadata.namespace
            path: namespace
  - emptyDir: {}
    name: k8tz

检查 Pod 的日志

查看有问题的日志

kubectl logs -n apps nginx-deployment-779898f6f5-p7hfw

如果容器之前崩溃过,可以通过下面命令访问之前容器的崩溃日志:

kubectl logs --previous ${POD_NAME} ${CONTAINER_NAME}

使用容器 exec 进行调试

##  说明: -c ${CONTAINER_NAME} 是可选择的。如果 Pod 中仅包含一个容器,就可以忽略它。
kubectl exec ${POD_NAME} -c ${CONTAINER_NAME} -- ${CMD} ${ARG1} ${ARG2} ... ${ARGN}

## 进入容器
kubectl -n apps exec -it busybox-6c8989b4f7-pmwkd sh

在外面执行容器中的命令

kubectl exec cassandra -- cat /var/log/cassandra/system.log

使用临时容器调试

当由于容器崩溃或容器镜像不包含调试程序(例如无发行版镜像等) 而导致 kubectl exec 无法运行时,临时容器对于排除交互式故障很有用。

添加临时容器

使用上面创建的nginx Pod,这个默认是没有 ps,ping等命令的,咱们用 debug 命令给他添加一个临时容器。

## “nginx-deployment-78d88c66dd-svtpz”   这个是Pod 名字
## “--image=busybox:1.28”         给Pod 添加的临时容器,正常情况下推出以后临时容器会自动关闭。
## “--target nginx”               Pod 里运行的主容器名字或者是业务容器名字。
kubectl debug -it nginx-deployment-78d88c66dd-svtpz --image=busybox:1.28 --target nginx -n apps

进入以后是下面这样的,然后可以在容器里调,比如ps,ping 等命令就都可以使用。

Defaulting debug container name to debugger-8xzrl.
If you don't see a command prompt, try pressing enter.
/ #

也可以使用 kubectl describe po -n apps nginx-deployment-78d88c66dd-tn2cr 查看

Ephemeral Containers:
  debugger-wmmrd:
    Container ID:   containerd://70ef78f9e9f9422e8480bc86d5a7d030302dca82a07217d032de6237c948911b
    Image:          busybox:1.28
    Image ID:       docker.io/library/busybox@sha256:141c253bc4c3fd0a201d32dc1f493bcf3fff003b6df416dea4f41046e0f37d47
    Port:           <none>
    Host Port:      <none>
    State:          Terminated
      Reason:       Completed
      Exit Code:    0
      Started:      Fri, 26 Apr 2024 09:53:12 +0800
      Finished:     Fri, 26 Apr 2024 09:53:12 +0800
    Ready:          False
    Restart Count:  0
    Environment:    <none>
    Mounts:         <none>

复杂调试

还是基于nginx Pod 演示。

## “nginx-deployment-78d88c66dd-m7h7s”   需要调试等Pod名字
## “--image=busybox:1.28”    为 nginx Pod 提供调试的容器
## “--share-processes”       允许调试容器与原始 Pod 共享进程命名空间
## “--copy-to=myapp-debug”   这个标志指示 Kubernetes 在执行调试时创建一个新的 Pod,其名称为 myapp-debug,并将原始 Pod 的卷和配置复制到新的调试 Pod 中。
kubectl debug nginx-deployment-78d88c66dd-m7h7s -it --image=busybox:1.28 --share-processes --copy-to=myapp-debug -n apps

创建完成以后查看会多出来一个Pod 名字为myapp-debug

[root@master01 yaml]# kubectl get po -n apps 
NAME                                READY   STATUS    RESTARTS      AGE
busybox-6c8989b4f7-pmwkd            1/1     Running   2 (27h ago)   3d18h
myapp-debug                         2/2     Running   1 (3s ago)    76s
nginx-deployment-78d88c66dd-m7h7s   1/1     Running   0             2m31s

拷贝有问题的Pod 并修改启动命令

为了模拟应用崩溃的场景,使用 kubectl run 命令创建一个立即退出的容器:

kubectl run --image=busybox:1.28 myapp -- false

使用 kubectl describe pod myapp 命令,你可以看到容器崩溃了:

Containers:
  myapp:
    Image:         busybox
    ...
    Args:
      false
    State:          Waiting
      Reason:       CrashLoopBackOff
    Last State:     Terminated
      Reason:       Error
      Exit Code:    1

使用 kubectl debug 命令创建新的 Pod 的一个副本并改变默认启动命令为交互式 shell:

## “myapp”  需要拷贝的有问题Pod 名字
## “--copy-to=myapp-debug”    将拷贝的Pod 重新命名为 myapp-debug
## “--container=myapp”        指定需要拷贝Pod 主容器的名字(这里的Pod名和容器名字是一样的,所有都是myapp,如果不一样的话需要修改成自己的)
kubectl debug myapp -it --copy-to=myapp-debug --container=myapp -- sh
If you don't see a command prompt, try pressing enter.
/ #

拷贝有问题的Pod 并修改镜像。

在某些情况下,可能需要修改一个行为异常的 Pod,即从其正常的生产容器镜像更改为包含调试构建程序或其他实用程序的镜像。

例子:

kubectl run myapp --image=busybox:1.28 --restart=Never -- sleep 1d

使用 kubectl debug 创建一个拷贝并将其容器镜像更改为 ubuntu:

## 参数基本和上面的一样。 “--set-image=*=ubuntu” 表示将原来的镜像修改为ubuntu
kubectl debug myapp --copy-to=myapp-debug --set-image=*=ubuntu
  • “*=ubuntu”: 表示把所有容器的镜像改为 ubuntu。

网站公告

今日签到

点亮在社区的每一天
去签到