centos7上kvm的安装与使用

一般都是虚拟机上使用的,请先将虚拟机的虚拟化打开

安装准备好需要的工具

xshell 和 xmanager(windows上安装的远程管理工具)

xshell下载地址:http://sw.bos.baidu.com/sw-search-sp/software/2e288f0f946d9/Xshell5_5.0.1326.exe

xmanager下载地址:http://sw.bos.baidu.com/sw-search-sp/software/7c666e01b0271/xmgr5_5.0.1049_wm.exe

请先都安装好在进行后面的操作

打开xshell –》文件 –》属性 –》隧道 设置成这样

未分类

使cpu支持虚拟化

更改的时候请关闭虚拟机,不然是无法修改的

未分类

inter的cpu

grep 'vmx' /proc/cpuinfoBashCopy

amd的cpu

grep 'svm' /proc/cpuinfoBashCopy

只要有内容就表示支持

安装依赖及kvm

yum  -y  install epel-release
yum -y install qemu-kvm libvirt virt-manager 
yum -y install dejavu-lgc-sans-fonts   #这个是解决xmanager乱码的问题BashCopy

运行下面的命令,有如下返回值表示成功

[root@localhost ~]# lsmod | grep kvm
kvm_intel             170181  0 
kvm                   554609  1 kvm_intel
irqbypass              13503  1 kvmBashCopy

启动服务

systemctl start libvirtd
systemctl enable libvirtdBashCopy

启动创建虚拟机窗口

virt-managerBashCopy

未分类

先不急,上传镜像上去,我很懒,直接上传到/root/下面了

[root@localhost ~]# ls
anaconda-ks.cfg  CentOS-7-x86_64-Minimal-1611.isoBashCopy

使用xmanager的图形来创建centos 7

未分类

直接点前进

未分类

选择镜像

未分类

未分类

找到后直接打开

未分类

继续

未分类

提示可能没权限,不管,直接yes

未分类

后面是配额,我们继续前进

未分类

磁盘大小

未分类

可以继续前进

这一步很关键,不选择好的话,后面无法使用键盘,我们勾上,选择在安装前先进行配置,下面还有个网卡选择,因为需要花点时间测试,网卡的部分将在下一文章讲解

未分类

然后点击finish

出来下面的,记得选择跟下图一样的配置,点击apply

未分类

然后就会看到下面的安装画面

未分类

基础教程安装完成。

安装WebVirtMgr来管理KVM虚拟机

WebVirtMgr 是一个基于 libvirt 开发的用来管理虚拟机的 Web 界面。纯 Python 开发的,前端是基于 Python 的 Django,后端是基于 Libvirt 的 Python 接口。
它允许您创建和配置新的域,并调整域的资源分配。VNC 查看器向 guest 域提供完整的图形控制台。仅支持 KVM 虚拟。

Web 界面需要 Nginx 反代,本文以 CentOS 7 系统在 OneinStack 一键包下安装 LNMP 环境为例。

WebVirtMgr 面板 和 KVM 服务器 可以安装在同一主机,也可以分开安装的。我是把 WebVirtMgr 面板 装在相对国内访问稍快点的美西 VPS 上。

使用 libvirt 配置的 KVM虚拟机 网络可以使用 bridged(桥接模式)和 NAT(网络地址转换模式)。本文以单 IP 使用 NAT 模式为例。

安装 WebVirtMgr

sudo yum -y install epel-release
sudo yum -y update
sudo yum -y install git python-pip libvirt-python libxml2-python python-websockify supervisor
sudo yum -y install gcc python-devel
sudo pip install numpy

安装 Python requirements 并设置 Django 环境

cd /data/wwwroot/
git clone git://github.com/retspen/webvirtmgr.git
cd webvirtmgr
sudo pip install -r requirements.txt
./manage.py syncdb
./manage.py collectstatic

执行过程中按要求输入用户信息:

You just installed Django's auth system, which means you don't have any superusers defined.
Would you like to create one now? (yes/no): yes (Put: yes)
Username (Leave blank to use 'admin'): admin (Put: your username or login)
E-mail address: [email protected] (Put: your email)
Password: xxxxxx (Put: your password)
Password (again): xxxxxx (Put: confirm password)
Superuser created successfully.

可添加额外的超级用户

./manage.py createsuperuser

设置 Nginx

vim /usr/local/nginx/conf/nginx.conf  #按自己实际 Nginx 配置文件路径
*** 省略

  server {
    listen 9556;
    server_name $hostname;

    location /static/ {
        root /data/wwwroot/webvirtmgr/webvirtmgr;
        expires max;
    }

    location / {
        proxy_pass http://127.0.0.1:8000;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-for $proxy_add_x_forwarded_for;
        proxy_set_header Host $host:$server_port;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_connect_timeout 600;
        proxy_read_timeout 600;
        proxy_send_timeout 600;
        client_max_body_size 1024M;
    }
  }

