当前位置: > 虚拟化 Virtualization > KVM >

centos 7.2 kvm虚拟化配置以及常用操作

时间:2016-12-13 01:47来源:linux.it.net.cn 作者:IT
1. 开始安装kvm
a. 检查你的系统是否支持虚拟化
grep -Ei 'vmx|svm' /proc/cpuinfo
如果有输出内容,则支持,其中intelcpu支持会有vmx,amd cpu支持会有svm

b. 通过yum安装虚拟化的软件包
yum install -y kvmvirt-*  libvirt  bridge-utils qemu-img
说明:
kvm:软件包中含有KVM内核模块,它在默认linux内核中提供kvm管理程序
libvirts:安装虚拟机管理工具,使用virsh等命令来管理和控制虚拟机。
bridge-utils:设置网络网卡桥接。
virt-*:创建、克隆虚拟机命令,以及图形化管理工具virt-manager
qemu-img:安装qemu组件,使用qemu命令来创建磁盘等。




c. 检查kvm模块是否加载
lsmod |grep kvm
正常应该是:
kvm_intel             55496  3
kvm                  337772  1 kvm_intel

如果没有,需要执行 
modprobe kvm-intel
还没有就重启一下试试

d. 配置网卡
cd /etc/sysconfig/network-scripts/
cp ifcfg-eth0 ifcfg-br0
分别编辑eth0和br0
ifcfg-eth0改成如下:
DEVICE=eth0
HWADDR=00:0C:29:55:A7:0A
TYPE=Ethernet
UUID=2be47d79-2a68-4b65-a9ce-6a2df93759c6
ONBOOT=yes
NM_CONTROLLED=yes
BOOTPROTO=none
BRIDGE=br0


ifcfg-br0改成如下:
DEVICE=br0
#HWADDR=00:0C:29:55:A7:0A
TYPE=Bridge
#UUID=2be47d79-2a68-4b65-a9ce-6a2df93759c6
ONBOOT=yes
NM_CONTROLLED=yes
BOOTPROTO=static
IPADDR=192.168.11.17
NETMASK=255.255.255.0
GATEWAY=192.168.11.1
DNS1=202.106.0.20

说明:我的虚拟机是桥接模式,所以设置br0的ip和我的真机同样的网段,包括网关也是我路由器的ip,大家可以根据自己的环境去配置,目的是为了让虚拟机可以上网。

/etc/init.d/network restart
查看网卡如下:
br0       Linkencap:Ethernet  HWaddr 00:0C:29:55:A7:0A
          inetaddr:192.168.11.17  Bcast:192.168.11.255  Mask:255.255.255.0
          inet6addr: fe80::20c:29ff:fe55:a70a/64 Scope:Link
          UPBROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RXpackets:141326 errors:0 dropped:0 overruns:0 frame:0
          TXpackets:90931 errors:0 dropped:0 overruns:0 carrier:0
         collisions:0 txqueuelen:0
          RXbytes:456024940 (434.8 MiB)  TX bytes:10933593 (10.4 MiB)

eth0      Linkencap:Ethernet  HWaddr 00:0C:29:55:A7:0A
          inet6addr: fe80::20c:29ff:fe55:a70a/64 Scope:Link
          UPBROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RXpackets:341978 errors:0 dropped:0 overruns:0 frame:0
          TXpackets:90946 errors:0 dropped:0 overruns:0 carrier:0
         collisions:0 txqueuelen:1000
          RXbytes:468848861 (447.1 MiB)  TX bytes:10934699 (10.4 MiB)

lo        Linkencap:Local Loopback
          inetaddr:127.0.0.1  Mask:255.0.0.0
          inet6addr: ::1/128 Scope:Host
          UPLOOPBACK RUNNING  MTU:65536  Metric:1
          RXpackets:0 errors:0 dropped:0 overruns:0 frame:0
          TXpackets:0 errors:0 dropped:0 overruns:0 carrier:0
         collisions:0 txqueuelen:0
          RXbytes:0 (0.0 b)  TX bytes:0 (0.0 b)

