I was trying to simulate router using docker containers. With the following docker-compose.yml, two containers are connected to the same network.
version: "1"
networks:
net_1:
ipam:
config:
- subnet: 192.168.1.0/24
services:
node_1:
image: ubuntu
container_name: node_1
cap_add:
- NET_ADMIN
networks:
net_1:
ipv4_address: 192.168.1.2
node_2:
image: ubuntu
container_name: node_2
cap_add:
- NET_ADMIN
networks:
net_1:
ipv4_address: 192.168.1.3
To my understanding, node_1 & node_2 both connected to a virtual network(net_1). However, the desired topology is node_1 & node_2 direct connecting each other, instead of via net_1. Namely, creating an interface (e.g. eth0) in node_1 and bind it with an interface in node_2. Any suggestion on how to do that?
Many thanks!
I found a solution with veth.
After the container is started, we can use the following commands (execute on Linux host) to add interfaces to container and assign IP addresses.
PID1=$(sudo docker inspect -f '{{.State.Pid}}' node_1)
PID2=$(sudo docker inspect -f '{{.State.Pid}}' node_2)
ln -s /proc/$PID1/ns/net /var/run/netns/$PID1
ln -s /proc/$PID2/ns/net /var/run/netns/$PID2
ip link add v1a type veth peer name v1b
ip link set v1a netns $PID1
ip link set v1b netns $PID2
ip netns exec $PID1 ip addr add 10.0.1.101/24 dev v1a
ip netns exec $PID1 ip link set v1a up
ip netns exec $PID2 ip addr add 10.0.1.102/24 dev v1b
ip netns exec $PID2 ip link set v1b up