深入探索KVM虚拟化技术:全面掌握虚拟机的创建与管理

举报
wzsのcloud 发表于 2024/10/28 21:23:34 2024/10/28
【摘要】 熟悉KVM虚拟化技术,实现从安装到命令行,全面掌握虚拟机的创建与管理

安装KVM

开启cpu虚拟化

注意:务必开启虚拟机CPU虚拟化,否则无法嵌套虚拟机

image.png

不开启后期报错

image.png

安装KVM

配置yum源 --》安装KVM

[root@cloud ~]# mount /dev/cdrom /mnt/
mount: /mnt: WARNING: device write-protected, mounted read-only.
[root@cloud ~]# vim /etc/yum.repos.d/
[root@cloud ~]# vim /etc/yum.repos.d/
bak/        cloud.repo  
[root@cloud ~]# vim /etc/yum.repos.d/cloud.repo 
[root@cloud ~]# yum clean all
14 files removed
[root@cloud ~]# yum repolist  all
repo id                    repo name                   status
AppStream                  AppStream                   enabled
BaseOS                     BaseOS                      enabled
[root@cloud ~]# yum grouplist 
AppStream                     316 MB/s | 5.7 MB     00:00    
BaseOS                        455 MB/s | 2.2 MB     00:00    
Available Environment Groups:
   Server
   Minimal Install
   Workstation
   Custom Operating System
Installed Environment Groups:
   Server with GUI
   Virtualization Host
Installed Groups:
   Container Management
   Headless Management
Available Groups:
   .NET Core Development
   RPM Development Tools
   Development Tools
   Graphical Administration Tools
   Legacy UNIX Compatibility
   Network Servers
   Scientific Support
   Security Tools
   Smart Card Support
   System Tools

[root@cloud ~]# yum groupinstall -y "Virtualization*"   ### 安装的软件包组
Last metadata expiration check: 0:01:01 ago on Sat 05 Aug 2023 03:08:26 PM CST.
No match for group package "insights-client"
No match for group package "centos-release-eula"
Dependencies resolved.
==============================================================
 Package      Arch   Version                  Repo       Size
==============================================================
Installing group/module packages:
 virt-install noarch 2.2.1-3.el8              AppStream  99 k
 virt-top     x86_64 1.0.8-32.el8             AppStream 729 k
 virt-viewer  x86_64 7.0-9.el8                AppStream 397 k
 virt-who     noarch 0.27.6-1.el8             AppStream 247 k
Installing dependencies:
 python3-suds noarch 0.7-0.8.94664ddd46a6.el8 AppStream 242 k
Installing Environment Groups:
 Virtualization Host
                                                             
Installing Groups:
 Virtualization Hypervisor
                                                             
 Virtualization Platform
                                                             
 Virtualization Client
                                                             
 Virtualization Tools
                                                             
 Base                                                        
 Core                                                        
 Standard                                                    

Transaction Summary
==============================================================
Install  5 Packages

Total size: 1.7 M
Installed size: 6.2 M
Downloading Packages:
Running transaction check
Transaction check succeeded.
Running transaction test
Transaction test succeeded.
Running transaction
  Preparing        :                                      1/1 
  Installing       : python3-suds-0.7-0.8.94664ddd46a6.   1/5 
  Installing       : virt-who-0.27.6-1.el8.noarch         2/5 
  Running scriptlet: virt-who-0.27.6-1.el8.noarch         2/5 
  Installing       : virt-viewer-7.0-9.el8.x86_64         3/5 
  Installing       : virt-top-1.0.8-32.el8.x86_64         4/5 
  Installing       : virt-install-2.2.1-3.el8.noarch      5/5 
  Running scriptlet: virt-install-2.2.1-3.el8.noarch      5/5 
  Verifying        : python3-suds-0.7-0.8.94664ddd46a6.   1/5 
  Verifying        : virt-install-2.2.1-3.el8.noarch      2/5 
  Verifying        : virt-top-1.0.8-32.el8.x86_64         3/5 
  Verifying        : virt-viewer-7.0-9.el8.x86_64         4/5 
  Verifying        : virt-who-0.27.6-1.el8.noarch         5/5 
Installed products updated.

Installed:
  python3-suds-0.7-0.8.94664ddd46a6.el8.noarch                
  virt-install-2.2.1-3.el8.noarch                             
  virt-top-1.0.8-32.el8.x86_64                                
  virt-viewer-7.0-9.el8.x86_64                                
  virt-who-0.27.6-1.el8.noarch                                