*** 省略
nginx -t
sudo service nginx restart
chown -R www.www /data/wwwroot/webvirtmgr

设置 Supervisor 管理进程

vim /etc/supervisord.d/webvirtmgr.ini
[program:webvirtmgr]
command=/usr/bin/python /data/wwwroot/webvirtmgr/manage.py run_gunicorn -c /data/wwwroot/webvirtmgr/conf/gunicorn.conf.py
directory=/data/wwwroot/webvirtmgr
autostart=true
autorestart=true
logfile=/var/log/supervisor/webvirtmgr.log
log_stderr=true
user=www

[program:webvirtmgr-console]
command=/usr/bin/python /data/wwwroot/webvirtmgr/console/webvirtmgr-console
directory=/data/wwwroot/webvirtmgr
autostart=true
autorestart=true
stdout_logfile=/var/log/supervisor/webvirtmgr-console.log
redirect_stderr=true
user=www

若系统、环境跟本文不符请注意修改文中路径和用户权限

systemctl restart supervisord
systemctl enable supervisord

以上已完成 WebVirtMgr 面板的安装,在浏览器 http://ip:9556 打开就能看到登陆面板了,下面安装 KVM 主机服务器。

安装 libvirt 和 KVM

wget -O - http://retspen.github.io/libvirt-bootstrap.sh | sudo sh

建立两个文件夹存放 虚拟机镜像文件 和 安装系统所需的ISO文件(之后要在面板的 “存储池” 里设置)

mkdir -p /home/kvm/img
mkdir -p /home/kvm/iso

安装 TCP 授权

sudo saslpasswd2 -a libvirt dane                  #添加用户和设置密码。
sudo sasldblistusers2 -f /etc/libvirt/passwd.db   #查看用户
virsh -c qemu+tcp://127.0.0.1/system nodeinfo     #验证设置

配置防火墙

允许安装 WebVirtMgr 面板的主机访问 KVM 主机服务器

iptables -A INPUT -s 安装WebVirtMgr面板主机的IP -j ACCEPT
service iptables save
systemctl restart iptables.service

现在就可以登陆 WebVirtMgr 面板添加主机服务器和建立KVM虚拟机了。面板很简单不做记录。

切记:使用 NAT 模式 不需要按网上各种教程建立网桥桥接。

KVM 使用virtio驱动Windows Server 虚拟机

KVM安装Windows默认使用的是qemu虚拟化IDE硬盘模式,在这种情况下,IO性能比较低,如果使用virtio的方式可以提高虚拟机IO性能。而virtio所驱动的网卡,也将原来的百兆扩展到千兆。这里就简单介绍下如何使用virtio驱动安装window server 2008. 其它windows版本操作相同,只需选择对应的驱动即可。

使用virtio安装window虚拟机

KVM安装Windows需要使用virtio的驱动:

https://Fedoraproject.org/wiki/Windows_Virtio_Drivers#Direct_download

安装虚拟机步骤:

1、安装virtio驱动

wget https://fedorapeople.org/groups/virt/virtio-win/virtio-win.repo -O /etc/yum.repos.d/virtio-win.repo

yum install virtio-win -y

2、查看virtio-win提供的驱动

rpm -ql virtio-win | grep iso
/usr/share/virtio-win/virtio-win-0.1.126.iso
/usr/share/virtio-win/virtio-win.iso

3、安装windows

创建一个虚拟机磁盘:

qemu-img  create -f qcow2 win-2c8g150g.img 150G

使用virtio驱动安装虚拟机:

virt-install -n win-2c8g150g --vcpus=2 --ram=8192 --os-type=windows --os-variant=win2k8 
-c /vm/iso/cn_windows_server_2008_r2_sp1_x64.iso 
--disk path=/usr/share/virtio-win/virtio-win-0.1.126_amd64.vfd,device=floppy 
--disk path=/vm/win-2c8g150g.img,format=qcow2,bus=virtio --graphics vnc,listen=0.0.0.0 
--noautoconsole

提示: 这里是使用的是软盘方式加载,如果镜像和驱动都使用cdrom的方式加载,在有些情况系统会找不到启动镜像,导致无法启动. 加载的驱动有x86和amd64两种类型,64位系统选择amd64. 32为系统选择x86.

4、 安装过程中,在选择磁盘界面会找不到磁盘

选择“加载驱动”,“浏览”,找到“软盘驱动器”,点开后选择 “server 2008”确定,驱动加载完成后,磁盘就出现了,继续安装即可。

5、安装完成后,在设备管理器中可以看到使用的是virtio

未分类

在已安装的kvm虚拟机上添加virtio驱动

如果以传统的IDE硬盘模式安装可以使用如下命令:

