作者:E4b9a6, 创建:2022-05-09, 字数:1532, 已阅:259, 最后更新:2022-05-09
Docker运行Openwrt常见做法是使用macvlan,网络信息假设如下
在Docker中对宿主机发起ICMP包做测试,从输出中可看出Openwrt虽与宿主机在相同网段下但因为Docker安全策略的问题却是无法直接通信的
➜ ~ sudo docker exec -it openwrt ping 192.168.1.1 -c 4 -W 1
PING 192.168.1.1 (192.168.1.1): 56 data bytes
--- 192.168.1.1 ping statistics 4 packets transmitted, 0 packets received, 100% packet loss
解决方法是多建立一个宿主机网卡的macvlan网桥,因为macvlan之间是可以互相通信的,创建一个名为openwrt-macvlan方法如下
# 网桥名称为openwrt-macvlan
/usr/bin/ip link add openwrt-macvlan link eth0 type macvlan mode bridge
# 为该网桥分配IP为192.168.11.12
/usr/bin/ip addr add 192.168.1.12 dev openwrt-macvlan
# 启动网桥
/usr/bin/ip link set openwrt-macvlan up
# 为宿主机添加静态路由通过创建的网桥来访问openwrt
/usr/bin/ip route add 192.168.11.11 dev openwrt-macvlan
再次在Docker容器Openwrt对宿主机发起ICMP包做测试,可以看到这次网络通信是成功的
➜ ~ sudo docker exec -it openwrt ping 192.168.1.1 -c 4 -W 1
PING 192.168.1.1 (192.168.1.1): 56 data bytes
64 bytes from 192.168.1.1: seq=0 ttl=64 time=0.540 ms
64 bytes from 192.168.1.1: seq=1 ttl=64 time=0.244 ms
64 bytes from 192.168.1.1: seq=2 ttl=64 time=0.282 ms
64 bytes from 192.168.1.1: seq=3 ttl=64 time=0.293 ms
--- 192.168.1.1 ping statistics 4 packets transmitted, 4 packets received, 0% packet loss
round-trip min/avg/max = 0.244/0.339/0.540 ms
将添加网桥的方法创建为脚本 /etc/openwrt-macvlan.sh ,并添加开机执行,执行 sudo crontab -e,输入如下
# DO NOT EDIT THIS FILE - edit the master and reinstall.
...
# m h dom mon dow command
@reboot /usr/bin/bash /etc/openwrt-macvlan.sh