In-depth exploration of KVM virtualization technology: Comprehensive mastery of virtual machine creation and management

Article directory

    • Install KVM
      • Enable cpu virtualization
      • Install KVM
      • Check whether the environment is normal
    • Create a virtual machine graphically with KVM
      • Upload ISO
      • Create a virtual machine
      • Load image
      • Configure memory
      • add disk
      • Can I manually specify the storage path?
      • Created successfully
      • The installation is complete
      • View virtual machines
    • KVM command line to create a virtual machine
      • Create disk
      • Create a virtual machine from the command line
      • Manually install a virtual machine
    • KVM command line to create a virtual machine-kickstart fully automatic installation
      • Generate cfg file using Centos7
      • Automatic installation using Centos8
      • test
    • Summary of KVM basic commands

Install KVM

Enable cpu virtualization

Note: Be sure to enable virtual machine CPU virtualization, otherwise the virtual machine cannot be nested

Disable later error reporting

Install KVM

Configure yum source –> Install 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*" ### Installed software package group
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 99k
 virt-top x86_64 1.0.8-32.el8 AppStream 729k
 virt-viewer x86_64 7.0-9.el8 AppStream 397k
 virt-who noarch 0.27.6-1.el8 AppStream 247k
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.7M
Installed size: 6.2M
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!

Can be opened via desktop icon or command line

[root@cloud ~]# virt-manager

Check whether the environment is normal

[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
### There is normal
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 graphically creates a virtual machine

Upload ISO

Create a virtual machine

Load image

Configuring memory

Add disk

Can I manually specify the storage path?

First create the disk used by the virtual machine under the specified path

Add physical disk –> Partition –> Format –> Mount –> Create disk

[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 is disk format
[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

Created successfully

Installation completed

View virtual machines

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

KVM command line to create a virtual machine

Create disk

[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

### Afterwards, when creating a virtual machine graphically, you can select the storage disk centos701.qcow2 that you just created manually.

Create a virtual machine through the command line

### In fact, it converts the previous graphical click steps into command line operations.
[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.

### Created successfully
[root@cloud kvm]# virsh list
 Id Name State
-------------------------------------------------- --
 3 centos7.0-2 running
 4 centos702 running


Manually install a virtual machine

KVM command line to create a virtual machine-kickstart fully automatic installation

Note: The CentOS 8 version does not have the kickstart tool. You can use the CentOS 7 version to generate a configuration file for the 8 version.

Use Centos7 to generate cfg files

  • yum install -y system-config-kickstart.noarch –Installation tool
  • system-config-kickstart –start the tool, be careful to disable udev naming rules net.ifnames=0 biosdevname=0

Configure and finally export the xxx.cfg file

  • yum install -y httpd –install apache
  • systemctl start httpd –Start the apache service, be sure to turn off the firewall
  • Save the configuration file generated by the tool.
### Turn off the firewall
[root@cloud html]# systemctl stop firewalld.service ### Temporary shutdown
[root@cloud html]# systemctl disable firewalld.service ### Disable enabling
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 ### Install httpd
[root@cloud ~]# systemctl start httpd ### Start the service
[root@cloud ~]# cd /var/www/html/ ### After starting the service, the directory /var/www/html/ will be automatically generated.
[root@cloud html]# mv /data/ks01.cfg . ### Place the cfg file generated by centos7 through the tool in the html directory
[root@cloud html]# ls
ks01.cfg

### Use virtual machine ip + directory file for direct access
# For example http://192.168.129.141/ks01.cfg

Automatic installation using Centos8

### Create disk
[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

### If there is an error, it will get stuck during the installation process.
[root@cloud ~]# virt-install \
> --name centos703 \ ### Virtual machine name
> --memory 2048 \ ### Memory
> --vcpus 1 \ ### cpu
> --disk path=/kvm/centos703.qcow2 \ ### Disk
> --location /data/CentOS-7-x86_64-DVD-2009.iso \ ### Mirror
> --network network=default \ ### Network
> --noautoconsole \
> -x ks=http://192.168.129.141/ks/ks01.cfg ### You can also use the local file 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.

### Use local files, choose one of the two
[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


#### Then you can use the graphical interface to view the automated installation

There is a problem? Although the installation can be fully automated through the command line, it is easy to observe the specific information of the virtual machine because of the graphical interface. What if there is no graphical interface? During the installation process and after the installation is completed, I don’t know the IP address of the virtual machine at all, nor do I know which step it has taken. What should I do at this time?

Add console=ttyS0 to the kickstart file

bootloader –append=”net.ifnames=0 biosdevname=0 console=ttyS0” –location=mbr

And connect to the virtual machine through virsh console xxx, which is equivalent to plugging in a console cable.

### Add 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 + ] exit

If it is not added in the installation file, it can also be added in subsequent virtual machines.

[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="'console'
# GRUB CMDL INE L INUX= crashkerne l=auto rd . lum. lu=centos/root rd. lum. lu=centos/swap rhgb quiet"
### Add here 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

Test

[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 ~]#

Summary of KVM basic commands

[root@cloud ~]# virsh --help View help
[root@cloud ~]# virsh list --all List all virtual machines (including running and closed ones)
[root@cloud ~]# virsh list List all virtual machines (only running ones)
[root@cloud ~]# virsh start centos705 --Start the virtual machine
[root@cloud ~]# virsh shutdown centos705 -- Shut down the virtual machine
[root@cloud ~]# virsh reboot centos705 --Restart the virtual machine

### If the virtual machine cannot be shut down, force shutdown or abnormal shutdown.
[root@cloud ~]# virsh destroy centos705
### Clear configuration
[root@cloud ~]# virsh undefine centos705

# Remove package
[root@localhost ~]# yum groupremove -y "Virtualization*"
[root@localhost ~]# rpm -qa | grep virtualization
[root@localhost ~]# systemctl list-units | grep virtualization
[root@localhost ~]# lsmod | grep virtualization