virt-install  --virt-type kvm --name win-2c8g100g  --ram 8192  
-vcpus=2 -s 100 -c /vm/iso/cn_windows_server_2008_r2_sp1_x64.iso 
--os-type=windows -f /vm/win-2c8g100g.img --graphics vnc,listen=0.0.0.0 --noautoconsole

安装之后要使用virtio驱动,可以选择加载virtio驱动的iso文件到虚拟机光驱:

virsh  attach-disk  win-2c8g100g /usr/share/virtio-win/virtio-win.iso  hdb  --type cdrom

或者使用如下命令:

virsh change-media win-2c8g100g hdb /usr/share/virtio-win/virtio-win.iso

参考链接:https://superuser.com/questions/239870/change-cd-rom-via-virsh

修改虚拟机的xml文件,使其能发现virtio类型的设备,否则驱动无法安装:
增加一块virtio驱动的硬盘:

qemu-img  create -f qcow2 test.img 1G

修改虚拟机的xml文件,在原有的”disk type”区域增加一个test磁盘的配置:

  <disk type='file' device='disk'>
      <driver name='qemu' type='qcow2'/>
      <source file='/vm/test.img'/>
      <target dev='vdb' bus='virtio'/>
    </disk>

修改网卡类型为 virtio, 在 interface type 区域,修改model type=’virtio’ :

<interface type='bridge'>
      <mac address='52:54:00:39:f9:60'/>
      <source bridge='br0'/>
      <model type='virtio'/>

提示:如果不是使用vnc远程连接,需要新增一个网卡配置,在没有安装驱动前,使用上面的配置,虚拟机是断网状态。
修改完成之后,重启虚拟机:

virsh shutdown win-2c8g100g
virsh start win-2c8g100g

进入虚拟机,成功添加iso驱动程序后,进入虚拟机的设备管理器界面,在“系统设备”里面对相应的驱动进行更新:
更新驱动需要找到挂载的CD中 virtio-win.iso中的对应文件。驱动镜像中分别有四种驱动,他们对应关系为:

Balloon, the balloon driver, affects the PCI standard RAM Controller in the System devicesgroup.

vioserial, the serial driver, affects the PCI Simple Communication Controller in the System devices group.

NetKVM, the network driver, affects the Network adapters group. This driver is only available if a virtio NIC is configured. Configurable parameters for this driver are documented in Appendix A, NetKVM Driver Parameters.

viostor, the block driver, affects the Disk drives group. This driver is only available if a virtio disk is configured.

参考链接:

https://access.RedHat.com/documentation/en-US/Red_Hat_Enterprise_Linux/6/html/Virtualization_Host_Configuration_and_Guest_Installation_Guide/form-Virtualization_Host_Configuration_and_Guest_Installation_Guide-Para_virtualized_drivers-Mounting_the_image_with_virt_manager.html

如果找不到英文说明中对应的设备,使用如下方式:

对未知设备添加virtio驱动即可,如图:

未分类

安装驱动之后:

未分类

对应的磁盘驱动成功安装:

未分类

此时virtio驱动添加完成,修改虚拟机的xml文件,删除test.img的虚拟磁盘配置,修改启动磁盘驱动类型:

    <disk type='file' device='disk'>
      <driver name='qemu' type='qcow2'/>
      <source file='/vm/win-2c8g100g.img'/>
      <target dev='vda' bus='virtio'/>
      <address type='pci' domain='0x0000' bus='0x00' slot='0x07' function='0x0'/>
    </disk>

重启虚拟机即可。

kvm虚拟机挂载lvm卷

kvm虚拟机挂载lvm卷

virsh attach-disk kvm-3 /dev/vg_shkvm3/kvm-3-data vdb --driver qemu --mode shareable

登录到kvm-3

[root@sh-kvm-3-3 ~]# fdisk -l

Disk /dev/vda: 21.5 GB, 21474836480 bytes
16 heads, 63 sectors/track, 41610 cylinders
Units = cylinders of 1008 * 512 = 516096 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x00002155

   Device Boot      Start         End      Blocks   Id  System
/dev/vda1   *           3        1018      512000   83  Linux
Partition 1 does not end on cylinder boundary.
/dev/vda2            1018       41611    20458496   8e  Linux LVM
Partition 2 does not end on cylinder boundary.

Disk /dev/mapper/VolGroup-lv_root: 18.8 GB, 18798870528 bytes
255 heads, 63 sectors/track, 2285 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x00000000


Disk /dev/mapper/VolGroup-lv_swap: 2147 MB, 2147483648 bytes
255 heads, 63 sectors/track, 261 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x00000000


