前言
一般情况下,想要抓取 pod 中的某个 container 的 tcpdump,直接 kubectl exec 进入那个 container,然后就可以抓取了。但是如果当你的 image 没有安装 bash 等 shell terminal,那我们就不能使用 exec 进入 container 了。所以此时我们就需要以下方法,通过自己编一个带有 shell 的 image,然后 docker exec 嵌入到 pod 中,再进行抓取 tcpdump。
构建一个带有 tcpdump 的镜像
-
先 pull 一个 base image alpine:3.9.2,然后 docker run 这个 image,在进入对应的 container,安装 tcpdump,再开另一个 terminal,提交生成一个新的 image。下面命令可供参考:
docker run -it --name=alpine alpine:3.9.2 # install tcpdump apk add tcpdump # switch another terminal and exec this command docker commit alpine aaa:tag
抓取 tcpdump
-
将你的 image 运行,然后嵌到想要的 container 的 network 上,然后进入到你自己 image 运行的 container 里面抓取 tcpdump
# display all of the container and found containerId that you want. docker ps | grep your service # if you want to copy tcpdump file out to container into local, you should reference step3. docker run -it --rm --net=container:containerID aaa:tag tcpdump -i lo -w lo.pcap #or if you want to grap all dump, you can use following command tcpdump -i any -w any.pcap
将 tcpdump 文件拷出 container 到本地,用 wireshark 进行分析
-
我是通过挂载的方式,将本地创建的 volume 挂到 container 里面的某个目录,然后将 coredump 文件生成在 container 里面的那个目录,然后在本地就可以看到对于的文件了。将对应文件拷出,进去 wireshark 分析就好了。(其实我之前有提到过 docker cp 这个命令也可以 copy 文件,也许更为简单。具体怎么使用,可以参考官网指导 docker cp command guidance.)
# create a volume name is data. docker volume create data # view detailed message . docker inspect data docker run -it --rm --net=container:containerID --mount source=data,destination=/dir aaa:tag
minikube 中抓取 tcpdump
minikube ssh -p master
sudo -i
ps -elf |grep keywordsofprocess
lsns -p pid
nsenter -t pid -n
tcpdump -i any port 9010
总结
其实在 pod 里面抓取 tcpdump 还是蛮重要的,因为当你一个 pod 里面有几个 container 的时候,内部的消息,其实在 pod 外面是抓取不到的。那只能想办法到 pod 里面去抓。但是一般都为了安全起见,产品的 image 并没有 bash 可以让你进到 container 里面。那我这个方法就有很大用处了。