Bridge interface for KVM VMs with access to Internet?

10,742

Solution 1

When you add your host Ethernet controller to the bridge br0 (connected to a VM) you are effectively creating two new devices on the network (two devices with new MAC-addresses) instead of the old one. In this case your bridge and your VM should each get a new IP. Now the tricky part is that your ISP/hosting company wants your MAC to remain the same as the MAC of your physical Ethernet controller. When you enable bridge, your ISP cannot identify new devices, which results in no internet connectivity.

What you need is NAT, so your VM would use the host's IP address to access the Internet. You can setup it with the following commands:

ip link add name br0 type bridge
ip addr add 172.20.0.1/24 dev br0
ip link set dev br0 up
sysctl -w net.ipv4.ip_forward=1
iptables --table nat --append POSTROUTING --out-interface enp3s0 -j MASQUERADE
iptables --insert FORWARD --in-interface br0 -j ACCEPT

After this you should be able to access Internet from your VMs (You don't need to run brctl)

Solution 2

I suspect you may find the simplest solution is to not add your NIC to the bridge, and instead, use forwarding and masquerading.

In other words, do something like:

  • sysctl -w net.ipv4.ip_forward=1
  • iptables -t nat -A POSTROUTING -o enp3s0 -j MASQUERADE
Share:
10,742

Related videos on Youtube

sina
Author by

sina

Updated on September 18, 2022

Comments

  • sina
    sina over 1 year

    I create a bridge interface for my KVM virtual machines:

    ip link add name br0 type bridge
    ip addr add 172.20.0.1/24 dev br0
    ip link set dev br0 up
    

    I create KVM VMs:

    virt-install --name $VM_NAME1 --network=bridge:br0,mac=$VM_MAC1
    virt-install --name $VM_NAME2 --network=bridge:br0,mac=$VM_MAC2
    

    Now, I want to give Internet access to the VMs:

    brctl addif enp3s0 br0
    

    enp3s0 is my primary interface. As soon as I run this command, my host loses its IP and access to the Internet. Even when I give it an IP the problem persists:

    dhclient enp3s0
    

    Neither host, nor the VMs have access to the Internet.