Disk /dev/vdb: 53.7 GB, 53687091200 bytes
16 heads, 63 sectors/track, 104025 cylinders
Units = cylinders of 1008 * 512 = 516096 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x00000000
[root@sh-kvm-3-3 ~]# fdisk /dev/vdb #分区 
Device contains neither a valid DOS partition table, nor Sun, SGI or OSF disklabel
Building a new DOS disklabel with disk identifier 0x93edb871.
Changes will remain in memory only, until you decide to write them.
After that, of course, the previous content won't be recoverable.

Warning: invalid flag 0x0000 of partition table 4 will be corrected by w(rite)

WARNING: DOS-compatible mode is deprecated. It's strongly recommended to
         switch off the mode (command 'c') and change display units to
         sectors (command 'u').

Command (m for help): n
Command action
   e   extended
   p   primary partition (1-4)
p
Partition number (1-4): 1
First cylinder (1-104025, default 1): 
Using default value 1
Last cylinder, +cylinders or +size{K,M,G} (1-104025, default 104025): 
Using default value 104025

Command (m for help): p

Disk /dev/vdb: 53.7 GB, 53687091200 bytes
16 heads, 63 sectors/track, 104025 cylinders
Units = cylinders of 1008 * 512 = 516096 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x93edb871

   Device Boot      Start         End      Blocks   Id  System
/dev/vdb1               1      104025    52428568+  83  Linux

Command (m for help): t
Selected partition 1
Hex code (type L to list codes): 8e
Changed system type of partition 1 to 8e (Linux LVM)

Command (m for help): w
The partition table has been altered!

Calling ioctl() to re-read partition table.
Syncing disks.

挂载lvm 到data目录

mkfs.ext4 /dev/vdb1
pvcreate /dev/vdb1
vgextend VolGroup /dev/vdb1
lvcreate -n data -L 30G VolGroup
mkdir /data
mkfs.ext4 /dev/VolGroup/data
mount /dev/VolGroup/data  /data/
echo "/dev/mapper/VolGroup-data    /data                   ext4    defaults        1 1"  >> /etc/fstab

扩容根目录

# lvextend -l +100%FREE /dev/mapper/VolGroup-lv_root
# resize2fs /dev/mapper/VolGroup-lv_root
# df -h
Filesystem            Size  Used Avail Use% Mounted on
/dev/mapper/VolGroup-lv_root
                      103G   40G   58G  41% /
tmpfs                 4.9G   12K  4.9G   1% /dev/shm
/dev/xvda1            477M  153M  299M  34% /boot

修复由于fstab文件错误导致KVM虚拟机无法启动的问题

最近客户反馈虚拟机在启动的过程中出现报错,详细如下图所示,在与他了解的过程中得知在重启之前在编辑过/etc/fstab文件,估计是因为这个原因造成的,于是有了这个修复的过程。

未分类

通过live CD启动Linux,我这里用的是KALI的系统,当然其它任何带live cd的系统光盘都可以。

未分类

启动完成以后,如果你使用mount /dev/vdb2 /mnt会出现报错:“不知道的文件系统”,这是因为LVM2的磁盘格式没有办法直接mount,需要通过以下步骤才能够进行mount的操作。

1、确保已经安装lvm2

未分类

2、确保能够通过fdisk -lu 识别所有物理卷

未分类

3、运行pvscan扫描所有磁盘的物理卷,这是为了确保您的LVM2硬盘能够被检测到。

未分类

4、运行vgscan扫描卷组

未分类

5、激活所有可用的卷组,这是显示已经激活3个逻辑卷

未分类

6、运行lvscan扫描所有磁盘的逻辑卷。您现在可以看到逻辑卷内的分区已经活动。

未分类

7、mount你需要编辑的逻辑卷至/mnt目录

mount /dev/cl/root /mnt

8、修改fstab文件

vi /mnt/etc/fstab

删除对应两行

未分类

9、重启服务器即可

reboot

未分类

kvm的网络桥接模式与快照管理介绍

先确认系统是否支持虚拟化技术

egrep '(vmx|svm)' --color=always /proc/cpuinfo

安装基本需要的组件

yum install -y qemu-kvm bridge-utils

给qemu-kvm命令添加到环境变量

ln -s /usr/libexec/qemu-kvm /sbin/

转载kvm模块

modprobe kvm

创建一个文件夹,用来存放将要创建的系统文件内容

qemu-img create -f qcow2 -o preallocation=metadata /PATH/FILENAME.img 20G

关闭networkmanager服务,并且创建一个br0的桥接网卡

cp /etc/sysconfig/network-scripts/ifcfg-eth0 /etc/sysconfig/network-scripts/ifcfg-br0

ifcfg-eth0作出如下配置(此时eth0已经虚拟成一个交换机)

未分类

ifcfg-br0作出如下配置

未分类

创建完成使用命令查看

brctl show

未分类

编写一个启动网络脚本

vim /root/qemu-ifup

未分类

