'How to capture packets for single docker container

There have many container running on the host. And I want to capture packets for the one container of these. Is there any way to do this?



Solution 1:[1]

You can bind to the network namespace of one container to another:

docker run -it --rm --net container:<container_name> \
  nicolaka/netshoot tcpdump ...

To see more about the netshoot image used above, see: https://github.com/nicolaka/netshoot

Solution 2:[2]

From and for a workstation with Wireshark:

docker exec -ti <container id> cat /sys/class/net/eth0/iflink

28
ip link | grep 28

28: veth11b0a6c@if27: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue master docker0 state UP mode DEFAULT group default

Wireshark interfaces

Solution 3:[3]

use nsenter -n -t pid command, into the same net namespace, then execute tcpdump

Solution 4:[4]

In rare cases (or maybe when you create your own container images) the container may have tcpdump installed. In that case, you can issue the following command to get a 10 second capture saved to the host computer (outside of the container):

# Set CONATINER_ID to the process you want to perform a dump from
# Consider docker ps for finding the container id
# for example, CONTAINER_ID=$( docker ps | grep $IMAGE | awk '{print $1}' )
docker exec $CONTAINER_ID bash -c 'timeout 10 tcpdump -i eth0 -w /dev/stdout' > capture.pcap

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 BMitch
Solution 2 Etienne Gautier
Solution 3 weifan01
Solution 4 Mark