virbr0    Linkencap:Ethernet  HWaddr 52:54:00:14:EF:D5
          inetaddr:192.168.122.1  Bcast:192.168.122.255  Mask:255.255.255.0
          UPBROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RXpackets:0 errors:0 dropped:0 overruns:0 frame:0
          TXpackets:0 errors:0 dropped:0 overruns:0 carrier:0
         collisions:0 txqueuelen:0
          RXbytes:0 (0.0 b)  TX bytes:0 (0.0 b)



e. 启动或重启libvirtd服务和messagebus 服务
/etc/init.d/libvirtd start
/etc/init.d/messagebus restart

此时可以查看网络接口列表
brctl show 结果如下:
bridge name     bridgeid               STPenabled     interfaces
br0            8000.000c2955a70a       no             eth0
virbr0         8000.52540014efd5       yes            virbr0-nic


2. 创建虚拟机
mkdir /data/   //创建一个存储虚拟机虚拟磁盘的目录,该目录所在分区必须足够大

virt-install \
--name  aming1 \
--ram 512 \
--disk path=/data/aming1.img,size=30 \
--vcpus 1 \
--os-type linux \
--os-variant rhel6 \
--network bridge=br0 \
--graphics none \
--console pty,target_type=serial \
--location'http://mirrors.163.com/centos/6.7/os/i386/' \
--extra-args 'console=ttyS0,115200n8 serial' 


说明:
--name  指定虚拟机的名字
--ram 指定内存分配多少
--disk path 指定虚拟磁盘放到哪里,size=30 指定磁盘大小为30G,这样磁盘文件格式为raw,raw格式不能做快照,后面有说明,需要转换为qcow2格式,如果要使用qcow2格式的虚拟磁盘,需要事先创建qcow2格式的虚拟磁盘。参考  http://www.361way.com/kvm-qcow2-preallocation-metadata/3354.html   示例:qemu-img create -f qcow2 -opreallocation=metadata  /data/test02.img 10G;  

--diskpath=/data/test02.img,format=qcow2,size=10,bus=virtio
--vcpus 指定分配cpu几个
--os-type 指定系统类型为linux
--os-variant 指定系统版本
--network  指定网络类型
--graphics 指定安装通过哪种类型,可以是vnc,也可以没有图形,在这里我们没有使用图形直接使用文本方式
--console 指定控制台类型
--location 指定安装介质地址,可以是网络地址,也可以是本地的一个绝对路径,(--location '/mnt/', 其中/mnt/下就是我们挂载的光盘镜像mount /dev/cdrom /mnt)如果是绝对路径,



已有本地镜像可以



virt-install \

--name  test02 \

--ram 512 \

--diskpath=/data/kvm/test02.qcow2,format=qcow2,size=10,bus=virtio \

--vcpus 1 \

--os-type linux \

--os-variant rhel7 \

--network bridge=br0 \

--graphics none \

--console pty,target_type=serial\

--location '/data/CentOS.iso' \

--extra-args'console=ttyS0,115200n8 serial'





会出现文本方式的安装界面,选择时区,安装包的选择(默认 Minial install)、root密码设置,创建新用户,以及网络配置。在此没看见有,注意设置一下DNS。



最后安装完,reboot就进入刚刚创建的虚拟机了。要想退回到宿主机,ctrl  ] 即可。

virsh list 可以列出当前的子机列表。

virsh start test01  启动test01

virsh console test01  可以进入指定的子机





3. 克隆虚拟机
virt-clone --original test01 --name template--file /data/clone1.img  
如果子机test01还未关机,则需要先关机,否则会报错:
ERROR    必须暂停或者关闭有要克隆设备的域。
关闭子机的方法是:
virsh shutdown test01

说明:默认,我们没有办法在宿主机直接shutdown自己,我们需要借助于子机上的acpid服务才可以,这个服务说白了就是让宿主机可以去调用子机的电源关闭的接口。所以,子机上需要安装并启动acpid服务。
先登录子机:
virsh console test01
登录后,安装acpid服务:
yum install -y acpid 
启动:
/etc/init.d/acpid start
按ctrl ] 退出来
此时再执行 virsh shutdowntest01 就可以啦。

克隆完后,virsh list all 就会发现clone1 这个子机,通过命令 
virsh start clone1 可以开启该子机。



4. virsh 常用操作
a. 开启子机
virsh start test01
也可以在开启的同时连上控制台
virsh start test01 --console