使用qemu-kvm创建并启动系统(安装windows 将if=virto改为if=ide即可)

qemu-kvm -cpu host -smp 1 -m 1G -name linux -drive  file=linux.img,media=disk,format=qcow2,if=virtio -drive file=/isofile/CentOS-7-x86_64-Minimal-1503-01.iso,media=cdrom -boot order=dc,once=d -net nic,macaddr=00:00:00:00:00:01 -net tap,script=/root/qemu-ifup -vnc 192.168.3.125:1

在另一个tty查看端口是否打开

未分类

在另外一台安装图形界面的主机安装vnc

yum install -y tigervnc

vncviewer 192.168.3.125:5901

未分类

确认安装程序完成后结束qemu-kvm进程

未分类

使用下面命令基于img磁盘启动(-daemonize后台脱离tty)

qemu-kvm -cpu host -smp 1 -m 1G -name centos7 -drive file=/kvm/linux.img,media=disk,format=qcow2,if=virtio -net nic,macaddr=00:00:00:00:00:01 -net tap,script=/root/qemu-ifup -vnc 192.168.3.125:1 -daemonize

未分类

快照使用方法:

创建快照

qemu-img snapshot -c 快照名称 /系统img/文件

查看创建的快照

qemu-img snapshot -l /系统img文件

快照恢复

qemu-img snapshot -a 快照的id号 /img文件

删除快照

qemu-img snapshot -d 快照id号 /img文件

快照检查(如遇到此类问题 Image is corrupt; cannot be opened read/write)

qemu-img check -r all /img文件位置

实验步骤:

未分类

安装配置KVM虚拟机

1、硬件环境检测

grep -E –color ‘vmx|svm’ /proc/cpuinfo

有输出代表cpu支持

2、软件包安装

yum install qemu-kvm qemu-img libvirt-python python-virtinst libvirt-client virt-viewer bridge-utils

—>少了一些组件也可

yum groupinstall -y Virtualization “Virtualization Client” “Virtualization Platform” “Virtualization Tools”

使用桥接网络安装bridge-utils包

yum -y install bridge-utils

3、关闭防火墙对IPv6支持并关闭selinux功能

chkconfig ip6tables off
setenforce 0 临时关闭
sed -i ‘s/SELINUX=enforcing/SELINUX=disabled/g’ /etc/selinux/config

4、查看模块并启动进程

查看KVM模块:lsmod | grep kvm
service libvirtd restart启动libvirt进程
modprobe kvm
modprobe kvm-intel
modprobe -ls | grep kvm

5、将网卡模式修改为桥接模式

首先复制原em1和em2网卡为br1和br2,将em1的配置文件修改为:

DEVICE=”em1“
BOOTPROTO=”static”
HWADDR=”30:85:A9:9F:67:74″
NM_CONTROLLED=”no”
ONBOOT=”yes”
TYPE=”Ethernet”
UUID=”34096e10-ff72-4142-b7b3-e290d200b68a”
BRIDGE=”br1″
命令:virsh iface-bridge em3 br3

虚拟安装脚本create_kvm.sh内容:

virt-install 
–name Test 
–ram 1536 
–vcpus=1 
–disk path=/data/img/kvm_Test.img,size=50 
–network bridge=br0 
–cdrom=/opt/iso/CentOS-6.8-x86_64-minimal.iso 
–accelerate 
–vnclisten=0.0.0.0 
–vncport=5911 
–vnc

启动虚机:

virsh start Test

查看虚拟状态:

virsh list –all

raw转换为qcow2格式:

qemu-img convert -f raw -0 qcow2 /data/img/kvm-Test.img /data/img/kvm-Test.qcow2
确认:
qemu-img info /data/img/kvm-Test.qcow2

修改虚机配置文件:

virsh edit Test

复制(克隆)一台虚拟服务器:

virt-clone -o Test -n Test -f /data/img/kvm-Test1.qcow2

虚机当前运行产生的相关文件所在目录:

/var/run/libvirt/qemu/
/etc/libvirt/qemu配置文件目录
virsh shutdown Test

如果报错,先暂停该虚机业务

virsh suspend Test
cp -av /data/img/kvm-Test1.qcow2  /data/img/kvm-Test2.qcow2
virsh dumpxml Test1 > /etc/libvirt/qemu/Test2.xml
virsh define /etc/libvirt/qemu/Test2.xml

虽然克隆完毕,但我们还不能启动,需编辑配置文件先修改vnc端口

virsh edit Test2

注意:与其他虚拟服务器vnc端口不一致而且要在可用范围内。
保存配置后尝试启动

virsh start Test2

通过vnc viewer连接
ifconfig命令查看后发现没网卡相关信息

more /etc/udev/rules.d/70-persistent-net.rules >>/etc/sysconfig/network-scripts/ifcfg-eth0

