Bootstrap

KVM虚拟化

KVM虚拟化

一、简介

KVM(Kernel-based Virtual Machine)是一种基于Linux内核的开源虚拟化技术,它允许将物理计算机划分成多个虚拟机,每个虚拟机可以运行自己的操作系统和应用程序。


KVM支持两种虚拟化模式:半虚拟化和全虚拟化。它们的区别和优势如下

  • 半虚拟化(Paravirtualization):

在半虚拟化模式下,虚拟机的操作系统需要被修改以与宿主机进行通信。虚拟机知道自己运行在虚拟化环境中,并使用特殊的API来与宿主机进行通信。优势是效率较高,虚拟机可以直接访问宿主机的硬件设备,因此性能较好。但是,半虚拟化要求虚拟机的操作系统进行修改,这可能会限制可移植性。

  • 全虚拟化(Full Virtualization):

在全虚拟化模式下,虚拟机的操作系统不需要进行修改,它被认为是运行在真正的硬件上。KVM通过使用虚拟设备驱动程序和硬件加速来模拟硬件环境,让虚拟机能够在其自己的独立环境中运行。优势是较好的可移植性,因为虚拟机的操作系统无需进行修改。但是,全虚拟化的性能相对较低,因为需要进行额外的虚拟化和模拟。

KVM虚拟化的工作原理如下:

  1. 首先,KVM利用Linux内核的虚拟化功能创建一个虚拟化的环境,这个环境被称为虚拟机监控器(Virtual Machine Monitor,VMM)或Hypervisor。

  2. 然后,KVM使用硬件虚拟化扩展(如Intel的VT-x或AMD的AMD-V)来提供对虚拟机的支持。这些扩展使得KVM能够在每个虚拟机中运行自己的操作系统,并直接访问宿主机的硬件设备。

  3. 虚拟机监控器负责在宿主机和虚拟机之间进行资源的分配和管理。它通过为每个虚拟机提供虚拟设备(如虚拟CPU、虚拟内存和虚拟磁盘)来模拟硬件环境,使得虚拟机可以独立运行。


总的来说,KVM虚拟化技术能够提供高性能和较好的可移植性,同时对硬件要求较高。它已经成为很多云计算平台和虚拟化解决方案的首选之一。

二、KVM部署

环境
操作系统主机名部署的软件IP地址
centos-7kvm-hostKVM192.168.179.20
centos-7kvm-webwebvirtmgr(web管理界面)192.168.179.21
前期准备

两台主机都需要做的操作

开启CPU虚拟化功能

1.如果是真机,请进入BIOS界面,开启虚拟化功能

2.如果是虚拟机,请先关机,然后开启虚拟化功能,如下图:

在这里插入图片描述

在这里插入图片描述


基本配置
//配置yum源,推荐使用阿里云源。安装epel源。
[root@kvm-host ~]# rm -rf /etc/yum.repos.d/*

[root@kvm-host ~]# curl -o /etc/yum.repos.d/CentOS-Base.repo https://mirrors.aliyun.com/repo/Centos-7.repo

[root@kvm-host ~]# sed -i -e '/mirrors.cloud.aliyuncs.com/d' -e '/mirrors.aliyuncs.com/d' /etc/yum.repos.d/CentOS-Base.repo

[root@kvm-host ~]# yum clean all
[root@kvm-host ~]# yum makecache

//配置epel源
[root@kvm-host ~]# yum -y install wget
[root@kvm-host ~]# wget -O /etc/yum.repos.d/epel.repo https://mirrors.aliyun.com/repo/epel-7.repo
[root@kvm-host ~]# yum makecache


//永久关闭防火墙和selinux
[root@kvm-host ~]# systemctl disable --now firewalld.service 
[root@kvm-host ~]# setenforce 0
[root@kvm-host ~]# sed -i 's/^SELINUX=enforcing/SELINUX=disabled/g' /etc/selinux/config

//重启主机
[root@kvm-host ~]# reboot 
(另外一台主机做同样的操作)

安装KVM

在主机kvm-host上操作

//检查CPU是否支持KVM;如果结果中有vmx(Intel)或svm(AMD)字样,就说明支持。
[root@kvm-host ~]# egrep -o 'vmx|svm' /proc/cpuinfo
vmx
vmx
vmx
vmx
[root@kvm-host ~]# 

//安装一些基本工具
[root@kvm-host ~]# yum -y install vim wget net-tools unzip zip gcc gcc-c++

