May 22, 2021 Docker From entry to practice
By default, Docker connects all containers to the
docker0
Users sometimes need to be able to communicate directly between two containers without having to bridge through a host bridge.
The solution is simple: create a
peer
interfaces, put in two containers, and configure them as point-to-point link types.
Start with 2 containers:
$ sudo docker run -i -t --rm --net=none base /bin/bash
root@1f1f4c1f931a:/#
$ sudo docker run -i -t --rm --net=none base /bin/bash
root@12e343489d2f:/#
Find the process number, and then create a tracking file for the network namespace.
$ sudo docker inspect -f '{{.State.Pid}}' 1f1f4c1f931a
2989
$ sudo docker inspect -f '{{.State.Pid}}' 12e343489d2f
3004
$ sudo mkdir -p /var/run/netns
$ sudo ln -s /proc/2989/ns/net /var/run/netns/2989
$ sudo ln -s /proc/3004/ns/net /var/run/netns/3004
Create a pair of
peer
and then configure the routes
$ sudo ip link add A type veth peer name B
$ sudo ip link set A netns 2989
$ sudo ip netns exec 2989 ip addr add 10.1.1.1/32 dev A
$ sudo ip netns exec 2989 ip link set A up
$ sudo ip netns exec 2989 ip route add 10.1.1.2/32 dev A
$ sudo ip link set B netns 3004
$ sudo ip netns exec 3004 ip addr add 10.1.1.2/32 dev B
$ sudo ip netns exec 3004 ip link set B up
$ sudo ip netns exec 3004 ip route add 10.1.1.1/32 dev B
The two containers can now ping each other and successfully establish a connection. Point-to-point links do not require subnets and subnet masks.
Alternatively, you can create
--net=none
link without specifying --net=none.
This allows the container to communicate over the original network.
Using a similar approach, you can create a container that communicates only with the host.
In general, however, it is more recommended
--icc=false
to close communication between containers.