Linux下kvm创建的虚拟机,虚拟机和宿主机网络配置方法
在 KVM 宿主机下创建的虚拟机,可以使用桥接模式、NAT 模式或者直接连接宿主机物理网卡的模式来进行网络配置。以下是在 Linux KVM 宿主机下创建的虚拟机的网络配置方法:
- 桥接模式
桥接模式可以使虚拟机直接通过宿主机的物理网卡连接到网络,可以使虚拟机获得独立的 IP 地址。具体步骤如下:
- 在宿主机上创建一个虚拟网桥,使用以下命令:
brctl addbr br0
ifconfig br0 up
- 将宿主机的物理网卡连接到虚拟网桥,使用以下命令:
brctl addif br0 eth0
其中,eth0
是宿主机的物理网卡名称。
- 在虚拟机中,指定网络接口为桥接模式,使用以下命令:
virsh edit <vm-name>
在 XML 配置文件中添加以下内容:
<interface type='bridge'>
<mac address='52:54:00:xx:xx:xx'/>
<source bridge='br0'/>
<model type='virtio'/>
</interface>
其中,<mac address='52:54:00:xx:xx:xx'/>
是虚拟机的 MAC 地址,<source bridge='br0'/>
是连接到虚拟网桥 br0
。
- 在虚拟机中配置 IP 地址和网关,使用以下命令:
sudo ip addr add <ip-address>/<netmask> dev eth0
sudo ip route add default via <gateway-ip-address>
其中,<ip-address>
是虚拟机的 IP 地址,<netmask>
是虚拟机的子网掩码,<gateway-ip-address>
是宿主机的 IP 地址。
- NAT 模式
NAT 模式可以使虚拟机通过宿主机的 IP 地址访问网络,但无法直接从外部访问虚拟机。具体步骤如下:
- 在虚拟机中,指定网络接口为 NAT 模式,使用以下命令:
virsh edit <vm-name>
在 XML 配置文件中添加以下内容:
<interface type='network'>
<mac address='52:54:00:xx:xx:xx'/>
<source network='default'/>
<model type='virtio'/>
</interface>
其中,<mac address='52:54:00:xx:xx:xx'/>
是虚拟机的 MAC 地址。
- 在虚拟机中配置 IP 地址和网关,使用以下命令:
sudo ip addr add <ip-address>/<netmask> dev eth0
sudo ip route add default via <gateway-ip-address>
其中,<ip-address>
是虚拟机的 IP 地址,<netmask>
是虚拟机的子网掩码,<gateway-ip-address>
是宿主机的 IP 地址。
- 直接连接物理网卡模式
直接连接物理网卡模式可以使虚拟机通过宿主机的物理网卡访问网络,但需要在虚拟机中手动配置 IP 地址和网关。具体步骤如下:
- 在虚拟机中,指定网络接口为直接连接物理网卡模式,使用以下命令:
virsh edit <vm-name>
在 XML 配置文件中添加以下内容:
<interface type='direct'>
<mac address='52:54:00:xx:xx:xx'/>
<source dev='eth0'/>
<model type='virtio'/>
</interface>
其中,<mac address='52:54:00:xx:xx:xx'/>
是虚拟机的 MAC 地址,<source dev='eth0'/>
是连接到宿主机的物理网卡。
- 在虚拟机中手动配置 IP 地址和网关,使用以下命令:
sudo ip addr add <ip-address>/<netmask> dev eth0
sudo ip route add default via <gateway-ip-address>
其中,<ip-address>
是虚拟机的 IP 地址,<netmask>
是虚拟机的子网掩码,<gateway-ip-address>
是宿主机的 IP 地址。
相关推荐