Complete!

可以通过桌面化图标打开或者命令行

[root@cloud ~]# virt-manager

image.png

检查环境是否正常

image.png

[root@cloud ~]# ifconfig 
ens160: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet 192.168.129.141  netmask 255.255.255.0  broadcast 192.168.129.255
        inet6 fe80::4b45:520e:3195:48b4  prefixlen 64  scopeid 0x20<link>
        ether 00:0c:29:9b:91:4d  txqueuelen 1000  (Ethernet)
        RX packets 339  bytes 60656 (59.2 KiB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 201  bytes 23207 (22.6 KiB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

lo: flags=73<UP,LOOPBACK,RUNNING>  mtu 65536
        inet 127.0.0.1  netmask 255.0.0.0
        inet6 ::1  prefixlen 128  scopeid 0x10<host>
        loop  txqueuelen 1000  (Local Loopback)
        RX packets 48  bytes 4080 (3.9 KiB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 48  bytes 4080 (3.9 KiB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0
### 有正常
virbr0: flags=4099<UP,BROADCAST,MULTICAST>  mtu 1500
        inet 192.168.122.1  netmask 255.255.255.0  broadcast 192.168.122.255
        ether 52:54:00:bd:e4:f0  txqueuelen 1000  (Ethernet)
        RX packets 0  bytes 0 (0.0 B)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 0  bytes 0 (0.0 B)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

KVM图形化创建虚拟机

上传ISO

image.png

创建虚拟机

image.png

加载镜像

image.png

配置内存

image.png

添加磁盘

image.png

image.png

能否手工指定存储路径呢?

在指定的路径下首先创建虚拟机所用的磁盘

添加物理磁盘 --> 分区 --> 格式化 --> 挂载 --> 创建磁盘

[root@cloud /]# fdisk /dev/nvme0n2

Welcome to fdisk (util-linux 2.32.1).
Changes will remain in memory only, until you decide to write them.
Be careful before using the write command.


Command (m for help): n
Partition type
   p   primary (0 primary, 0 extended, 4 free)
   e   extended (container for logical partitions)
Select (default p): 

Using default response p.
Partition number (1-4, default 1): 
First sector (2048-41943039, default 2048): 
Last sector, +sectors or +size{K,M,G,T,P} (2048-41943039, default 41943039): 

Created a new partition 1 of type 'Linux' and of size 20 GiB.
Partition #1 contains a LVM2_member signature.

Do you want to remove the signature? [Y]es/[N]o: p
Do you want to remove the signature? [Y]es/[N]o: y

The signature will be removed by a write command.

Command (m for help): p
Disk /dev/nvme0n2: 20 GiB, 21474836480 bytes, 41943040 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disklabel type: dos
Disk identifier: 0x87cd3c01

Device         Boot Start      End  Sectors Size Id Type
/dev/nvme0n2p1       2048 41943039 41940992  20G 83 Linux

Filesystem/RAID signature on partition 1 will be wiped.

Command (m for help): w
The partition table has been altered.
Calling ioctl() to re-read partition table.
Syncing disks.

[root@cloud /]# mkfs.xfs /dev/nvme0n2p1
meta-data=/dev/nvme0n2p1         isize=512    agcount=4, agsize=1310656 blks
         =                       sectsz=512   attr=2, projid32bit=1
         =                       crc=1        finobt=1, sparse=1, rmapbt=0
         =                       reflink=1
data     =                       bsize=4096   blocks=5242624, imaxpct=25
         =                       sunit=0      swidth=0 blks
naming   =version 2              bsize=4096   ascii-ci=0, ftype=1
log      =internal log           bsize=4096   blocks=2560, version=2
         =                       sectsz=512   sunit=0 blks, lazy-count=1
realtime =none                   extsz=4096   blocks=0, rtextents=0

[root@cloud /]# mkdir /kvm
[root@cloud /]# cd kvm/
### qcow2为磁盘格式
[root@cloud kvm]# qemu-img create -f qcow2 /kvm/centos1.qcow2 20g
Formatting '/kvm/centos1.qcow2', fmt=qcow2 size=21474836480 cluster_size=65536 lazy_refcounts=off refcount_bits=16
[root@cloud kvm]# ls
centos1.qcow2

image.png

image.png

创建成功

image.png

安装完成

image.png

image.png

查看虚拟机

[root@cloud ~]# virsh list 
 Id    Name                           State
----------------------------------------------------
 3     centos7.0-2                    running

KVM命令行创建虚拟机

创建磁盘

[root@cloud kvm]# qemu-img create -f qcow2 /kvm/os1.qcow2 20g
Formatting '/kvm/os1.qcow2', fmt=qcow2 size=21474836480 cluster_size=65536 lazy_refcounts=off refcount_bits=16

[root@cloud kvm]# ls
os1.qcow2

### 之后,通过图形化创建虚拟机的时候可以选择刚才手工创建的存储磁盘 centos701.qcow2

通过命令行创建虚拟机

### 其实就是把前面图形化点击的步骤转换成了命令行操作。
[root@cloud kvm]# virt-install \
> --name centos702 \
> --memory 2048 \
> --vcpus 1 \
> --disk path=/kvm/os1.qcow2 \
> --location /data/CentOS-7-x86_64-DVD-2009.iso \
> --network network=default \
> --noautoconsole

Starting install...
Retrieving file vmlinuz...                                                                             | 6.5 MB  00:00:00     
Retrieving file initrd.img...                                                                          |  53 MB  00:00:00     
Domain installation still in progress. You can reconnect to 
the console to complete the installation process.

### 创建成功
[root@cloud kvm]# virsh list
 Id    Name                           State
----------------------------------------------------
 3     centos7.0-2                    running
 4     centos702                      running


手动安装虚拟机

image.png


KVM命令行创建虚拟机-kickstart全自动安装

注意:CentOS 8 版本是没有 kickstart 工具的,可以使用 CentOS 7 版本生成配置文件给 8 版本使用。

使用Centos7生成cfg文件

  • yum install -y system-config-kickstart.noarch --安装工具
  • system-config-kickstart --启动工具,注意禁用udev命名规则 net.ifnames=0 biosdevname=0

进行配置,最后导出 xxx.cfg 文件

  • yum install -y httpd --安装apache
  • systemctl start httpd --启动apache服务,注意关闭防火墙
  • 将工具生成好的配置文件保存。
### 关闭防火墙
[root@cloud html]# systemctl stop firewalld.service        ###  临时关闭
[root@cloud html]# systemctl disable firewalld.service     ### 禁止启用
Removed /etc/systemd/system/multi-user.target.wants/firewalld.service.
Removed /etc/systemd/system/dbus-org.fedoraproject.FirewallD1.service.

[root@cloud ~]# yum install -y httpd    ### 安装httpd
[root@cloud ~]# systemctl start httpd   ### 开启服务
[root@cloud ~]# cd /var/www/html/       ### 开启服务后,会自动生成目录 /var/www/html/
[root@cloud html]# mv /data/ks01.cfg .  ### 将centos7通过工具生成的cfg文件放到html目录下
[root@cloud html]# ls
ks01.cfg

### 使用虚拟机 ip + 目录文件 直接访问
# 例如 http://192.168.129.141/ks01.cfg

使用Centos8自动安装

### 创建磁盘
[root@cloud html]# qemu-img create -f qcow2 /kvm/centos703.qcow2 20g
Formatting '/kvm/centos703.qcow2', fmt=qcow2 size=21474836480 cluster_size=65536 lazy_refcounts=off refcount_bits=16

[root@cloud html]# ls /kvm/
centos703.qcow2  os1.qcow2

### 如果有错误,会在安装过程中卡住
[root@cloud ~]# virt-install \
> --name centos703 \                       ### 虚拟机名称
> --memory 2048 \                          ### 内存
> --vcpus 1 \                              ### cpu
> --disk path=/kvm/centos703.qcow2 \       ### 磁盘
> --location /data/CentOS-7-x86_64-DVD-2009.iso \  ### 镜像
> --network network=default \                      ### 网络
> --noautoconsole \
> -x ks=http://192.168.129.141/ks/ks01.cfg    ### 也可以使用本地文件 ks=/data/ks01.cfg

Starting install...
Retrieving file vmlinuz...                                       | 6.5 MB  00:00:00     
Retrieving file initrd.img...                                    |  53 MB  00:00:00     
Domain installation still in progress. You can reconnect to 
the console to complete the installation process.

### 使用本地文件,二选其一即可
[root@cloud ~]# virt-install --name centos703 --memory 2048 --vcpus 1 --disk path=/kvm/centos703.qcow2 --location /data/CentOS-7-x86_64-DVD-2009.iso --network network=default --noautoconsole -x ks=/data/ks01.cfg


####  之后即可使用图形化界面进行查看自动化安装

有个问题?虽然是通过命令行可以进行全自动安装,但是因为有图形化界面,所以便于观察虚拟机的具体信息。如果没有图形化界面呢?安装过程及安装完成后根本不知道虚拟机的ip地址,也不知道进行到哪一步了,这时候怎么办?

在kickstart文件中添加 console=ttyS0

bootloader --append="net.ifnames=0 biosdevname=0 console=ttyS0" --location=mbr

并通过 virsh console xxx 方式连接到虚拟机里面,相当于插上了一根console线。

### 添加 console=ttyS0
[root@cloud ~]# vim /data/ks01.cfg
...
# System timezone
timezone Asia/Shanghai
# System bootloader configuration
# bootloader --append="net.ifnames=0 biosdevname=0" --location=mbr
bootloader --append="net.ifnames=0 biosdevname=0 console=ttyS0" --location=mbr
# Clear the Master Boot Record
zerombr
....

[root@cloud ~]# qemu-img create -f qcow2 /kvm/os333.qcow2 20g


[root@cloud ~]# virt-install --name centos705 --memory 2048 --vcpus 1 --disk path=/kvm/os333.qcow2 --location /data/CentOS-7-x86_64-DVD-2009.iso --network network=default --noautoconsole -x ks=/data/ks01.cfg

Starting install...
Retrieving file vmlinuz...                                       | 6.5 MB  00:00:00     
Retrieving file initrd.img...                                    |  53 MB  00:00:00     
Domain installation still in progress. You can reconnect to 
the console to complete the installation process.


[root@cloud ~]# virsh console centos705
Connected to domain centos705
Escape character is ^]

CentOS Linux 7 (Core)
Kernel 3.10.0-957.el7.x86_64 on an x86_64

localhost login: root
Password: 


### ctrl + ] 退出

如果安装文件中没有加入,也可在后续虚拟机中加入

[root localhost ]# cd /etc/def auu lt/
[root localhost default]# ls
grub   nss    useradd
[root localhost default]# vi grub a
GRUB TIMEOUT=5
GRUB DISTRIBUTOR="S(sed 's, release .*5, ,g'’/etc/system-re lease )"
GRUB DEFAULT-saved
GRUB DISABLE SUBMENU=true
GRUB_ TERMINAL OUTPUT="'conso le'
# GRUB CMDL INE L INUX= crashkerne l=auto rd . lum. lu=centos/root rd. lum. lu=centos/swap rhgb quiet" 
### 加入到此处 console=ttyS0
GRUB CMDL INE L INUX= crashkerne l=auto rd . lum. lu=centos/root rd. lum. lu=centos/swap rhgb quiet console=ttyS0"
GRUB_ DISABLE RECOUERY="'true"

[root localhost default]# grub2-mkconfig -o /boot/grub2/grub.cfg
[root localhost default]# reboot

测试

[root@cloud ~]# virsh console centos7.0 
Connected to domain centos7.0
Escape character is ^]

CentOS Linux 7 (Core)
Kernel 3.10.0-1160.el7.x86_64 on an x86_64

localhost login: root
Password: 
Last login: Sat Aug  5 06:42:12 on tty1
[root@localhost ~]# 

KVM基本命令总结

[root@cloud ~]# virsh --help              查看帮助
[root@cloud ~]# virsh list --all          列出所有虚拟机(包括正在运行的和关闭的)
[root@cloud ~]# virsh list                列出所有虚拟机(仅运行中的)
[root@cloud ~]# virsh start centos705     --启动虚拟机
[root@cloud ~]# virsh shutdown centos705  -- 关闭虚拟机
[root@cloud ~]# virsh reboot centos705    --重启虚拟机

### 如果虚拟机关不了,强制关闭,非正常关闭
[root@cloud ~]# virsh destroy centos705
### 清除配置
[root@cloud ~]# virsh undefine centos705

# 移除软件包
[root@localhost ~]# yum groupremove -y "Virtualization*"
[root@localhost ~]# rpm -qa | grep virtualization
[root@localhost ~]# systemctl list-units | grep virtualization
[root@localhost ~]# lsmod | grep virtualization
【版权声明】本文为华为云社区用户原创内容,转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息, 否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。