b. 关闭子机
virsh shutdown test01 (这个需要借助子机上的acpid服务)
另外一种方法是 
virsh destroy test01 

c. 让子机随宿主机开机自动启动
virsh autostart test01
解除自动启动
virsh autostart --disable test01 

d. 列出子机
virsh list  //只能列出启动的子机
virsh list --all  //可以把所有子机都列出来

e. 删除子机
virsh destroy clone1
virsh undefine clone1
rm -f /data/clone1.img

f. 挂起子机
virsh suspend test01

h. 恢复子机
virsh resume test01



5. 快照管理
a. 创建快照
virsh snapshot-create test01
会报错:
unsupported configuration: internal snapshot fordisk vda unsupported for storage type raw
这是因为raw格式的镜像不能做快照,所以需要先转换一下格式

b. 磁盘镜像转换格式
先查看当前子机磁盘镜像格式
qemu-img info /data/test01.img  
结果是:
image: /data/test01.img
file format: raw
virtual size: 30G (32212254720 bytes)
disk size: 1.6G


把raw格式转换为qcow格式(其实是复制了一份):
qemu-img convert -f raw -O qcow2 /data/test01.img/data/test01.qcow2

qemu-img info /data/test01.qcow2   //再次查看格式,结果如下
image: /data/test01.qcow2
file format: qcow2
virtual size: 30G (32212254720 bytes)
disk size: 1.1G
cluster_size: 65536


现在我们还需要编辑子机配置文件,让它使用新格式的虚拟磁盘镜像文件
virsh edit test01  //这样就进入了该子机的配置文件(/etc/libvirt/qemu/test01.xml),跟用vim编辑这个文件一样的用法
需要修改的地方是:
      <driver name='qemu'type='raw' cache='none'/>
      <sourcefile='/data/test01.img'/>

改为:
      <driver name='qemu'type='qcow2' cache='none'/>
      <sourcefile='/data/test01.qcow2'/>


c. 继续创建快照
virsh snapshot-create test01  //这次成功了,提示如下
Domain snapshot 1437248443 created


列出快照:
virsh snapshot-list test01

查看当前子机的快照版本:
virsh snapshot-current test01

test01子机的快照文件在  /var/lib/libvirt/qemu/snapshot/test01/  目录下


d.  恢复快照
首先需要关闭子机
virsh destroy test01

确认子机是否关闭
virsh domstate test01
关闭

vish snapshot-list test01  //结果是
名称              Creation Time            状态
------------------------------------------------------------
1437248443          2015-07-19 03:40:43 +0800 shutoff
1437248847          2015-07-19 03:47:27 +0800 running


virsh snapshot-revert test01  1437248443

e. 删除快照
virsh snapshot-delete test01  1437248847



6. 磁盘扩容

a. 对于raw格式的虚拟磁盘扩容

qemu-img info /data/kvm/test03.img //本身只有9G

1.  image: /data/kvm/test03.img

2.  file format: raw

3.  virtual size: 9.0G (9663676416 bytes)

4.  disk size: 1.1G




qemu-img resize /data/kvm/test03.img +2G

qemu-img info /data/kvm/test03.img //现在增加了2G

1.  image: /data/kvm/test03.img

2.  file format: raw

3.  virtual size: 11G (11811160064 bytes)

4.  disk size: 1.1G

5.   




virsh destroy test03  //关闭test03虚拟机
virsh start test03  //开启test03虚拟机
virsh console test03  //进入虚拟机

fdisk -l   查看已经磁盘分区已经增加
[root@localhost ~]# fdisk -l



但是磁盘挂载的空间并没有增加
[root@localhost ~]# df -h

Filesystem           Size  Used Avail Use%Mounted on

/dev/mapper/VolGroup-lv_root

                    6.5G  579M  5.6G  10% /

tmpfs               250M     0  250M   0%/dev/shm

/dev/vda1            477M  26M  427M   6% /boot








因为新增加的空间还没有划分使用。所以要继续分区:
[root@localhost ~]# fdisk /dev/vda

1.  WARNING: DOS-compatible mode is deprecated.It's strongly recommended to

2.          switch off the mode (command 'c') and change display units to

3.          sectors (command 'u').

4.   

5.  Command (m for help): p

6.   

7.  Disk /dev/vda: 11.8 GB, 11811160064 bytes

