实际在部署虚拟化的时候我们往往都会把宿主机和VM各自的地址段单独规划。借助OpenWrt可以自己划分一下vlan。OpenWrt上设置vlan tag可以参考之前的文章。比如我的network配置文件,划分了3个VLAN(其实最好不要使用vlan 0),非默认vlan里每个lan口都是打了vlan tag:
config interface 'loopback'
option ifname 'lo'
option proto 'static'
option ipaddr '127.0.0.1'
option netmask '255.0.0.0'
config interface 'lan'
option ifname 'eth1.0'
option type 'bridge'
option proto 'static'
option ipaddr '10.0.1.1'
option netmask '255.255.255.0'
config interface 'lan1'
option ifname 'eth1.1'
option type 'bridge'
option proto 'static'
option ipaddr '10.1.1.1'
option netmask '255.255.255.0'
config interface 'lan2'
option ifname 'eth1.2'
option type 'bridge'
option proto 'static'
option ipaddr '10.2.1.1'
option netmask '255.255.255.0'
config interface 'wan'
option ifname 'eth0'
config switch 'eth1'
option reset '1'
option enable_vlan '1'
config switch_vlan
option device 'eth1'
option vlan '0'
option ports '0 1 2t 5*'
config switch_vlan
option device 'eth1'
option vlan '1'
option ports '0t 1t 2t 5*'
config switch_vlan
option device 'eth1'
option vlan '2'
option ports '0t 1t 2t 5*'
config interface 'wwan'
option proto 'dhcp'
其他还需要修改好dhcp和firewall配置文件(可以简单参考之前的文章)。
在自己笔记本上测试的,把有线网卡eth0加了vlan 2,把没有eth0放到br0网桥,eth0.2放到了br2。测试dhcp br0和br2分别获取到IP。
#/etc/network/interfaces 这个是默认的网桥配置
auto br0
iface br0 inet dhcp
bridge_ports eth0
bridge_fd 0
bridge_maxwait 0
为了测试方便也可以就直接命令行手动添加一下。
sudo vconfig add eth0 2
sudo brctl addbr br2
sudo brctl addif br2 eth0.2
如果想写到配置文件就
auto br0
iface br0 inet dhcp
bridge_ports eth0
bridge_fd 0
bridge_maxwait 0
auto br2
iface br2 inet manual
bridge_ports eth0.2
bridge_maxwait 0
auto br3
iface br3 inet manual
bridge_ports eth0.3
bridge_maxwait 0
iface eth0.2 inet manual
vlan-raw-device eth0
iface eth0.3 inet manual
vlan-raw-device eth0
反正就是把网卡加到1个vlan,然后把新建一个网桥,桥接一下这个网卡。
然后修改VM的配置文件,改成桥接到br2
<interface type='bridge'>
<mac address='52:54:00:cf:0f:f1'/>
<source bridge='br2'/>
<model type='virtio'/>
<bandwidth>
<inbound average='512' peak='550' burst='520'/>
<outbound average='512' peak='550' burst='520'/>
</bandwidth>
启动VM后了可以看到VM能获得的IP是10.2.1.0/24段内的了。并且是可以访问公网,说明测试OK。
root@debian:~# ifconfig
eth0 Link encap:Ethernet HWaddr 52:54:00:cf:0f:f1
inet addr:10.2.1.116 Bcast:10.2.1.255 Mask:255.255.255.0
inet6 addr: fe80::5054:ff:fecf:ff1/64 Scope:Link
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:10 errors:0 dropped:0 overruns:0 frame:0
TX packets:15 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:947 (947.0 B) TX bytes:1326 (1.2 KiB)