Centos 安裝KVM並安裝虛擬機

需要注意的地方:

!!!如果修改了虛擬機XML配置,需要停止虛擬機,然後使用以下命令重新讀取XML配置!!!:

virsh define /etc/libvirt/qemu/centos7.xml

Linux服務器兩塊獨立的網卡最好不要配置同一網段的IP地址,不然有時會有些Bug。

virsh edit name 可以更改虛擬機配置

如果虛擬機需要使用雙網卡,virsh edit新增一塊網卡的配置,並且將新增的網卡掛載到宿主機另一塊網卡上即可。掛載在同一塊上也行

 

新增一個網卡:

virsh attach-interface cent_xu --type bridge --source br0
virsh dumpxml cent_xu > /etc/libvirt/qemu/cent_xu.xml

檢測是否支持KVM

KVM 是基於 x86 虛擬化擴展(Intel VT 或者 AMD-V) 技術的虛擬機軟件,所以查看 CPU 是否支持 VT 技術,就可以判斷是否支持KVM。有返回結果,如果結果中有vmx(Intel)或svm(AMD)字樣,就說明CPU的支持的。

cat /proc/cpuinfo | egrep 'vmx|svm'

flags   : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp lm constant_tsc arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc aperfmperf eagerfpu pni pclmulqdq dtes64 monitor ds_cpl vmx smx est tm2 ssse3 fma cx16 xtpr pdcm pcid dca sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm arat epb pln pts dtherm tpr_shadow vnmi flexpriority ept vpid fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid cqm xsaveopt cqm_llc cqm_occup_llc

關閉SELinux,將 /etc/sysconfig/selinux 中的 SELinux=enforcing 修改爲 SELinux=disabled

 

安裝 KVM 環境

通過 yum 安裝 kvm 基礎包和管理工具

# 安裝 kvm 基礎包
# ------------------------
yum -y install kvm

# 安裝 kvm 管理工具
# ------------------------
yum -y install qemu-kvm python-virtinst libvirt libvirt-python virt-manager libguestfs-tools bridge-utils virt-install

# qemu-kvm: KVM模塊

# pyhon-virtinst: 包含python模塊和工具(virt-install,virt-clone和virt-image),
# 用於安裝和克隆虛擬機使用libvirt。 它完全支持paravirtulized客人和客人虛擬客人。 
# 支持的虛擬機管理程序是Xen,qemu(QEMU)和kvm

# libvirt: 虛擬管理模塊
# virt-manager: 圖形界面管理虛擬機
# libguestfs* : virt-cat等命令的支持軟件包


# 重啓宿主機,以便加載 kvm 模塊
# ------------------------
reboot

# 查看KVM模塊是否被正確加載
# ------------------------
lsmod | grep kvm

kvm_intel             162153  0
kvm                   525259  1 kvm_intel

開啓kvm服務,並且設置其開機自動啓動

systemctl start acpid.service
systemctl enable acpid.service
systemctl start libvirtd.service
systemctl enable libvirtd.service

查看狀態操作結果,如Active: active (running),說明運行情況良好

systemctl status libvirtd
systemctl is-enabled libvirtd

● libvirtd.service - Virtualization daemon
   Loaded: loaded (/usr/lib/systemd/system/libvirtd.service; enabled; vendor preset: enabled)
   Active: active (running) since 二 2001-01-02 11:29:53 CST; 1h 41min ago
     Docs: man:libvirtd(8)
           http://libvirt.org

安裝KVM成功後會在宿主機上自動生成一個虛擬網橋,用來虛擬機和宿主機之間的通信

下面來安裝虛擬機:

 

安裝前要設置環境語言爲英文LANG="en_US.UTF-8",如果是中文的話某些版本可能會報錯。CentOS 7 在這裏修改 /etc/locale.conf

kvm創建虛擬機,特別注意.iso鏡像文件一定放到/home 或者根目錄重新創建目錄,不然會因爲權限報錯,無法創建虛擬機。

注:下列兩條命令都是在黑窗中進行系統配置然後安裝

virt-install --virt-type=kvm --name=centos88 --vcpus=2 --memory=4096 --location=/tmp/CentOS-7-x86_64-Minimal-1511.iso --disk path=/home/vms/centos88.qcow2,size=40,format=qcow2 --network bridge=br0 --graphics none --extra-args='console=ttyS0' --force

 

