KVM虚拟化

KVM虚拟化

文章目录

  • KVM虚拟化
      • 虚拟化简介
    • KVM
      • KVM部署
        • CPU虚拟化功能
        • kvm管理界面安装

虚拟化简介

虚拟化:在一台计算机上虚拟出多个逻辑的计算机,而且每个逻辑计算机它可以是不同的操作系统

虚拟化技术:可以扩大硬件容量,单个cpu模拟出多个cpu并行,允许一个平台上同时允许多个操作系统,应用程序都可以在相互独立的空间内运行,并且互不影响

优点:

  1. 节约成本
  2. 提高效率

宿主机通过hypervisor的程序将宿主机硬件虚拟化然后提供给guset使用

Hypervisor:一种运行在物理服务器硬件与操作系统之间的中间软件层

可允许多个操作系统和应用来共享硬件资源

根据Hypervisor的实现方式和所处的位置,虚拟化分为两种:

完全虚拟化:直接在物理机上部署虚拟化,并且不需要修改操作系统内核

半虚拟化:需要修改操作系统内核,使其支持虚拟化驱动来实现虚拟化技术

理论上讲:

完全虚拟化一般对硬件虚拟化功能进行了特别优化,性能上比半虚拟化要高;
半虚拟化因为基于普通的操作系统,会比较灵活,比如支持虚拟机嵌套。嵌套意味着可以在KVM虚拟机中再运行KVM

KVM

简介

Kvm基于linux内核实现的,kvm有一个内核模块叫kvm.ko,只用于管理虚拟cpu和内存

那 IO 的虚拟化,比如存储和网络设备则是由 Linux 内核与Qemu来实现。

Qemu 是纯软件实现的虚拟化模拟器,几乎可以模拟任何硬件设备,我们最熟悉的就是能够模拟一台能够独立运行操作系统的虚拟机,虚拟机认为自己和硬件打交道,但其实是和 Qemu 模拟出来的硬件打交道,Qemu 将这些指令转译给真正的硬件。

正因为 Qemu 是纯软件实现的,所有的指令都要经 Qemu 过一手,性能非常低,所以,在生产环境中,大多数的做法都是配合 KVM 来完成虚拟化工作,因为 KVM 是硬件辅助的虚拟化技术,主要负责 比较繁琐的 CPU 和内存虚拟化,而 Qemu 则负责 I/O 虚拟化,两者合作各自发挥自身的优势,相得益彰.

作为一个 Hypervisor,KVM 本身只关注虚拟机调度和内存管理这两个方面。IO 外设的任务交给 Linux 内核和 Qemu。

Libvirt 就是 KVM 的管理工具。管理虚拟机和虚拟化功能的软件

其实,Libvirt 除了能管理 KVM 这种 Hypervisor,还能管理 Xen,VirtualBox 等。

Libvirt 包含 3 个东西:后台 daemon 程序 libvirtd、API 库和命令行工具 virsh

  • libvirtd是服务程序,接收和处理 API 请求;
  • API 库使得其他人可以开发基于 Libvirt 的高级工具,比如 virt-manager,这是个图形化的 KVM 管理工具;
  • virsh 是我们经常要用的 KVM 命令行工具

KVM部署

系统:Centos8 stream

CPU虚拟化功能

部署前请确保你的CPU虚拟化功能已开启,分为两种情况:

(1)虚拟机要关机设置CPU虚拟化

(2)物理机要在BIOS里开启CPU虚拟化

2、虚拟机设置(内存:8G 磁盘:200G 虚拟化功能:开启)

设置虚拟机内存,添加一块200G的硬盘

KVM虚拟化_第1张图片

开启虚拟化

KVM虚拟化_第2张图片

新建分区,将硬盘所有大小都给这个分区