然后修改MAC地址和对应IP并注释无关代码后保存

service network restart

重启服务:

service libvirtd restart

再次尝试启动虚拟机Test2(略)

yum install -y acpid
service acpid start
chkconfig acpid on

kvm 基础镜像与增量镜像

KVM虚拟机的基本镜像和增量镜像

1、概述

实验目的:通过一个基础镜像(node.img),里面把各个虚拟机都需要的环境都搭建好,然后基于这个镜像建立起一个个增量镜像,每个增量镜像对应一个虚拟机,虚拟机对镜像中所有的改变都记录在增量镜像里面,基础镜像始终保持不变。
功能:节省磁盘空间,快速复制虚拟机。
环境:
基本镜像文件:node.img 虚拟机ID:node
增量镜像文件:node4.img 虚拟机ID:node4
要求:以基本镜像文件node.omg为基础,创建一个镜像文件node4.img,以此创建一个虚拟机机node4,虚拟机node4的改变将存储于node4.img中。

2、创建增量镜像文件

[root@target kvm_node]#qemu-img create -b node.img -f qcow2 node4.img
[root@target kvm_node]# qemu-img info node4.img 
image: node4.img
file format: qcow2
virtual size: 20G (21495808000 bytes)
disk size: 33M
cluster_size: 65536
backing file: node.img (actual path: node.img)

注:该实验只是针对qcow2格式的镜像文件,未测试raw格式的镜像文件是否可行。

3、创建虚拟机node4的XML配置文件

[root@target kvm_node]# cp /etc/libvirt/qemu/node.xml /etc/libvirt/qemu/node4.xml
[root@target kvm_node]# vim /etc/libvirt/qemu/node4.xml 
<domain type='kvm'>
  <name>node4</name>                                  #node4的虚拟机名,须修改,否则与基本虚拟机冲突
  <uuid>4b7e91eb-6521-c2c6-cc64-c1ba72707fe4</uuid>   #node4的UUID,必须修改,否则与基本虚拟机冲突
  <memory>524288</memory>
  <currentMemory>524288</currentMemory>
  <vcpu cpuset='0-1'>2</vcpu>
  <os>
    <type arch='x86_64' machine='rhel5.4.0'>hvm</type>
    <boot dev='hd'/>
  </os>
  <features>
    <acpi/>
    <apic/>
    <pae/>
  </features>
  <clock offset='localtime'/>
  <on_poweroff>destroy</on_poweroff>
  <on_reboot>restart</on_reboot>
  <on_crash>restart</on_crash>
  <devices>
    <emulator>/usr/libexec/qemu-kvm</emulator>
    <disk type='file' device='disk'>
      <driver name='qemu' type='qcow2'/>
      <source file='/virhost/kvm_node/node4.img'/>    #将原指向/virhost/kvm_node/node.img改为node4.img
      <target dev='vda' bus='virtio'/>
      <address type='pci' domain='0x0000' bus='0x00' slot='0x05' function='0x0'/>
    </disk>
    <interface type='bridge'>
      <mac address='54:52:00:69:d5:f4'/>             #修改网卡MAC,防止冲突
      <source bridge='br0'/>
      <model type='virtio'/>
      <address type='pci' domain='0x0000' bus='0x00' slot='0x03' function='0x0'/>
    </interface>
    <interface type='bridge'>
      <mac address='54:52:00:69:d5:e4'/>            #修改网卡MAC,防止冲突
      <source bridge='br0'/>
      <model type='virtio'/>
      <address type='pci' domain='0x0000' bus='0x00' slot='0x04' function='0x0'/>
    </interface>
    <serial type='pty'>
      <target port='0'/>
    </serial>
    <console type='pty'>
      <target type='serial' port='0'/>
    </console>
    <input type='mouse' bus='ps2'/>
    <graphics type='vnc' port='5904' autoport='no' listen='0.0.0.0' passwd='xiaobai'>
      <listen type='address' address='0.0.0.0'/>
    </graphics>
    <video>
      <model type='cirrus' vram='9216' heads='1'/>
      <address type='pci' domain='0x0000' bus='0x00' slot='0x02' function='0x0'/>
    </video>
    <memballoon model='virtio'>
      <address type='pci' domain='0x0000' bus='0x00' slot='0x06' function='0x0'/>
    </memballoon>
  </devices>
</domain>

4、根据xml配置定义虚拟机node4

[root@target kvm_node]#virsh define /etc/libvirt/qemu/node4.xml
[root@target kvm_node]#virsh start node4  

5、测试

[root@target kvm_node]# du -h node.img

6.3G node.img

[root@target kvm_node]# du -h node4.img

33M node4.img

