Introduction
Containers can use the network stack in a few different ways. It all depends on how they connect to the network. A couple of options are:
- docker bridge
- host (ex.
$ docker run --rm -it --net=host ...) - container networks (ex.
$ docker run --rm -it --net=container:id ...) - overlay
Building a container and running good old stuff like TCPdump or ngrep would not yield much interesting information, because you link directly to the bridge network or overlay in a default scenario.
The good news is, that you can link your TCPdump container to the host network or even better, to the container network stack.
- In the
--net=hostcase, you can capture all traffic between the host and the physical network. - In the
--net=container:idall traffic in/out a specific container (or group of containers) can be captured.
So let's get started!
First create a TCPdump container
$ docker build -t tcpdump - <<EOF
FROM ubuntu
RUN apt-get update && apt-get install -y tcpdump
CMD tcpdump -i eth0
EOF
Now lets run a network, an nginx container … and run some traffic
$ docker network create demo-net
$ docker run -d --network demo-net --name wwwnginx nginx
$ docker run -it --network demo-net dockersec/siege \
-c 1 http://wwwnginx/
Now open a new shell and link the TCPdump container
$ docker run -it --net=container:wwwnginx tcpdump
Or if you want to specify tcpdump flags and filters:
$ docker run -it --net=container:wwwnginx tcpdump tcpdump port 80
When traffic is received, TCPdump will display the captured traffic:
14:38:05.095483 IP 86fde53b1869.80 > 08f18be305e8.demo-net.41274: Flags [F.], seq 846,
ack 149, win 235, options [nop,nop,TS val 2062442 ecr 2062442], length 0
14:38:05.095564 IP 08f18be305e8.demo-net.41274 > 86fde53b1869.80: Flags [F.], seq 149,
ack 847, win 247, options [nop,nop,TS val 2062442 ecr 2062442], length 0
14:38:05.095607 IP 86fde53b1869.80 > 08f18be305e8.demo-net.41274: Flags [.], ack 150,
win 235, options [nop,nop,TS val 2062442 ecr 2062442], length 0
14:38:06.097784 IP 08f18be305e8.demo-net.41276 > 86fde53b1869.80: Flags [S], seq
2606688608, win 29200, options [mss 1460,sackOK,TS val 2062543 ecr 0,nop,wscale 7],
length 0
This technique is extremely useful for debugging network issues in containerized applications and for security analysis of container traffic.