目录

docker进阶-使用nsenter抓包

Docker 如何使用 nsenter 工具进入容器.

1. 进入 pod netns 抓包

发现某个服务不通,最好将其副本数调为1,并找到这个副本 pod 所在节点。

  • 查看指定 pod 运行的容器 ID

    kubectl describe pod <pod> -n mservice

  • 获得容器进程的 pid

    docker inspect -f {{.State.Pid}} <container>

  • 进入该容器的 network namespace

    nsenter -n --target <PID>

  • 依赖宿主机的命令:kubectl, docker, nsenter, grep, head, sed

技巧

进入 podnetns,可以执行宿主机上的 ip aifconfig 来查看容器的网卡,执行 netstat -tunlp 查看当前容器监听了哪些端口,再通过 tcpdump 抓包:

tcpdump -i eth0 -w test.pcap port 80

2. 一键进入 pod 脚本

一直手动操作也相对比较麻烦,我们可以使用脚本一键完成 nsenter 的动作。登录 pod 所在节点,将如下脚本粘贴到 shell (注册函数到当前登录的 shell,我们后面用。)

1
2
3
4
5
6
7
8
function e() {
set -eu
   ns=${2-"default"}
   pod=`kubectl -n $ns describe pod $1 | grep -Eo 'docker://.*$' | head -n 1 | sed 's/docker:\/\/\(.*\)$/\1/'`
   pid=`docker inspect -f {{.State.Pid}} $pod`
echo "enter pod netns successfully for $ns/$1"
  nsenter -n --target $pid
}

一键进入 pod 所在的 netns,格式:e POD_NAME NAMESPACE,示例:

e istio-galley-58c7c7c646-m6568 istio-system

注意
省略 NAMESPACE 默认为 default

e proxy-5546768954-9rxg6

ctrl-c 停止抓包,再用 scpsz 将抓下来的包下载到本地使用 wireshark 分析