//安装kvm
[root@kvm-host ~]# yum -y install qemu-kvm qemu-kvm-tools qemu-img virt-manager libvirt libvirt-python libvirt-client virt-install virt-viewer bridge-utils libguestfs-tools
(安装过程省略...)

//把KVM主机的网卡配置为桥接模式。
[root@kvm-host ~]# cd /etc/sysconfig/network-scripts/
[root@kvm-host network-scripts]# cp ifcfg-ens33 ifcfg-br0
[root@kvm-host network-scripts]# vim ifcfg-br0 
[root@kvm-host network-scripts]# cat ifcfg-br0 
TYPE="Bridge"             //修改为Bridge
NM_CONTROLLED="no"        //添加此行
BOOTPROTO="static"
NAME="br0"                //修改为br0
DEVICE="br0"              //修改为br0
ONBOOT="yes"
IPADDR="192.168.179.20"
PREFIX="24"
GATEWAY="192.168.179.2"
DNS1="8.8.8.8"
DNS2="114.114.114.114"
[root@kvm-host network-scripts]# 

//原来的网卡配置成这样
[root@kvm-host network-scripts]# vim ifcfg-ens33 
[root@kvm-host network-scripts]# cat ifcfg-ens33 
TYPE="Ethernet"
BOOTPROTO="static"
NAME="ens33"
DEVICE="ens33"
ONBOOT="yes"
BRIDGE="br0"
NM_CONTROLLED="no"
[root@kvm-host network-scripts]# 

//重启网卡服务
[root@kvm-host network-scripts]# systemctl restart network
[root@kvm-host ~]# ifdown ens33;ifup ens33

//查看,已经有br0、virbr0、virbr0-nic了,分别对应三种模式:桥接、NAT,仅主机。
[root@kvm-host network-scripts]# ip a
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
    inet6 ::1/128 scope host 
       valid_lft forever preferred_lft forever
2: ens33: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast master br0 state UP group default qlen 1000
    link/ether 00:0c:29:77:15:29 brd ff:ff:ff:ff:ff:ff
    inet6 fe80::20c:29ff:fe77:1529/64 scope link 
       valid_lft forever preferred_lft forever
3: br0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP group default qlen 1000
    link/ether 00:0c:29:77:15:29 brd ff:ff:ff:ff:ff:ff
    inet 192.168.179.20/24 brd 192.168.179.255 scope global br0
       valid_lft forever preferred_lft forever
    inet6 fe80::20c:29ff:fe77:1529/64 scope link 
       valid_lft forever preferred_lft forever
4: virbr0: <NO-CARRIER,BROADCAST,MULTICAST,UP> mtu 1500 qdisc noqueue state DOWN group default qlen 1000
    link/ether 52:54:00:4d:e1:72 brd ff:ff:ff:ff:ff:ff
    inet 192.168.122.1/24 brd 192.168.122.255 scope global virbr0
       valid_lft forever preferred_lft forever
5: virbr0-nic: <BROADCAST,MULTICAST> mtu 1500 qdisc pfifo_fast master virbr0 state DOWN group default qlen 1000
    link/ether 52:54:00:4d:e1:72 brd ff:ff:ff:ff:ff:ff
[root@kvm-host network-scripts]#

//启动服务
[root@kvm-host ~]# systemctl enable --now libvirtd

//查看安装结果
[root@kvm-host ~]# lsmod|grep kvm
kvm_intel             174841  0 
kvm                   578518  1 kvm_intel
irqbypass              13503  1 kvm
[root@kvm-host ~]# 
//安装成功

//测试并验证安装结果
[root@kvm-host ~]# virsh -c qemu:///system list
 Id    Name                           State
----------------------------------------------------      //没有问题

[root@kvm-host ~]# virsh --version
4.5.0              //版本号

[root@kvm-host ~]# virt-install --version
1.5.0

//简单配置
[root@kvm-host ~]# ln -s /usr/libexec/qemu-kvm /usr/bin/qemu-kvm

//查看网桥信息
[root@kvm-host ~]# brctl show
bridge name	bridge id		STP enabled	interfaces
br0		8000.000c29771529	no		ens33
virbr0		8000.5254004de172	yes		virbr0-nic
[root@kvm-host ~]# 
安装kvm web管理界面

在主机kvm-web上操作

//安装依赖包
[root@kvm-web ~]# yum -y install git python-pip libvirt-python libxml2-python python-websockify supervisor nginx python-devel
(耐心等待安装...)

