menu Chancel's blog
rss_feed
Chancel's blog
秋雨一何碧,山色倚晴空。

Docker下Openwrt与宿主机网络通信

类型:Network
创建时间:2022-05-09 01:14:18
更新时间:2022-05-09 01:14:18
类型:Network
更新时间:2022-05-09 01:14:18

Docker运行Openwrt常见做法是使用macvlan,网络信息假设如下

  • 宿主机:192.168.1.10
  • Docker容器IP:192.168.1.11
  • 宿主机网卡名称:eth0

在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

[[replyMessage== null?"发表评论":"@" + replyMessage.m_author]]

account_circle
email
web_asset
textsms

评论列表([[messageResponse.total]])

[[messageItem.m_author]] [[messageItem.m_author]]
[[messageItem.create_time]]
[[getEnviron(messageItem.m_environ)]]
[[subMessage.m_author]] [[subMessage.m_author]] @ [[subMessage.parent_message.m_author]] [[subMessage.parent_message.m_author]]
[[subMessage.create_time]]
[[getEnviron(messageItem.m_environ)]]