How to TCPdump Containers in Kubernetes pods ?

Analyzing Network traffic is one of the crucial element while developing a solution. In the case of normal VMs/ physical machine, we will use TCPdump and listen to the external interfaces which will capture, the packets and can be later used for analysis. TCPdump is a tool used to capture the packets and we will be using wireshark to analyze these packets. Normally pod/container images will be of minimal flavor and will not be having the debugging OS tools, so In this article, we will see how to capture the packet, even if we don't have tcpdump rpm installed in the container.

Identify  Worker Node

We will have to identify the worker Node where our pod is running. Below code snippet shows the command for the same

[root@cluster-01-cs-01 ~]# kubectl get pods -n ckey-second -o wide
NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES
keycloak-0 2/2 Running 0 11h 192.106.208.226  cluster-01-worker-12 <none> <none>
keycloak-1 2/2 Running 0 11h 192.106.175.115  cluster-01-worker-20 <none> <none>
mariadb-0  2/2 Running 0 11h 192.106.128.88   cluster-01-worker-17 <none> <none>

Identify the Container ID

We will have to identify the container's ID for which we need to capture the network packages

kubectl get pod keycloak-0 -n ckey-second -o json | grep containerID -A 10

"containerID": "docker://a6c6cddd5461ae5f17440fca4107827d16e6fca6243c4b65ad2d23eb8ac7312d",
"image": "<image-tag>",
"imageID": "docker-pullable:<trimmed>",
"lastState": {},

Verify tcpdump package

Login to the worker node, where the pod is running

[root@cluster-01-cs-01 ~]#ssh root@cluster-01-worker-12
[root@cluster-01-worker-12 cloud-user]# rpm -qa|grep tcp
tcpdump-4.9.2-4.el7_7.1.x86_64

Capture packets using tcpdump

Idenitfy unique network interface index

Login into the container using the container Id , and identify unique network interface index

cluster-01-worker-12 ~]# docker exec -it a6c6cddd5461ae5f17440fca4107827d16e6fca6243c4b65ad2d23eb8ac7312d bash
bash-4.2$ cat /sys/class/net/eth0/iflink
162
bash-4.2$

Locate the  interface on the worker

[root@cluster-01-worker-12 cloud-user]# ip link |grep 162
162: cali3876eb3873c@if3: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 8950 qdisc noqueue state UP mode DEFAULT group default

Capture packets from the interface

Normal tcpdump commands can be used to capture the traffic from the interface and can be written to a file

[root@cluster-01-worker-12 cloud-user]# tcpdump -i cali3876eb3873c -w packets.pcap
tcpdump: verbose output suppressed, use -v or -vv for full protocol decode
<trimmed>
9 packets captured
9 packets received by filter
0 packets dropped by kernel

Search on LinuxDataHub

Leave a Comment