lhost ~]# parted /dev/sdb
GNU Parted 3.2
Using /dev/sdb
Welcome to GNU Parted! Type 'help' to view a list of commands.
(parted) mklabel                                                          
New disk label type? msdos                                                
(parted) unit                                                             
Unit?  [compact]? Mib                                                     
(parted) p                                                                
Model: VMware, VMware Virtual S (scsi)
Disk /dev/sdb: 204800MiB
Sector size (logical/physical): 512B/512B
Partition Table: msdos
Disk Flags: 

Number  Start  End  Size  Type  File system  Flags

(parted) mkpart                                                                                                                 
Partition type?  primary/extended? primary                                
File system type?  [ext2]? xfs                                            
Start? 10Mib                                                              
End? 200Gb                                                                
(parted) p                                                                
Model: VMware, VMware Virtual S (scsi)
Disk /dev/sdb: 204800MiB
Sector size (logical/physical): 512B/512B
Partition Table: msdos
Disk Flags: 

Number  Start    End        Size       Type     File system  Flags
 1      10.0MiB  190735MiB  190725MiB  primary  xfs          lba

(parted) q                                                                
Information: You may need to update /etc/fstab.

格式化并挂载
[root@localhost ~]# mkfs.xfs /dev/sdb1
meta-data=/dev/sdb1              isize=512    agcount=4, agsize=12206400 blks
         =                       sectsz=512   attr=2, projid32bit=1
         =                       crc=1        finobt=1, sparse=1, rmapbt=0
         =                       reflink=1    bigtime=0 inobtcount=0
data     =                       bsize=4096   blocks=48825600, imaxpct=25
         =                       sunit=0      swidth=0 blks
naming   =version 2              bsize=4096   ascii-ci=0, ftype=1
log      =internal log           bsize=4096   blocks=23840, version=2
         =                       sectsz=512   sunit=0 blks, lazy-count=1
realtime =none                   extsz=4096   blocks=0, rtextents=0
[root@localhost ~]# blkid /dev/sdb1
/dev/sdb1: UUID="7b24e38f-2688-4cc6-9f6e-0e99007fea5b" BLOCK_SIZE="512" TYPE="xfs" PARTUUID="5fc6ce4a-01"
[root@localhost ~]# mkdir /kvmdata
[root@localhost ~]# vim /etc/fstab
 UUID=7b24e38f-2688-4cc6-9f6e-0e99007fea5b  /kvmdata  xfs    defaults 0 0  

[root@localhost ~]# mount -a
[root@localhost ~]# df -h
Filesystem           Size  Used Avail Use% Mounted on
devtmpfs             5.8G     0  5.8G   0% /dev
tmpfs                5.9G     0  5.9G   0% /dev/shm
tmpfs                5.9G  9.0M  5.8G   1% /run
tmpfs                5.9G     0  5.9G   0% /sys/fs/cgroup
/dev/mapper/cs-root   17G  1.8G   16G  11% /
/dev/sda1           1014M  211M  804M  21% /boot
tmpfs                1.2G     0  1.2G   0% /run/user/0
/dev/sdb1            187G  1.4G  185G   1% /kvmdata

KVM安装
关闭防火墙和selinux
[root@localhost ~]# systemctl stop firewalld.service 
[root@localhost ~]# systemctl disable firewalld.service 
Removed /etc/systemd/system/multi-user.target.wants/firewalld.service.
Removed /etc/systemd/system/dbus-org.fedoraproject.FirewallD1.service.
[root@localhost ~]# setenforce 0
[root@localhost ~]# sed -i 's/SELINUX=.*/SELINUX=disabled/' /etc/sysconfig/selinux
部署yum源
[root@localhost ~]# cd /etc/yum.repos.d/
[root@localhost yum.repos.d]# rm -rf *
[root@localhost yum.repos.d]# ls
[root@localhost yum.repos.d]# curl -o /etc/yum.repos.d/CentOS-Base.repo https://mirrors.aliyun.com/repo/Centos-vault-8.5.2111.repo

安装所需软件包
[root@localhost yum.repos.d]# yum -y install epel-release vim wget net-tools unzip zip gcc gcc-c++
----
验证cpu是否支持kvm,vmx是intel的  svm是AMD的
[root@localhost yum.repos.d]# egrep -o 'vmx|svm' /proc/cpuinfo 
vmx
vmx
vmx
vmx

