Working with kernel network namespaces created by Docker

Published on Author admin

To work with kernel network namespaces created by Docker create necessary symbolic link:

ln -s /var/run/docker/netns  /var/run/netns

List network namespaces:

ip netns list

Result will be similar to:

# ip netns list
644c14147ad2 (id: 2)
bb230cf5f65f (id: 1)
e2772d19bfd0 (id: 0)

Execute command inside network namespace:

ip netns exec <namespace> <command>

Example - listing network interfaces inside network namespace:

# ip netns exec bb230cf5f65f ip addr
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
17: eth0@if18: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP group default
    link/ether 02:42:ac:11:00:03 brd ff:ff:ff:ff:ff:ff link-netnsid 0
    inet 172.17.0.3/16 brd 172.17.255.255 scope global eth0
       valid_lft forever preferred_lft forever

Example - displaying routing table inside network namespace:

# ip netns exec bb230cf5f65f ip route
default via 172.17.0.1 dev eth0
172.17.0.0/16 dev eth0 proto kernel scope link src 172.17.0.3

Example - using ping command inside network namespace:

# ip netns exec bb230cf5f65f ping 172.17.0.3
PING 172.17.0.3 (172.17.0.3) 56(84) bytes of data.
64 bytes from 172.17.0.3: icmp_seq=1 ttl=64 time=0.050 ms
64 bytes from 172.17.0.3: icmp_seq=2 ttl=64 time=0.072 ms
64 bytes from 172.17.0.3: icmp_seq=3 ttl=64 time=0.076 ms
^C
--- 172.17.0.3 ping statistics ---
3 packets transmitted, 3 received, 0% packet loss, time 2061ms
rtt min/avg/max/mdev = 0.050/0.066/0.076/0.011 ms

Example - display listening ports inside network namespace:

# ip netns exec 644c14147ad2 netstat -tlpn
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name    
tcp        0      0 0.0.0.0:80              0.0.0.0:*               LISTEN      19801/nginx: master
tcp6       0      0 :::80                   :::*                    LISTEN      19801/nginx: master