virt-install --virt-type=kvm --name=centos74_2  --vcpus=2 --memory=4096 --location=/home/ISO/CentOS-7-x86_64-Minimal-1708.iso --disk path=/home/vms/centos74_2.qcow2,size=40,format=qcow2 --network bridge=br0 --graphics none --extra-args='console=ttyS0' --force

提供另一種方式:在服務器上只完成虛擬機的配置信息和鏡像的引導,系統的安裝通過VNC遠程登錄系統進行

virt-install --connect qemu:///system --name kali --memory=4096 --vcpus=2 --disk path=/home/vms/kali.qcow2,device=disk,format=qcow2,bus=virtio,cache=none,size=50 --cdrom /home/ISO/kali-linux-kde-amd64.iso --os-type=linux --network bridge=br0,model=virtio,model=e1000 --hvm --virt-type=kvm --noautoconsole --graphics vnc,listen=0.0.0.0,port=5901

安裝WindowsServer2008R2(硬盤格式爲ide,即bus=ide)

virt-install --connect qemu:///system --name windows --memory=4096 --vcpus=2 --disk path=/home/vms/windows.qcow2,device=disk,format=qcow2,bus=ide,cache=none,size=50 --cdrom /home/ISO/cn_windows_server_2008_r2_standard_enterprise_datacenter_web_x64_dvd_x15-50360.iso --os-type=windows --network bridge=br0,model=virtio,model=e1000 --hvm --virt-type=kvm --noautoconsole --graphics vnc,listen=0.0.0.0,port=5902  

 

KVM所在服務器顯示如下:

 

通過VNC遠程登錄虛擬機後完成系統安裝

 

命令行配置系統

 

上面創建虛擬機命令最終需要你配置系統基礎設置,帶 [!] 基本都是要配置的,按照順序往下配置,按對用的數字以此進行設置。

Installation

 1) [x] Language settings                 2) [!] Timezone settings
        (English (United States))                (Timezone is not set.)
 3) [!] Installation source               4) [!] Software selection
        (Processing...)                          (Processing...)
 5) [!] Installation Destination          6) [x] Kdump
        (No disks selected)                      (Kdump is enabled)
 7) [ ] Network configuration             8) [!] Root password
        (Not connected)                          (Password is not set.)
 9) [!] User creation
        (No user will be created)
  Please make your choice from above ['q' to quit | 'b' to begin installation |
  'r' to refresh]:

一步步配置下去即可

 

連接虛擬機

通過 virsh console <虛擬機名稱> 命令來連接虛擬機

# 查看虛擬機
virsh list              # 查看在運行的虛擬機
virsh list –all         # 查看所有虛擬機

 Id    Name                           State
----------------------------------------------------
 7     centos72                       running

配置虛擬機網絡,編輯vi /etc/sysconfig/network-scripts/ifcfg-eth0

TYPE=Ethernet
BOOTPROTO=static
IPADDR=IP   #配置成與網橋同一網段的IP地址
PREFIX=24
GATEWAY=GateWay_IP  #配置網關地址,用來連接外網
DNS1=114.114.114.114  # 配置兩個DNS服務器地址,用於域名解析
DNS2=8.8.8.8    
DEFROUTE=yes
PEERDNS=yes
PEERROUTES=yes
IPV4_FAILURE_FATAL=no
IPV6INIT=yes
IPV6_AUTOCONF=yes
IPV6_DEFROUTE=yes
IPV6_PEERDNS=yes
IPV6_PEERROUTES=yes
IPV6_FAILURE_FATAL=no
NAME=eth0
UUID=adfa3b7d-bf60-47e6-8482-871dee686fb5
DEVICE=eth0
ONBOOT=yes

配置物理機網絡

一般來說,服務器可能有多個網卡,選擇一個網卡當做網橋來與虛擬機通信

在/etc/sysconfig/network-scripts裏新增一個文件:ifcfg-br0

TYPE=Bridge
BOOTPROTO=static
NAME=br0
DEVICE=br0
GATEWAY=GateWay_IP  # 網關IP
DNS1=114.114.114
DNS2=8.8.8.8
ONBOOT=yes
IPADDR=IP  # 此處的IP其實是你宿主機上物理網卡,用來與虛擬機通信的網卡的IP
PREFIX=24

