在 K8s 中调试 Alpine Image:没有 `netstat`,没有 `ip`,没有 `apk`

Debug Alpine Image in K8s: No `netstat`, no `ip`, no `apk`

我要调试的 Kubernetes 集群中有一个容器。

但是没有netstat,没有ip,也没有apk

有没有办法升级此映像,以便安装常用工具?

在本例中,它是 K8s 1.23 集群中的 nginx 容器镜像。

使用容器的全部意义在于优化集群中的资源利用率。使用的图像应仅包含 运行 您的应用程序所需的软件包。

应从您的映像中删除不需要的包(尤其是在产品中)以降低计算利用率并减少攻击向量。

这似乎是一个精简的图像,其中只有运行该应用程序所需的库。

为了进行调试,您必须在与要调试的容器相同的 pid 和网络命名空间中创建一个新容器

先构建容器

Docker 文件

FROM alpine
RUN apk update && apk add strace
CMD ["strace", "-p", "1"]

建造

$ docker build -t strace .

运行

docker run -t --pid=container:<targetContainer> \
  --net=container:targetContainer \
  --cap-add sys_admin \
  --cap-add sys_ptrace \
  strace
strace: Process 1 attached
futex(0xd72e90, FUTEX_WAIT, 0, NULL

https://rothgar.medium.com/how-to-debug-a-running-docker-container-from-a-separate-container-983f11740dc6

Alpine 是图像的 stripped-down 版本以减少占用空间。因此,预计会缺少这些工具。虽然从 Kubernetes 1.23 开始,您可以使用 kubectl debug 命令将调试 pod 附加到主题 pod。 语法:

kubectl debug -it <POD_TO_DEBUG> --image=ubuntu --target=<CONTAINER_TO_DEBUG> --share-processes

示例: 在下面的示例中,ubuntu 容器附加到 Nginx-alpine pod,需要调试。另外,请注意 ps -eaf 输出显示 nginx 进程 运行,cat /etc/os-release 显示 ubuntu 运行。两个容器之间的指示过程是shared/visible。

ps@kube-master:~$ kubectl debug -it nginx --image=ubuntu --target=nginx --share-processes
Targeting container "nginx". If you don't see processes from this container, the container runtime doesn't support this feature.
Defaulting debug container name to debugger-2pgtt.
If you don't see a command prompt, try pressing enter.
root@nginx:/# ps -eaf
UID          PID    PPID  C STIME TTY          TIME CMD
root           1       0  0 19:50 ?        00:00:00 nginx: master process nginx -g daemon off;
101           33       1  0 19:50 ?        00:00:00 nginx: worker process
101           34       1  0 19:50 ?        00:00:00 nginx: worker process
101           35       1  0 19:50 ?        00:00:00 nginx: worker process
101           36       1  0 19:50 ?        00:00:00 nginx: worker process
root         248       0  1 20:00 pts/0    00:00:00 bash
root         258     248  0 20:00 pts/0    00:00:00 ps -eaf
root@nginx:/# 

如此处所示 ubuntu 进行调试,这为我们提供了各种工具:

root@nginx:/# cat /etc/os-release
NAME="Ubuntu"
VERSION="20.04.3 LTS (Focal Fossa)"
ID=ubuntu
ID_LIKE=debian
PRETTY_NAME="Ubuntu 20.04.3 LTS"
VERSION_ID="20.04"
HOME_URL="https://www.ubuntu.com/"
SUPPORT_URL="https://help.ubuntu.com/"
BUG_REPORT_URL="https://bugs.launchpad.net/ubuntu/"
PRIVACY_POLICY_URL="https://www.ubuntu.com/legal/terms-and-policies/privacy-policy"
VERSION_CODENAME=focal
UBUNTU_CODENAME=focal
root@nginx:/# 

如果您的集群中需要启用临时容器,那么您可以通过 here 中描述的功能门来启用它。