Skip to main content

Analyze Container Traffic with tcpdump

·2 mins

tcpdump is not available in container images due to their minimal approach. To address this, you can build a tcpdump image and then use Docker’s --net flag to access a container’s or the host network itself.

Building the image #

The Dockerfile:

FROM alpine 
RUN apk update && apk add tcpdump 
CMD tcpdump -i eth0 

Building the image:

docker build -t tcpdump .
[+] Building 13.9s (6/6) FINISHED                                                                 

...REDACTED...


 => [2/2] RUN apk update && apk add tcpdump                                                                  6.0s
 => exporting to image                                                                                       0.2s
 => => exporting layers                                                                                      0.1s
 => => writing image sha256:f359f058f549da4085af83fde9f1095ca9e5e1db769078fd78277d0e11bcd455                 0.0s
 => => naming to docker.io/library/tcpdump

Now I have a local tcpdump image:

docker images | grep tcp
tcpdump                    latest    f359f058f549   4 minutes ago   10.4MB

Container network namespace #

With --net=container:<container_name>|<container_id>, you can attach or deploy a container inside another container’s namespace. You can read about it here.

Now I can run tcpdump on my netdata container:

docker run --rm -it --net=container:netdata --name tcpdump-tmp tcpdump

The syntax is: --name <container_name> <image>

To override the default CMD tcpdump -i eth0, run:

--name <container_name> <image> <CMD>

--name tcpdump-tmp tcpdump tcpdump -i enp0s5

Host network namespace #

Inside the host namespace:

docker run --rm -it --privileged=true --net=host --name tcpdump-tmp tcpdump tcpdump -i enp0s5

Ephemeral Pods #

Will come back to later……..

Reference

For local development:

kubectl --namespace demo debug $POD --image tcpdump alpine --stdin --tty --target container-name

Preferred method:

kubectl --namespace demo debug $POD --image tcpdump alpine --stdin --tty --share-processes --copy-to container-name-demo-debug