docker networking namespace not visible in ip netns list

感情迁移 提交于 2019-11-29 19:12:57
jary

That's because docker is not creating the reqired symlink:

# (as root)
pid=$(docker inspect -f '{{.State.Pid}}' ${container_id})
mkdir -p /var/run/netns/
ln -sfT /proc/$pid/ns/net /var/run/netns/$container_id

Then, the container's netns namespace can be examined with ip netns ${container_id}, e.g.:

# e.g. show stats about eth0 inside the container 
ip netns exec "${container_id}" ip -s link show eth0

As @jary indicates, the ip netns command only works with namespace symlinks in /var/run/netns. However, if you you have the nsenter command available (part of the util-linux package), you can accomplish the same thing using the PID of your docker container.

To get the PID of a docker container, you can run:

docker inspect --format '{{.State.Pid}}' <container_name_or_Id>

To get a command inside the network namespace of a container:

nsenter -t <contanier_pid> -n <command>

E.g:

$ docker inspect --format '{{.State.Pid}}' weechat
4432
$ sudo nsenter -t 4432 -n ip addr show
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default 
    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
    inet6 ::1/128 scope host 
       valid_lft forever preferred_lft forever
75: eth0@if76: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP group default 
    link/ether 02:42:ac:11:00:1b brd ff:ff:ff:ff:ff:ff
    inet 172.17.0.27/16 scope global eth0
       valid_lft forever preferred_lft forever
    inet6 fe80::42:acff:fe11:1b/64 scope link 
       valid_lft forever preferred_lft forever

The above was equivalent to running ip netns exec <some_namespace> ip addr show.

As you can see here, you will need to run nsenter with root privileges.

Similar but different with @jary’s answer.
There is no need to introduce /proc/<pid>/ or netster. Only one move below to achieve what you want. Thus, you could operate containers’ network namespace just like they are created manually on host machine.

One Move:

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

Result:

Start a container:

docker run -tid ubuntu:18.04 

List container:

root@Light-G:/var/run# docker ps
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
972909a27ea1        ubuntu:18.04        "/bin/bash"         19 seconds ago      Up 18 seconds                           peaceful_easley

List network namespace of this container:

root@Light-G:/var/run# ip netns list
733443afef58 (id: 0)

Delete container:

root@Light-G:/var/run# docker rm -f 972909a27ea1
972909a27ea1

List network namespace again:

root@Light-G:/var/run# ip netns list
root@Light-G:/var/run#
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!