//从github上下载webvirtmgr代码
[root@kvm-web src]# wget https://github.com/retspen/webvirtmgr/archive/refs/heads/master.zip
[root@kvm-web src]# yum -y install unzip
[root@kvm-web src]# unzip master.zip 
[root@kvm-web src]# ls
webvirtmgr-master  webvirtmgr-master.zip

//安装webvirtmgr
[root@kvm-web src]# ls
master.zip  webvirtmgr-master
[root@kvm-web src]# cd webvirtmgr-master/
[root@kvm-web webvirtmgr-master]# pip install -r requirements.txt
Collecting django==1.5.5 (from -r requirements.txt (line 1))
  Downloading https://files.pythonhosted.org/packages/38/49/93511c5d3367b6b21fc2995a0e53399721afc15e4cd6eb57be879ae13ad4/Django-1.5.5.tar.gz (8.1MB)
    60% |███████████████████▎            | 4.9MB 2.3MB/s eta 0:00:02
    (耐心等待安装...)
    
//检查sqlite3是否安装
[root@kvm-web webvirtmgr-master]# python
Python 2.7.5 (default, Jun 20 2023, 11:36:40) 
[GCC 4.8.5 20150623 (Red Hat 4.8.5-44)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sqlite3          //输入这条命令,如果没有任何反馈,就没问题
>>> exit()                  //退出
[root@kvm-web webvirtmgr-master]# 


//初始化帐号信息
[root@kvm-web webvirtmgr-master]# python manage.py syncdb
WARNING:root:No local_settings file found.
Creating tables ...
Creating table auth_permission
Creating table auth_group_permissions
Creating table auth_group
Creating table auth_user_groups
Creating table auth_user_user_permissions
Creating table auth_user
Creating table django_content_type
Creating table django_session
Creating table django_site
Creating table servers_compute
Creating table instance_instance
Creating table create_flavor

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  //询问你,是否创建一个超级管理员,yes
Username (leave blank to use 'root'): admin      //用户名,是web页面的管理员,非系统用户
Email address: 1@2.com                           //邮箱,根据实际填
Password:                                        //输入密码
Password (again):                                //再次输入密码
Superuser created successfully.
Installing custom SQL ...
Installing indexes ...
Installed 6 object(s) from 1 fixture(s)
[root@kvm-web webvirtmgr-master]# 


//拷贝web网页至指定目录
[root@kvm-web webvirtmgr-master]# mkdir /var/www
[root@kvm-web webvirtmgr-master]# cp -r /usr/local/src/webvirtmgr-master/ /var/www/
[root@kvm-web webvirtmgr-master]# chown -R nginx.nginx /var/www/webvirtmgr-master/


//给本机的root用户配置免密登录
//生成密钥
[root@kvm-web ~]# ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa):   //回车
Created directory '/root/.ssh'.
Enter passphrase (empty for no passphrase):      //回车
Enter same passphrase again: 
Your identification has been saved in /root/.ssh/id_rsa.
Your public key has been saved in /root/.ssh/id_rsa.pub.
The key fingerprint is:            //回车
SHA256:x3g8rKS/7YGHTnfaQH6C+hyCWps+q2psP3cP2N1HOyA root@kvm-web
The key's randomart image is:
+---[RSA 2048]----+
|                 |
|                 |
|                 |
|         =       |
|        SEO. .   |
|     .oo.Xo.o .  |
|.   o.ooB.B.o+   |
| + +.+ O.= O. .  |
|+.++Boo.B++ .    |
+----[SHA256]-----+
[root@kvm-web ~]# 

//发送密钥给kvm主机
[root@kvm-web ~]# ssh-copy-id 192.168.179.20
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/root/.ssh/id_rsa.pub"
The authenticity of host '192.168.179.20 (192.168.179.20)' can't be established.
ECDSA key fingerprint is SHA256:FUBajMDXZl+SPT7to3Z/OhKLk0INYLP7iXNsAjaZq7g.
ECDSA key fingerprint is MD5:3e:5b:91:c7:e2:93:e6:2f:73:55:ac:7d:a3:7b:5c:04.
Are you sure you want to continue connecting (yes/no)? yes     //输入yes
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys
[email protected]'s password:     //输入该主机的root密码

Number of key(s) added: 1

Now try logging into the machine, with:   "ssh '192.168.179.20'"
and check to make sure that only the key(s) you wanted were added.

[root@kvm-web ~]# 

//root用户可以免密登录对方主机
[root@kvm-web ~]# ssh [email protected]
Last login: Wed Oct 11 16:17:34 2023 from kvm-host
[root@kvm-host ~]# exit
logout
Connection to 192.168.179.20 closed.
[root@kvm-web ~]# 


//配置端口转发
[root@kvm-web ~]# ssh 192.168.179.20 -L localhost:8000:localhost:8000 -L localhost:6080:localhost:60
Last login: Wed Oct 11 16:22:25 2023 from 192.168.179.1
[root@kvm-host ~]# exit           //记得退出来
logout
Connection to 192.168.179.20 closed.
[root@kvm-web ~]# 



//配置nginx
//先备份原配置文件
[root@kvm-web ~]# mv /etc/nginx/nginx.conf /opt/

//再手动创建一个新配置文件,内容如下
[root@kvm-web ~]# vim /etc/nginx/nginx.conf
[root@kvm-web ~]# cat /etc/nginx/nginx.conf
user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;

include /usr/share/nginx/modules/*.conf;

events {
    worker_connections 1024;
}

http {
    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;

    sendfile            on;
    tcp_nopush          on;
    tcp_nodelay         on;
    keepalive_timeout   65;
    types_hash_max_size 2048;

    include             /etc/nginx/mime.types;
    default_type        application/octet-stream;

    include /etc/nginx/conf.d/*.conf;

    server {
        listen       80;
        server_name  localhost;

        include /etc/nginx/default.d/*.conf;

        location / {
            root html;
            index index.html index.htm;
        }

        error_page 404 /404.html;
            location = /40x.html {
        }

        error_page 500 502 503 504 /50x.html;
            location = /50x.html {
        }
    }
}
[root@kvm-web ~]# 

//手动配置nginx虚拟主机
[root@kvm-web ~]# vim /etc/nginx/conf.d/webvirtmgr.conf
[root@kvm-web ~]# cat /etc/nginx/conf.d/webvirtmgr.conf
server {
    listen 80 default_server;

    server_name $hostname;
    #access_log /var/log/nginx/webvirtmgr_access_log;

    location /static/ {
        root /var/www/webvirtmgr-master/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 $remote_addr;
        proxy_connect_timeout 600;
        proxy_read_timeout 600;
        proxy_send_timeout 600;
        client_max_body_size 1024M;
    }
}
[root@kvm-web ~]# 

//确保bind绑定的是本机的8000端口
[root@kvm-web ~]# vim /var/www/webvirtmgr-master/conf/gunicorn.conf.py
(省略)
bind = '0.0.0.0:8000'      //修改为0.0.0.0:8000
backlog = 2048
(省略)


//重启nginx
[root@kvm-web ~]# systemctl restart nginx.service
[root@kvm-web ~]# systemctl enable nginx.service 
Created symlink from /etc/systemd/system/multi-user.target.wants/nginx.service to /usr/lib/systemd/system/nginx.service.
[root@kvm-web ~]# 


//设置supervisor,直接在最后面添加以下内容
[root@kvm-web ~]# vim /etc/supervisord.conf
(省略)
[program:webvirtmgr-master]
command=/usr/bin/python2 /var/www/webvirtmgr-master/manage.py run_gunicorn -c /var/www/webvirtmgr-master/conf/gunicorn.conf.py
directory=/var/www/webvirtmgr-master
autostart=true
autorestart=true
logfile=/var/log/supervisor/webvirtmgr-master.log
log_stderr=true
user=nginx

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

//启动supervisor并设置开机自启
[root@kvm-web ~]# systemctl start supervisord && systemctl enable supervisord
Created symlink from /etc/systemd/system/multi-user.target.wants/supervisord.service to /usr/lib/systemd/system/supervisord.service.
[root@kvm-web ~]# 


//配置nginx用户
//给本机的nginx用户配置免密登录
[root@kvm-web ~]# su - nginx -s /bin/bash
-bash-4.2$ ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/var/lib/nginx/.ssh/id_rsa): 
Created directory '/var/lib/nginx/.ssh'.
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved in /var/lib/nginx/.ssh/id_rsa.
Your public key has been saved in /var/lib/nginx/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:7yQztH2aDeJ4fK733bap+RMKxmIkH2NYoryC2uo0EXc nginx@kvm-web
The key's randomart image is:
+---[RSA 2048]----+
|                 |
|       . .       |
| . ..E. +        |
|  o .o o =       |
| ..   . S +      |
| ... . . B +   . |
|.+  .  .B B o . .|
|o o    ooBo* o.oo|
|oo    ..o==.oo+=+|
+----[SHA256]-----+

-bash-4.2$ touch ~/.ssh/config && echo -e "StrictHostKeyChecking=no\nUserKnownHostsFile=/dev/null" >> ~/.ssh/config

-bash-4.2$ chmod 0600 ~/.ssh/config

-bash-4.2$ ssh-copy-id [email protected]
/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/var/lib/nginx/.ssh/id_rsa.pub"
/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys
Warning: Permanently added '192.168.179.20' (ECDSA) to the list of known hosts.
[email protected]'s password: 

Number of key(s) added: 1

Now try logging into the machine, with:   "ssh '[email protected]'"
and check to make sure that only the key(s) you wanted were added.

-bash-4.2$ exit
logout
[root@kvm-web ~]# 

//生成配置文件
[root@kvm-web ~]# vim /etc/polkit-1/localauthority/50-local.d/50-libvirt-remote-access.pkla
[root@kvm-web ~]# cat /etc/polkit-1/localauthority/50-local.d/50-libvirt-remote-access.pkla
[Remote libvirt SSH access]
Identity=unix-user:root
Action=org.libvirt.unix.manage
ResultAny=yes
ResultInactive=yes
ResultActive=yes
[root@kvm-web ~]# 

//修改权限
[root@kvm-web ~]# chown -R root.root /etc/polkit-1/localauthority/50-local.d/50-libvirt-remote-access.pkla

//重启nginx服务
[root@kvm-web ~]# systemctl restart nginx

//重启kvm主机上的kvm服务
[root@kvm-web ~]# ssh [email protected] "systemctl restart libvirtd"

//建议重启一下主机kvm-web
[root@kvm-web ~]# reboot
实例管理

在浏览器访问kvm-web主机的IP地址

使用创建的超级管理员登录

在这里插入图片描述


kvm连接管理

创建ssh连接

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述


kvm存储管理

创建存储

在这里插入图片描述

在这里插入图片描述


进入存储

在这里插入图片描述

在这里插入图片描述


通过远程连接软件上传ISO镜像文件到/var/lib/libvirt/images 中

//查看上传的ISO镜像文件
[root@kvm-host ~]# cd /var/lib/libvirt/images/
[root@kvm-host images]# ls
CentOS-Stream-8-20230626.1-x86_64-dvd1.iso
[root@kvm-host images]# 

在这里插入图片描述

创建系统安装镜像

在这里插入图片描述

在这里插入图片描述


kvm网络管理

添加桥接网络

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述


kvm虚机实例管理

创建一个虚拟机

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

进入虚拟机系统安装界面

在这里插入图片描述

进行正常安装系统的操作,过程省略

注意:虚拟主机中网卡要配和kvm主机一样的网段,本案例的kvm主机是192.168.179.0/24网段的,所以虚拟主机也要配此网段的ip地址

通过xshell软件ssh远程连接这台虚拟机

//查看ip:IP地址为192.168.179.18/24
[root@localhost ~]# ip a
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
    inet6 ::1/128 scope host 
       valid_lft forever preferred_lft forever
2: ens3: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc fq_codel state UP group default qlen 1000
    link/ether 52:54:00:f5:67:23 brd ff:ff:ff:ff:ff:ff
    altname enp0s3
    inet 192.168.179.18/24 brd 192.168.179.255 scope global noprefixroute ens3
       valid_lft forever preferred_lft forever
    inet6 fe80::5054:ff:fef5:6723/64 scope link noprefixroute 
       valid_lft forever preferred_lft forever
[root@localhost ~]# 

//可以上网
[root@localhost ~]# ping -c4 www.baidu.com
PING www.a.shifen.com (36.155.132.55) 56(84) bytes of data.
64 bytes from 36.155.132.55 (36.155.132.55): icmp_seq=1 ttl=128 time=51.5 ms
64 bytes from 36.155.132.55 (36.155.132.55): icmp_seq=2 ttl=128 time=73.9 ms
64 bytes from 36.155.132.55 (36.155.132.55): icmp_seq=3 ttl=128 time=80.6 ms
64 bytes from 36.155.132.55 (36.155.132.55): icmp_seq=4 ttl=128 time=79.10 ms

--- www.a.shifen.com ping statistics ---
4 packets transmitted, 4 received, 0% packet loss, time 3005ms
rtt min/avg/max/mdev = 51.527/71.483/80.575/11.815 ms
[root@localhost ~]# 

;