安装kvm
[root@localhost yum.repos.d]# yum -y install qemu-kvm qemu-img  virt-manager  libvirt  libvirt-python3  libvirt-client  virt-install  virt-viewer  bridge-utils  libguestfs-tools

配置网络,因为虚拟机中的网络,我们一般是都和公司服务器处在同一网段的,所以我们需要把kvm的网卡配置成桥接模式

[root@localhost yum.repos.d]#  cd /etc/sysconfig/network-scripts/
[root@localhost network-scripts]# cp ifcfg-ens33 ifcfg-br0
[root@localhost network-scripts]# ls
ifcfg-br0  ifcfg-ens33
[root@localhost network-scripts]# cat > ifcfg-br0 <
> TYPE=Bridge
> BOOTPROTO=none
> NAME=br0
> DEVICE=br0
> ONBOOT=yes
> IPADDR=192.168.245.127
> PREFIX=24
> GATEWAY=192.168.245.2
> DNS=8.8.8.8
> EOF
[root@localhost network-scripts]# cat > ifcfg-ens33 <
> TYPE=Ethernet
> BOOTPROTO=none
> NAME=ens33
> DEVICE=ens33
> ONBOOT=yes
> BRIDGE=br0
> EOF
[root@localhost network-scripts]# nmcli connection reload
[root@localhost network-scripts]# nmcli connection up ens33
[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: ens33: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc fq_codel master br0 state UP group default qlen 1000
    link/ether 00:0c:29:7f:82:fa brd ff:ff:ff:ff:ff:ff
3: br0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP group default qlen 1000
    link/ether 00:0c:29:7f:82:fa brd ff:ff:ff:ff:ff:ff
    inet 192.168.245.127/24 brd 192.168.245.255 scope global noprefixroute br0
       valid_lft forever preferred_lft forever
    inet6 fe80::20c:29ff:fe7f:82fa/64 scope link 
       valid_lft forever preferred_lft forever

启动及配置

[root@localhost ~]# systemctl enable --now libvirtd
[root@localhost ~]# lsmod |grep kvm
kvm_intel             339968  0
kvm                   905216  1 kvm_intel
irqbypass              16384  1 kvm
#软连接:
[root@localhost ~]# ln -s /usr/libexec/qemu-kvm /usr/bin/qemu-kvm
[root@localhost ~]# ll /usr/bin/qemu-kvm
lrwxrwxrwx. 1 root root 21 Oct  6 13:08 /usr/bin/qemu-kvm -> /usr/libexec/qemu-kvm
#看一下网路
[root@localhost ~]# brctl show
bridge name     bridge id               STP enabled     interfaces
br0             8000.000c297f82fa       no              ens33
virbr0          8000.525400730ec0       yes             virbr0-nic
[root@localhost ~]# 
kvm管理界面安装
[root@localhost ~]# yum -y install git python2-pip supervisor nginx python2-devel
---
[root@localhost webvirtmgr-master]# rpm -ivh --nodeps libxml2-python-2.9.1-6.el7.5.x86_64.rpm
[root@localhost webvirtmgr-master]# rpm -ivh --nodeps python-websockify-0.6.0-2.el7.noarch.rpm
#从github上下载webvirtmgr代码
[root@localhost ~]# wget https://download-ib01.fedoraproject.org/pub/epel/7/x86_64/Packages/p/python-websockify-0.6.0-2.el7.noarch.rpm

[root@localhost src]# ls
webvirtmgr-master
[root@localhost webvirtmgr-master]#  pip install -r requirements.txt


检查sqlite3是否下载
[root@localhost src]# python3
Python 3.6.8 (default, Jan 19 2022, 23:28:49) 
[GCC 8.5.0 20210514 (Red Hat 8.5.0-7)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import sqlite3
>>> exit()

初始化账号信息
[root@localhost webvirtmgr-master]# python2 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): uy^H^H
Please enter either "yes" or "no": yes		#是否创建超级管理员账户	
Username (leave blank to use 'root'): root 	#设置用户名
Email address: 123@qq.com	#用户邮箱
Password: 	#设置密码	
Password (again): 	#确认一遍
Superuser created successfully.
Installing custom SQL ...
Installing indexes ...
Installed 6 object(s) from 1 fixture(s)
拷贝web网页到指定目录
[root@localhost webvirtmgr-master]#  mkdir /var/www
[root@localhost webvirtmgr-master]#  cp -r /usr/local/src/webvirtmgr-master/ /var/www/
[root@localhost webvirtmgr-master]#  chown -R nginx.nginx /var/www/webvirtmgr-master/

生成一对公钥与私钥,由于这里webvirtmgr和kvm服务部署在同一台主机中,所以这里本地信任。如果kvm部署在其他机器上的时候,那么就需要把公钥发送到kvm主机中

[root@localhost webvirtmgr-master]# ssh-keygen
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:
[root@localhost webvirtmgr-master]# ssh-copy-id -i ~/.ssh/id_rsa.pub [email protected]
[root@localhost webvirtmgr-master]#  ssh 192.168.245.127 -L localhost:8000:localhost:8000 -L localhost:6080:localhost:60
Last login: Thu Oct  6 17:37:06 2022 from 192.168.245.1
[root@localhost ~]# ss -antl
State       Recv-Q      Send-Q           Local Address:Port            Peer Address:Port      Process      
LISTEN      0           128                    0.0.0.0:111                  0.0.0.0:*                      
LISTEN      0           32               192.168.122.1:53                   0.0.0.0:*                      
LISTEN      0           128                    0.0.0.0:22                   0.0.0.0:*                      
LISTEN      0           128                  127.0.0.1:6080                 0.0.0.0:*                      
LISTEN      0           128                  127.0.0.1:8000                 0.0.0.0:*                      
LISTEN      0           128                       [::]:111                     [::]:*                      
LISTEN      0           128                       [::]:22                      [::]:*                      
LISTEN      0           128                      [::1]:6080                    [::]:*                      
LISTEN      0           128                      [::1]:8000                    [::]:*     

配置nginx

[root@localhost ~]#  cp /etc/nginx/nginx.conf /etc/nginx/nginx.conf.bak
[root@localhost ~]# vim /etc/nginx/nginx.conf
    server {
        listen       [::]:80 default_server;
        server_name  localhost;

        # Load configuration files for the default server block.
        include /etc/nginx/default.d/*.conf;

        location / {
        root    html;
               index   index.html index.htm;
配置nginx虚拟主机
[root@localhost ~]#  vim /etc/nginx/conf.d/webvirtmgr.conf
[root@localhost ~]# 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/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;
                                                                                                            }
}
确保bind绑定本机的8000端口
[root@localhost ~]#  vim /var/www/webvirtmgr-master/conf/gunicorn.conf.py
[root@localhost ~]# cat /var/www/webvirtmgr-master/conf/gunicorn.conf.py|grep bind
# bind - The socket to bind.
bind = '127.0.0.1:8000'
重启nginx服务,查看端口是否开启
[root@localhost ~]# ss -antl
State       Recv-Q      Send-Q           Local Address:Port            Peer Address:Port      Process      
LISTEN      0           128                    0.0.0.0:111                  0.0.0.0:*                      
LISTEN      0           32               192.168.122.1:53                   0.0.0.0:*                      
LISTEN      0           128                    0.0.0.0:22                   0.0.0.0:*                      
LISTEN      0           128                  127.0.0.1:6080                 0.0.0.0:*                      
LISTEN      0           128                  127.0.0.1:8000                 0.0.0.0:*                      
LISTEN      0           128                       [::]:111                     [::]:*                      
LISTEN      0           128                       [::]:22                      [::]:*                      
LISTEN      0           128                      [::1]:6080                    [::]:*                      
LISTEN      0           128                      [::1]:8000                    [::]:*           
设置supervisor
[root@localhost ~]# vim /etc/supervisord.conf
//在文件最后添加如下信息
[program:webvirtmgr]
#这里command是一行
command=/usr/bin/python2 /var/www/webvirtmgr/manage.py run_gunicorn -c /var/www/webvirtmgr/conf/gunicorn.conf.py
directory=/var/www/webvirtmgr
autostart=true
autorestart=true
logfile=/var/log/supervisor/webvirtmgr.log
log_stderr=true
user=nginx

[program:webvirtmgr-console]
command=/usr/bin/python2 /var/www/webvirtmgr/console/webvirtmgr-console
directory=/var/www/webvirtmgr
autostart=true
autorestart=true
stdout_logfile=/var/log/supervisor/webvirtmgr-console.log
redirect_stderr=true
user=nginx
启动supervisor并设置开机自启
[root@localhost ~]# systemctl restart supervisord.service 
[root@localhost ~]# systemctl enable supervisord.service 
Created symlink /etc/systemd/system/multi-user.target.wants/supervisord.service → /usr/lib/systemd/system/supervisord.service.

配置nginx用户
[nginx@localhost ~]$ su - nginx -s /bin/bash
[nginx@localhost ~]$ su - nginx -s /bin/bash
Password: 
su: Authentication failure
[nginx@localhost ~]$ 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:VMO3gXYYU3uDtDgW2uYtfObXfWVU8vRxBcPXc7gIaeA [email protected]
The key's randomart image is:
+---[RSA 3072]----+
|        .o**o.++B|
|       . +O*++o*O|
|        Eo*+++oo*|
|       . = oo..o |
|        S + +   o|
|           =   oo|
|            . . +|
|             .  .|
|                 |
+----[SHA256]-----+
[nginx@localhost ~]$ 
[nginx@localhost ~]$ echo -e "StrictHostKeyChecking=no\nUserKnownHostsFile=/dev/null" > ~/.ssh/config
[nginx@localhost ~]$ cat .ssh/config 
StrictHostKeyChecking=no
UserKnownHostsFile=/dev/null
[nginx@localhost ~]$ chmod 600 .ssh/config
[nginx@localhost ~]$ ssh-copy-id [email protected]
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/var/lib/nginx/.ssh/id_rsa.pub"
/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
Warning: Permanently added '192.168.245.127' (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.
[nginx@localhost ~]$ exit
logout
[root@localhost ~]# vim /etc/polkit-1/localauthority/50-local.d/50-libvirt-remote-access.pkla
[root@localhost ~]# 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@localhost ~]#  systemctl restart nginx
Job for nginx.service failed because the control process exited with error code.
See "systemctl status nginx.service" and "journalctl -xe" for details.
[root@localhost ~]# systemctl restart libvirtd
[root@localhost ~]#  ss -antl
State       Recv-Q      Send-Q           Local Address:Port            Peer Address:Port      Process      
LISTEN      0           128                    0.0.0.0:111                  0.0.0.0:*                      
LISTEN      0           32               192.168.122.1:53                   0.0.0.0:*                      
LISTEN      0           128                    0.0.0.0:22                   0.0.0.0:*                      
LISTEN      0           128                  127.0.0.1:6080                 0.0.0.0:*                      
LISTEN      0           128                  127.0.0.1:8000                 0.0.0.0:*                      
LISTEN      0           128                       [::]:111                     [::]:*                      
LISTEN      0           128                       [::]:22                      [::]:*                      
LISTEN      0           128                      [::1]:6080                    [::]:*                      
LISTEN      0           128                      [::1]:8000                    [::]:*        

KVM虚拟化_第3张图片

KVM虚拟化_第4张图片

KVM虚拟化_第5张图片

KVM虚拟化_第6张图片

KVM虚拟化_第7张图片

KVM虚拟化_第8张图片

KVM虚拟化_第9张图片

KVM虚拟化_第10张图片

你可能感兴趣的:(linux服务,运维)