物理網卡配置:

TYPE=Ethernet
BOOTPROTO=none
NAME=eno1
DEVICE=eno1
ONBOOT=yes
BRIDGE="br0"

配置路由轉發vi /etc/sysctl.conf

# Controls IP packet forwarding
net.ipv4.ip_forward = 0
修改爲
# Controls IP packet forwarding
net.ipv4.ip_forward = 1    允許內置路由

Bridge模式配置

Bridge方式即虛擬網橋的網絡連接方式,是客戶機和子網裏面的機器能夠互相通信。可以使虛擬機成爲網絡中具有獨立IP的主機。橋接網絡(也叫 物理設備共享)被用作把一個物理設備複製到一臺虛擬機。網橋多用作高級設置,特別是主機多個網絡接口的情況。

┌─────────────────────────┐      ┌─────────────────┐
│          HOST           │      │Virtual Machine 1│
│ ┌──────┐      ┌───────┐ │      │    ┌──────┐     │
│ │ br0  │──┬───│ vnet0 │─│─ ─ ─ │    │ br0  │     │
│ └──────┘  │   └───────┘ │      │    └──────┘     │
│     │     │             │      └─────────────────┘
│     │     │   ┌───────┐ │      ┌─────────────────┐
│ ┌──────┐  └───│ vnet1 │─│─     │Virtual Machine 2│
│ │ eno0 │      └───────┘ │ │    │    ┌──────┐     │
│ └──────┘                │  ─ ─ │    │ br0  │     │
│ ┌──────┐                │      │    └──────┘     │
│ │ eno1 │                │      └─────────────────┘
│ └──────┘                │
└─────────────────────────┘

KVM一些常用命令:

克隆虛擬機:將74克隆到xiang

virt-clone -o centos74 -n cent_xiang -f /home/cent_xiang.qcow2

 

  • 列出所有的虛擬機

 

virsh list --all
  • 顯示虛擬機信息
virsh dominfo kvm-1
  • 顯示虛擬機內存和cpu的使用情況
yum install virt-top -y
virt-top
  • 顯示虛擬機分區信息
virt-df kvm-1
  • 關閉虛擬機(shutodwn)
virsh shutdown kvm-1
  • 啓動虛擬機
virsh start kvm-1
  • 設置虛擬機(kvm-1)跟隨系統自啓
virsh autostart kvm-1
  • 關閉虛擬及自啓
virsh autostart --disable kvm-1
  • 刪除虛擬機
virsh undefine kvm-1
  • 通過控制窗口登錄虛擬機
virsh console kvm-1

給虛擬機添加硬盤

添加硬盤(lvm卷)或者USB到虛擬機上

virsh attach-disk kvm-1 /dev/sdb vbd --driver qemu --mode shareable
  • 使用完成之後可以卸載usb
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
#  <vcpu>2</vcpu>  # 4 > 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 & paste
the entry for your mail storage device and just change the target and address tags. For example:
 # virsh edit vm1
 <disk type='file' device='disk'>
 <driver name='qemu' type='raw' cache='none' io='threads'/>
 <source file='/vm-images/vm1.img'/>
 <target dev='vda' bus='virtio'/>
 <address type='pci' domain='0x0000' bus='0x00' slot='0x04'
function='0x0'/>
 </disk>
 Add:
 <disk type='file' device='disk'>
 <driver name='qemu' type='raw' cache='none' io='threads'/>
 <source file='/vm-images/vm1-add.img'/>
 <target dev='vdb' bus='virtio'/>
 <address type='pci' domain='0x0000' bus='0x00' slot='0x06'
function='0x0'/>
 </disk>
 # 這裏建議使用上面的添加硬盤的方式添加

刪除虛擬機

  • 第一步,停掉虛擬機
virsh shutdown kvm-1
  • 第二步
virsh destroy kvm-1
  • 第三步
virsh undefine kvm-1
  • 第四部
 rm /dev/vg_shkvm1/kvm-1  # 不建議刪除硬盤

 

更爲詳細的KVM內容見:http://blog.csdn.net/github_27924183/article/details/76914322?locationNum=5&fps=1

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章