8.  16 heads, 63 sectors/track, 22885 cylinders

9.  Units = cylinders of 1008 * 512 = 516096bytes

10.Sector size(logical/physical): 512 bytes / 512 bytes

11.I/O size(minimum/optimal): 512 bytes / 512 bytes

12.Diskidentifier: 0x000099f3

13. 

14.  Device Boot      Start        End      Blocks  Id  System

15./dev/vda1  *           3       1018      512000  83  Linux

16.Partition 1does not end on cylinder boundary.

17./dev/vda2           1018      <font color="#ff0000">16645</font>    7875584   8e  Linux LVM

18.Partition 2does not end on cylinder boundary.

19. 

20.Command (mfor help):<font color="#ff0000"> n</font>

21.Commandaction

22.  e   extended

23.  p   primary partition (1-4)

24.p

25.Partitionnumber (1-4): <font color="#ff0000">3</font>

26.Firstcylinder (1-22885, default 1): <fontcolor="#ff0000">16646</font>

27.Lastcylinder, +cylinders or +size{K,M,G} (16646-22885, default 22885):

28.Usingdefault value 22885

29. 

30.Command (mfor help): p

31. 

32.Disk/dev/vda: 11.8 GB, 11811160064 bytes

33.16 heads, 63sectors/track, 22885 cylinders

34.Units =cylinders of 1008 * 512 = 516096 bytes

35.Sector size(logical/physical): 512 bytes / 512 bytes

36.I/O size(minimum/optimal): 512 bytes / 512 bytes

37.Diskidentifier: 0x000099f3

38. 

39.  Device Boot      Start        End      Blocks  Id  System

40./dev/vda1  *           3       1018      512000  83  Linux

41.Partition 1does not end on cylinder boundary.

42./dev/vda2           1018      16645     7875584   8e  Linux LVM

43.Partition 2does not end on cylinder boundary.

44.<fontcolor="#ff0000">/dev/vda3          16646       22885    3144960   83  Linux</font>

45. 

46.Command (mfor help): w

47.Thepartition table has been altered!

48. 

49.Callingioctl() to re-read partition table.

50. 

51.WARNING:Re-reading the partition table failed with error 16: Device or resource busy.

52.The kernelstill uses the old table. The new table will be used at

53.the nextreboot or after you run partprobe(8) or kpartx(8)

54.Syncingdisks.




然后再把这个/dev/vda3 加入到lvm里面去:

ls  /dev/vda3 如果没有这个分区,需要重启一下。

[root@localhost ~]# pvcreate/dev/vda3

1.    <spanstyle="line-height: 1.5; background-color: rgb(247, 247,247);">Physical volume "/dev/vda3" successfullycreated</span>




[root@localhost ~]# pvs

1.  PV        VG       Fmt  Attr PSize PFree

2.    /dev/vda2 <fontcolor="#ff0000"> VolGroup</font> lvm2a--  7.51g    0

3.    /dev/vda3          lvm2 ---  3.00g 3.00g




[root@localhost ~]# vgextendVolGroup /dev/vda3

1.  Volume group "VolGroup"successfully extended




[root@localhost ~]# vgs

1.  VG       #PV #LV #SNAttr   VSize  <fontcolor="#ff0000">VFree</font>

2.    VolGroup   2  2   0 wz--n- 10.50g <fontcolor="#ff0000">3.00g</font>




[root@localhost ~]# lvs

1.  LV      VG      Attr       LSize   PoolOrigin Data%  Meta%  Move Log Cpy%Sync Convert

2.    lv_root VolGroup-wi-ao----   6.71g

3.    lv_swap VolGroup -wi-ao----816.00m




[root@localhost ~]# lvextend -l +100%FREE /dev/VolGroup/lv_root

1.  Size of logical volume VolGroup/lv_rootchanged from 6.71 GiB (1718 extents) to 9.71 GiB (2485 extents).

2.    Logical volume lv_rootsuccessfully resized




[root@localhost ~]# df -h

1.  Filesystem           Size  Used Avail Use% Mounted on

2.  /dev/mapper/VolGroup-lv_root

3.                      6.5G  618M  5.6G  10% /

4.  tmpfs                250M    0  250M   0% /dev/shm