[root@node4 ~]# dd if=/dev/zero of=test bs=1M count=200   #在虚拟机node4上增量200M大小文件
200+0 records in
200+0 records out
209715200 bytes (210 MB) copied, 1.00361 seconds, 209 MB/s
[root@target kvm_node]# du -h node.img                    #基本镜像文件node.img大小未变

6.3G node.img

[root@target kvm_node]# du -h node.img                    #增量镜像文件node4.img增加200M了
234M    node4.img

KVM虚拟机virsh管理常用命令

管理kvm虚拟机

常用的虚拟机管理命令

  • 列出所有的虚拟机
1  virsh list --all
  • 显示虚拟机信息
1  virsh dominfo kvm-1
  • 显示虚拟机内存和cpu的使用情况
1  yum install virt-top -y
2  virt-top
  • 显示虚拟机分区信息
1  virt-df kvm-1
  • 关闭虚拟机(shutodwn)
1  virsh shutdown kvm-1
  • 启动虚拟机
1  virsh start kvm-1
  • 设置虚拟机(kvm-1)跟随系统自启
1  virsh autostart kvm-1
  • 关闭虚拟及自启
1  virsh autostart --disable kvm-1
  • 删除虚拟机
1  virsh undefine kvm-1
  • 通过控制窗口登录虚拟机
virsh console kvm-1

给虚拟机添加硬盘

添加硬盘(lvm卷)或者USB到虚拟机上

1  virsh attach-disk kvm-1 /dev/sdb vbd --driver qemu --mode shareable
  • 使用完成之后可以卸载usb
1  virsh detach-disk kvm vdb

添加lvm卷,并挂载

[root@sh-kvm-1 ~]# lvcreate -n kvm-1-data -L 50G vg_shkvm1
[root@sh-kvm-1 ~]# virsh attach-disk kvm-1 /dev/vg_shkvm1/kvm-1-data vdb --driver qemu --mode shareable
Disk attached successfully
# 登录到kvm-1上查看lvm是否已经被挂载
[root@sh-kvm-1 ~]# virsh console kvm-1 # 输入kvm-1的用户和密码
[root@sh-kvm-1-1 ~]# fdisk -l # 查看硬盘挂载情况

Disk /dev/vda: 21.5 GB, 21474836480 bytes
16 heads, 63 sectors/track, 41610 cylinders
Units = cylinders of 1008 * 512 = 516096 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x00058197

   Device Boot      Start         End      Blocks   Id  System
/dev/vda1   *           3        1018      512000   83  Linux
Partition 1 does not end on cylinder boundary.
/dev/vda2            1018       41611    20458496   8e  Linux LVM
Partition 2 does not end on cylinder boundary.

Disk /dev/mapper/VolGroup-lv_root: 18.8 GB, 18798870528 bytes
255 heads, 63 sectors/track, 2285 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x00000000


Disk /dev/mapper/VolGroup-lv_swap: 2147 MB, 2147483648 bytes
255 heads, 63 sectors/track, 261 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x00000000


Disk /dev/vdb: 53.7 GB, 53687091200 bytes  # 新添加的硬盘
16 heads, 63 sectors/track, 104025 cylinders
Units = cylinders of 1008 * 512 = 516096 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x00000000
  • 格式化新添加的vdb,并添加到lvm组中
# 对新添加的硬盘分区
[root@sh-kvm-1-1 ~]# fdisk /dev/vdb
Device contains neither a valid DOS partition table, nor Sun, SGI or OSF disklabel
Building a new DOS disklabel with disk identifier 0xf04b6807.
Changes will remain in memory only, until you decide to write them.
After that, of course, the previous content won't be recoverable.

Warning: invalid flag 0x0000 of partition table 4 will be corrected by w(rite)

WARNING: DOS-compatible mode is deprecated. It's strongly recommended to
         switch off the mode (command 'c') and change display units to
         sectors (command 'u').

Command (m for help): m  # 查看帮助
Command action
   a   toggle a bootable flag
   b   edit bsd disklabel
   c   toggle the dos compatibility flag
   d   delete a partition
   l   list known partition types
   m   print this menu
   n   add a new partition
   o   create a new empty DOS partition table
   p   print the partition table
   q   quit without saving changes
   s   create a new empty Sun disklabel
   t   change a partition's system id
   u   change display/entry units
   v   verify the partition table
   w   write table to disk and exit
   x   extra functionality (experts only)
Command (m for help): n  #添加一个分区
Command action
   e   extended
   p   primary partition (1-4)
p  #选择添加一个扩展分区
Partition number (1-4):
Value out of range.
Partition number (1-4): 1
First cylinder (1-104025, default 1):
Using default value 1
Last cylinder, +cylinders or +size{K,M,G} (1-104025, default 104025):
Using default value 104025

Command (m for help): t  #改变分区的格式
Selected partition 1
Hex code (type L to list codes): 8e  #改成lvm
Changed system type of partition 1 to 8e (Linux LVM)

