现在的虚拟化架构越来越普遍了。最近摸索了下centos下如何构建KVM虚拟机NAT网络,在此记录下点滴。
1.硬件检测
KVM虚拟机需要CPU支持虚拟化技术。Intel的叫vmx,AMD的叫svm.
cat /proc/cpuinfo|grep svm
2.安装kvm内核
yum groupinstall KVM -y
安装完后载入确认
modprobe kvm-amd
lsmod|grep kvm
3.配置VNC
/etc/libvirt/qemu.conf
vnc_listen = "0.0.0.0"
/etc/init.d/libvirtd start
4.安装虚拟机:
virt-install --name os_11 --hvm --ram 512 --vcpus 2 --disk path=/opt/vms/os_11.img,size=20 --network network:default --accelerate --vnc --vncport=5911 --os-variant rhel5.4 --cdrom /root/ubuntu-11.04-server-amd64.iso -d
然后用VNC连接5911端口开始安装
5.克隆虚拟机:
virt-clone -o os_11 -n os_12 -f /data/vm/os_12.img
virt-clone -o os_11 -n os_13 -f /data/vm/os_13.img
修改虚拟机配置文件/etc/libvirt/qemu/os_12.xml的vnc端口
os_12 3aab5774-1810-9c67-4b97-24c9c9db071f 524288 524288 2 hvm destroy restart restart /usr/libexec/qemu-kvm
6.启动虚拟机(ubuntu 11.04):
virsh start os_11
virsh start os_12
virsh start os_13
7.查看virbr0的网段,默认192.168.122.1
vnc连接虚拟机设置os_11 IP:192.168.122.11
vnc连接虚拟机设置os_12 IP:192.168.122.12
vnc连接虚拟机设置os_13 IP:192.168.122.13
网卡配置文件:
auto lo
iface lo inet loopback
# The primary network interface
auto eth0
iface eth0 inet static
address 192.168.122.11
netmask 255.255.255.0
network 192.168.122.0
broadcast 192.168.122.255
gateway 192.168.122.1
8.此时应该可以ssh到虚拟机了,并且虚拟机上也能上网了。
9.注意问题
(1)确认安装libvirtd,virsh等相关依赖
(2)在物理机上需要配置允许IP转发:
echo 1 > /proc/sys/net/ipv4/ip_forward ,
vi /etc/sysctl.conf 修改net.ipv4.ip_forward = 1
(3)启用iptables服务,需要进行ip转发,重新设置ip转发用virsh net-start default,我的配置如下:
#iptables -L -vn
Chain INPUT (policy ACCEPT 1181K packets, 492M bytes)
pkts bytes target prot opt in out source destination
0 0 ACCEPT udp -- virbr0 * 0.0.0.0/0 0.0.0.0/0 udp dpt:53
0 0 ACCEPT tcp -- virbr0 * 0.0.0.0/0 0.0.0.0/0 tcp dpt:53
0 0 ACCEPT udp -- virbr0 * 0.0.0.0/0 0.0.0.0/0 udp dpt:67
0 0 ACCEPT tcp -- virbr0 * 0.0.0.0/0 0.0.0.0/0 tcp dpt:67
Chain FORWARD (policy ACCEPT 0 packets, 0 bytes)
pkts bytes target prot opt in out source destination
39 12560 ACCEPT all -- * virbr0 0.0.0.0/0 192.168.122.0/24 state RELATED,ESTABLISHED
56 3833 ACCEPT all -- virbr0 * 192.168.122.0/24 0.0.0.0/0
0 0 ACCEPT all -- virbr0 virbr0 0.0.0.0/0 0.0.0.0/0
0 0 REJECT all -- * virbr0 0.0.0.0/0 0.0.0.0/0 reject-with icmp-port-unreachable
0 0 REJECT all -- virbr0 * 0.0.0.0/0 0.0.0.0/0 reject-with icmp-port-unreachable
Chain OUTPUT (policy ACCEPT 953K packets, 48M bytes)
pkts bytes target prot opt in out source destination
(4)虚拟机的配置文件在/etc/libvirt/qemu/中,可以修改xml调整虚拟机的配置