5.  /dev/vda1            477M   26M  427M   6% /boot




[root@localhost ~]# resize2fs /dev/VolGroup/lv_root

1.  resize2fs 1.41.12 (17-May-2010)

2.  Filesystem at /dev/VolGroup/lv_root ismounted on /; on-line resizing required

3.  old desc_blocks = 1, new_desc_blocks = 1

4.  Performing an on-line resize of/dev/VolGroup/lv_root to 2544640 (4k) blocks.

5.  The filesystem on /dev/VolGroup/lv_root isnow 2544640 blocks long.


[root@localhost ~]# df -h

1.  Filesystem           Size  Used Avail Use% Mounted on

2.  /dev/mapper/VolGroup-lv_root

3.                      <fontcolor="#ff0000">9.5G  </font>618M  8.4G   7% /

4.  tmpfs                250M    0  250M   0% /dev/shm

5.  /dev/vda1            477M   26M  427M   6% /boot




另外,如果是增加磁盘,思路是: 
创建磁盘: qemu-img create -fraw  /data/kvm/test03_2.img 5G
关闭虚拟机: virsh destroy test03
编辑配置文件: virsh edittest03  增加如下:

1.  <disk type='file'device='disk'>     

2.    <driver name='qemu'type='raw' cache='none'/>      

3.    <source file='/data/kvm/test03_2.img'/>     

4.    <target dev='vdb'bus='virtio'/>      

5.  </disk>


开启虚拟机:virsh start test03
进入虚拟机:virsh console test03
分区: fdisk /dev/vdb
格式化(略)
挂载(略)
当然也可以按照上面的思路把 /dev/vdb1 加入到 lvm里面去


b. qcow2格式
步骤基本上和raw一样。如果提示 This image format doesnot support resize, 检查一下你qemu-img create的时候,是否有加  preallocation=metadata 选项,如果有,就不能resize了。





7. 调整cpu和内存查看子机配置:
virsh dominfo test02
virsh edit  test02
修改:
  <memoryunit='KiB'>524288</memory>
  <currentMemoryunit='KiB'>524288</currentMemory>
  <vcpuplacement='static'>1</vcpu>

为:
  <memoryunit='KiB'>624288</memory>
  <currentMemoryunit='KiB'>624288</currentMemory>
  <vcpuplacement='static'>2</vcpu>


重启虚拟机:
virsh destroy test02
virsh start test02





8. 不重启虚拟机在线增加网卡
virsh domiflist test02  查看test02子机的网卡列表
virsh attach-interface test02 --type bridge--source br0   //命令行增加一块网卡
virsh dumpxml test02 >/etc/libvirsh/qemu/test02.xml   //命令行增加的网卡只保存在内存中,重启就失效,所以需要保存到配置文件中,其中/etc/libvirsh/qemu/test02.xml 为test02子机的配置文件
virsh console test02 //进入虚拟机后,执行
ifconfig -a
发现多了一个网卡  eth1





9. 虚拟机迁移

该方式要确保虚拟机是关机状态。
virsh shutdown test02
virsh dumpxml test02 >/etc/libvirt/qemu/test03.xml  // 如果是远程机器,需要把该配置文件拷贝到远程机器上
virsh domblklist test02  //查看test02子机的磁盘所在目录
Target     Source
------------------------------------------------
vda       /data/add1.qcow2
rsync -av /data/add1.qcow2/data/test03.qcow2   //如果是迁移到远程,则需要把该磁盘文件拷贝到远程机器上
vi /etc/libvirt/qemu/test03.xm  //因为是迁移到本机,配置文件用的是test02子机的配置,不改会有冲突,所以需要修改该文件,如果是远程机器不用修改
修改domname:
  <name>test03</name>
修改uuid(随便更改一下数字,位数不要变)
<uuid>77bb10bd-3ad8-8899-958d-756063002969</uuid>
修改磁盘路径:
    <disk type='file'device='disk'>
      <driver name='qemu'type='raw' cache='none'/>
      <source file='/data/test03.qcow2'/>
      <target dev='vda'bus='virtio'/>
      <address type='pci'domain='0x0000' bus='0x00' slot='0x05' function='0x0'/>
    </disk>

virsh list --all   //会发现新迁移的test03子机



(责任编辑:IT)
------分隔线----------------------------