在Docker中运行OpenWrt教程

参考:
https://github.com/luoqeng/OpenWrt-on-Docker
斐讯N1小钢炮固件docker安装最新版openwrt实现旁路由

软件环境:
Win10中运行的Hyper-V中运行的Debian中运行的Docker

网络环境:
主路由:192.168.2.1/24
Win10(主机):192.168.2.5
Debian(Hyper-V桥接到局域网):192.168.2.8
OpenWrt(Debian中的Docker中运行):192.168.2.2

一、开启网卡混杂模式(重要)

首先要开启Hyper-V中Debian虚拟机网卡的混杂模式,否则OpenWrt无法连网,主机也ping不通OpenWrt。

Enable promiscuous mode in Hyper-V:
Hyper-V > VM > Settings > NIC (click plus) > ADVANCED FEATURE > Enable MAC Address Spoofing
(https://serverfault.com/questions/812528/docker-container-connection-in-macvlan-network)

如果是Linux环境,那么用ip link set eth0 promisc on即可。

二、选择OpenWrt镜像

推荐两个:
https://www.right.com.cn/forum/thread-866582-1-1.html
https://www.right.com.cn/forum/thread-762559-1-1.html

三、将OpenWrt镜像导入Docker

mkdir ~/openwrt
mkdir /mnt/openwrt
cd ~/openwrt
# 将下载好的OpenWrt镜像放到这里
mount -o loop openwrt-x86-64-rootfs-squashfs.img /mnt/openwrt
cd /mnt/openwrt/
tar zcf ~/openwrt/openwrt.tgz *
cd ~/openwrt
docker import openwrt.tgz openwrt
umount /mnt/openwrt
rm -r /mnt/openwrt

四、运行OpenWrt容器

docker network create -d macvlan --subnet=192.168.2.0/24 --gateway=192.168.2.1 -o parent=eth0 macvlan0 # 创建docker macvlan网络
docker run --restart=always --privileged --name='openwrt' --net=macvlan0 --ip=192.168.2.2 --detach=true openwrt /sbin/init # 运行openwrt容器
docker exec -it openwrt /bin/sh # 进入openwrt容器shell
vi /etc/config/network # 编辑openwrt网络配置
```
config interface 'lan'
        option type 'bridge'
        option ifname 'eth0'
        option proto 'static'
        option ipaddr '192.168.2.2'
        option netmask '255.255.255.0'
        option ip6assign '60'
        option gateway '192.168.2.1'
        option dns '192.168.2.1'
```
/etc/init.d/network restart # 重启网络

五、Docker宿主机(Debian)配置网络

注意:修改网络配置可能会让你失去对宿主机(Debian)的网络连接。

  • 临时配置网络(重启后失效)
# 添加macvlan桥接网卡,并将192.168.2.8分配到该网卡
ip addr del 192.168.2.8/24 dev eth0; \
ip link add macvlan link eth0 type macvlan mode bridge; \
ip addr add 192.168.2.8/24 dev macvlan; \
ip link set macvlan up; \

# 替换默认路由到macvlan网卡
ip route del 192.168.2.0/24 dev eth0; \
ip route del default; \
ip route add 192.168.2.0/24 dev macvlan; \
ip route add default via 192.168.2.1 dev macvlan;
  • 永久配置网络(重启也能生效)

宿主机(Debian)修改网络配置:vi /etc/network/interface

将:

auto eth0
iface eth0 inet static
  address 192.168.2.8
  broadcast 192.168.2.255
  netmask 255.255.255.0
  gateway 192.168.2.1
  dns-nameservers 192.168.2.1

修改为:

auto eth0
iface eth0 inet manual

auto macvlan
iface macvlan inet static
  address 192.168.2.8
  netmask 255.255.255.0
  gateway 192.168.2.1
  dns-nameservers 192.168.2.1
  pre-up ip link add macvlan link eth0 type macvlan mode bridge
  post-down ip link del macvlan link eth0 type macvlan mode bridge

修改完后重启网络systemctl restart networking或者重启系统查看效果。

六、打开Openwrt管理页面

此时,如果配置正常的话,在局域网中就可以访问 http://192.168.2.2/ 来打开OpenWrt的管理页面了,一般情况下root密码为password

留下评论