Skip to content

antony@notes:~/kubernetes$ cat "Debugging-with-an-ephemeral-debug-container.md"

Debugging with an ephemeral debug container

2024-10-26· kubernetes ·Kubernetes

Debugging with an ephemeral debug container

kubectl exec 無法滿足需求時,Ephemeral containers 對於交互式排查問題非常有用,例如 container 崩潰或 container image(如 distroless images)不包含除錯工具的情況。

Example debugging using ephemeral containers

您可以使用 kubectl debug 命令向正在運行的 Pod 添加 ephemeral containers。首先,為示例創建一個 Pod:

$ kubectl run ephemeral-demo --image=registry.k8s.io/pause:3.1 --restart=Never

本節中的示例使用了 pause container image,因為它不包含除錯工具,但此方法適用於所有 container images。

如果您嘗試使用 kubectl exec 創建一個 shell,您會看到一個錯誤,因為這個容器映像中沒有 shell。

$ kubectl exec -it ephemeral-demo -- sh

執行結果 :

error: Internal error occurred: unable to upgrade connection: pod does not exist

您可以改用 kubectl debug 添加一個除錯容器。如果指定 -i/--interactive 參數,kubectl 將自動連接到 Ephemeral Container 的 console。

$ kubectl debug -it ephemeral-demo --image=busybox:1.28 --target=ephemeral-demo
  • -i,表示打開標準輸入(stdin),允許你在 Container 內輸入命令。
    • -t 結合使用,可以進入交互式 Shell。
  • -t,為 debugging container 分配一個虛擬終端(TTY),使您能夠與 container 交互。
  • ephemeral-demo,要排除故障的 Pod 的名稱。
  • --image='', debug container 使用的 Container image.
  • --target='',要進到 Pod 中的哪個 Container.

執行結果 :

Targeting container "ephemeral-demo". If you don't see processes from this container it may be because the container runtime doesn't support this feature.
Defaulting debug container name to debugger-j8vfr.
If you don't see a command prompt, try pressing enter.
/ #

此命令會添加一個新的 busybox container 並連接到它。--target 參數用於指定另一個 container 的 Linux process namespace。這在這裡是必要的,因為 kubectl run 創建的 Pod 並未啟用process namespace sharing

:::info

--target 參數必須得到 Container Runtime 的支持。如果不支持,Ephemeral Container 可能無法啟動,或者可能會在一個隔離的 process namespace 中啟動,因此 ps 無法顯示其他 containers 中的 processes 。

:::

執行 ps -eaf 檢查是否能看到 pause process

/ # ps -eaf

執行結果 :

PID   USER     TIME  COMMAND
    1 root      0:00 /pause
   13 root      0:00 sh
   25 root      0:00 ps -eaf

您可以使用 kubectl describe 查看新建 ephemeral container 的狀態:

$ kubectl describe pod ephemeral-demo

執行結果 :

...
Ephemeral Containers:
  debugger-j8vfr:
    Container ID:   containerd://40e5ca6659b5921235eee1fb7372eb10c14d72e8e84082fd4ad6e1a7195db160
    Image:          busybox:1.28
    Image ID:       docker.io/library/busybox@sha256:141c253bc4c3fd0a201d32dc1f493bcf3fff003b6df416dea4f41046e0f37d47
    Port:           <none>
    Host Port:      <none>
    State:          Running
      Started:      Sat, 26 Oct 2024 02:23:33 +0000
    Ready:          False
    Restart Count:  0
    Environment:    <none>
    Mounts:         <none>
...

完成後,使用 kubectl delete 刪除該 Pod:

$ kubectl delete pod ephemeral-demo