Command (m for help): w  # 保存更改
root@sh-kvm-1-1 ~]# mkfs.ext4 /dev/vdb1  # 格式化分区
mke2fs 1.41.12 (17-May-2010)
Filesystem label=
OS type: Linux
Block size=4096 (log=2)
Fragment size=4096 (log=2)
Stride=0 blocks, Stripe width=0 blocks
3276800 inodes, 13107142 blocks
655357 blocks (5.00%) reserved for the super user
First data block=0
Maximum filesystem blocks=4294967296
400 block groups
32768 blocks per group, 32768 fragments per group
8192 inodes per group
Superblock backups stored on blocks:
    32768, 98304, 163840, 229376, 294912, 819200, 884736, 1605632, 2654208,
    4096000, 7962624, 11239424

Writing inode tables: done
Creating journal (32768 blocks): done
Writing superblocks and filesystem accounting information: done

This filesystem will be automatically checked every 28 mounts or
180 days, whichever comes first.  Use tune2fs -c or -i to override.
[root@sh-kvm-1-1 ~]# pvc reate /dev/vdb1   # 创建pv
vdb   vdb1
[root@sh-kvm-1-1 ~]# vgextend VolGroup /dev/vdb  # 扩展lvm vg
vdb   vdb1
[root@sh-kvm-1-1 ~]# vgs
  VG       #PV #LV #SN Attr   VSize  VFree
  VolGroup   2   2   0 wz--n- 69.50g 50.00g
# 从上面能看出,新添加的 已经加到lvm组中

改变虚拟机的参数

通过命令行更改创建之后虚拟机的内存,cpu等信息

  • 更改内存
# 1. 查看虚拟机当前内存
[root@sh-kvm-1 ~]# virsh dominfo kvm-1 | grep memory
Max memory:     4194304 KiB
Used memory:    4194304 KiB

# 2、动态设置内存为512MB,内存减少
virsh setmem kvm-1 524288
# 注意单位必须是KB

# 3、查看内存变化
# virsh dominfo kvm-1 | grep memory
Max memory: 14194304 KiB
Used memory: 524288 kiB

# 4、内存增加
virsh shutdown kvm-1
virsh edit kvm-1  # 直接更改memory
virsh create /etc/libvirt/demu/kvm-1/xml
# 之后操作1,2,3步骤增加内存
  • 更改CPU

需要修改配置文件,因此需要停止虚拟机

virsh shutdown kvm-1
virsh edit kvm-1
#  2  # 4 &gt; 2
virsh create /etc/libvirt/demu/kvm-1/xml
  • 硬盘扩容
1. Create a 10-GB non-sparse file:
# dd if=/dev/zero of=/vm-images/vm1-add.img bs=1M count=10240
2. Shutdown the VM:
 # virsh shutdown vm1
3. Add an extra entry for ‘disk’ in the VM's XML file in /etc/libvirt/qemu. You can look copy &amp; paste
the entry for your mail storage device and just change the target and address tags. For example:
 # virsh edit vm1




 <address />

 Add:




 <address />

 # 这里建议使用上面的添加硬盘的方式添加

删除虚拟机

  • 第一步,停掉虚拟机
1  virsh shutdown kvm-1
  • 第二步
1  virsh destroy kvm-1
  • 第三步
1  virsh undefine kvm-1
  • 第四部
1  rm /dev/vg_shkvm1/kvm-1  # 不建议删除硬盘

CentOS 6安装配置KVM

上一篇文章介绍过CentOS 6安装Xen,有点麻烦,因为自CentOS 6开始,虚拟化平台已经从xen转向KVM,所以在CentOS 6安装KVM还是非常的简单的。

1、安装KVM

  1. yum groupinstall Virtualization ‘Virtualization Client’

2、安装api支持

  1. yum install libvirt
  2. service libvirtd start

3、验证是否已经载入KVM模块

  1. $ lsmod | grep kvm
  2. kvm
  3. kvm_intel

4、使用virt-manager安装guest

virt-manager是一个api gui工具,可以很方便的管理虚拟机。下面简单介绍使用virt-manager安装虚拟机系统。
1)打开virt-manager,Add-connection,hypervisor选择QEMU/KVM,点击connect。
2)在连接localhost(QEMU)右键-NEW,输入guest名称,还有选择安装方式,我这里选择iso文件安装,点击forword。
3)选择iso文件路径,点击forword。
4)定义分配内存及cpu个数。
5)定义磁盘映像大小。
6)下一步就是常规的系统安装了。

5、使用virt-install安装guest

当你的CentOS没有桌面环境时,可以使用virt-install命令安装,如:
1、输入虚拟机名称
2、分配多少内存
3、定义虚拟机磁盘映像的位置
4、此步可以直接输入iso的位置或是url
5、进行系统常规安装