kvm部署

简介

KVM — 全称是基于内核的虚拟机(Kernel-based Virtual Machine)

  • KVM是一个开源软件,基于内核的虚拟化技术,实际是嵌入系统的一个虚拟化模块,通过优化内核来使用虚拟技术,该内核模块使得 Linux 变成了一个Hypervisor,虚拟机使用 Linux 自身的调度器进行管理。
  • KVM 是基于虚拟化扩展(Intel VT 或者 AMD-V)的 X86 硬件的开源的 Linux 原生的全虚拟化解决方案。KVM 中,虚拟机被实现为常规的 Linux 进程,由标准 Linux 调度程序进行调度;虚机的每个虚拟 CPU 被实现为一个常规的 Linux 进程。这使得 KMV 能够使用 Linux 内核的已有功能。但是,KVM 本身不执行任何硬件模拟,需要客户空间程序通过 /dev/kvm 接口设置一个客户机虚拟服务器的地址空间,向它提供模拟的 I/O,并将它的视频显示映射回宿主的显示屏。目前这个应用程序是 QEMU。
  • Guest:客户机系统,包括CPU(vCPU)、内存、驱动(Console、网卡、I/O 设备驱动等),被 KVM 置于一种受限制的 CPU 模式下运行。
  • KVM:运行在内核空间,提供CPU 和内存的虚级化,以及客户机的 I/O 拦截。Guest 的 I/O 被 KVM 拦截后,交给 QEMU 处理。
  • QEMU:修改过的为 KVM 虚机使用的 QEMU 代码,运行在用户空间,提供硬件 I/O 虚拟化,通过IOCTL /dev/kvm 设备和 KVM 交互。

KVM模块和管理工具
KVM有一个内核模块叫 kvm.ko,只用于管理虚拟 CPU 和内存。IO 的虚拟化,就交给 Linux 内核和qemu来实现。

Libvirt:是 KVM 的管理工具。Libvirt 除了能管理 KVM 这种 Hypervisor,还能管理 Xen,VirtualBox 等。OpenStack 底层也使用 Libvirt。

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

  • libvirtd是服务程序,接收和处理 API 请求;
  • API 库使得其他人可以开发基于 Libvirt 的高级工具,比如 virt-manager,这是个图形化的 KVM 管理工具,后面我们也会介绍;
  • virsh 是我们运维工程师经常要用的 KVM 命令行工具。作为 KVM 和 OpenStack 的实施人员,virsh 和 virt-manager 是一定要会用的。

KVM安装

主机 ip 职责 系统
kvm 192.168.111.141 kvm redhat8
kvm-web 192.168.111.143 nginx、kvm Web centos7
//关闭防火墙和selinux
[root@localhost ~]# systemctl disable --now firewalld
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 -ri 's/^(SELINUX=).*/\1disabled/g' /etc/selinux/config
[root@localhost ~]# getenforce 
Permissive
[root@localhost ~]# reboot

[root@localhost ~]# getenforce 
Disabled

//配置网络源并下载相应的工具
dnf -y install epel-release vim wget net-tools unzip zip gcc gcc-c++

//验证cpu是否支持kvm,如果结果中有vmx或svm字样,就说明cpu是支持的
svm                 //svm的多少在于你给的cpu核数

//安装依赖包和kvm
[root@localhost ~]# yum -y install qemu-kvm qemu-kvm-common qemu-img virt-manager libvirt python3-libvirt libvirt-client virt-install virt-viewer bridge-utils libguestfs-tools

//配置桥接网卡 
因为虚拟机中网络,我们一般都是和公司的其他服务器是同一个网段,所以我们需要把
KVM服务器的网卡配置成桥接模式。这样的话KVM的虚拟机就可以通过该桥接网卡和公司内部
其他服务器处于同一网段

此处我的网卡是ens160,所以用br0来桥接ens160网卡

[root@localhost network-scripts]# cat ifcfg-br0 
TYPE=Bridge
BOOTPROTO=static
NAME=br0
DEVICE=br0
ONBOOT=yes
IPADDR=192.168.111.141
PREFIX=24
GATEWAY=192.168.200.2
DNS1=114.114.114.114
[root@localhost network-scripts]# cat ifcfg-ens160 
TYPE=Ethernet
BOOTPROTO=static
NAME=ens160
DEVICE=ens160
ONBOOT=yes
IPV6_PRIVACY=no
BRIDGE=br0

//重启网卡
[root@localhost ~]# systemctl restart NetworkManager
[root@localhost ~]# ifdown ens160;ifup ens160
Error: '/etc/sysconfig/network-scripts/ifcfg-ens160' is not an active connection.
Error: no active connection provided.
Connection successfully activated (D-Bus active path: /org/freedesktop/NetworkManager/ActiveConnection/3)
[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: ens160: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc fq_codel master br0 state UP group default qlen 1000
    link/ether 00:0c:29:07:67:13 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:07:67:13 brd ff:ff:ff:ff:ff:ff
    inet 192.168.111.141/24 brd 192.168.111.255 scope global noprefixroute br0
       valid_lft forever preferred_lft forever
    inet6 fe80::20c:29ff:fe07:6713/64 scope link 
       valid_lft forever preferred_lft forever

//启动服务并验证安装结果
[root@localhost network-scripts]# lsmod|grep kvm
kvm_intel             315392  0
kvm                   847872  1 kvm_intel
irqbypass              16384  1 kvm
[root@localhost network-scripts]# virsh -c qemu:///system list
 Id   名称   状态
-------------------

[root@localhost network-scripts]# virsh --version
6.0.0
[root@localhost network-scripts]# virt-install --version
2.2.1
[root@localhost network-scripts]# ln -s /usr/libexec/qemu-kvm /usr/bin/qemu-kvm
[root@localhost network-scripts]# ll /usr/bin/qemu-kvm
lrwxrwxrwx 1 root root 21 10月 20 23:05 /usr/bin/qemu-kvm -> /usr/libexec/qemu-kvm
[root@localhost network-scripts]# brctl show
bridge name     bridge id               STP enabled     interfaces
br0             8000.000000000000       no              
virbr0          8000.52540016ec1b       yes             virbr0-nic

kvm web管理界面部署

#安装epel源
[root@kvm-web ~]# yum -y install epel-release
#安装软件包
[root@kvm-web ~]# yum -y install git python-pip libvirt-python libxml2-python python-websockify supervisor nginx python-devel

#从github上下载webvirtmgr代码
[root@kvm-web ~]# cd /usr/local/src
[root@kvm-web src]# git clone git://github.com/retspen/webvirtmgr.git
正克隆到 'webvirtmgr'...
remote: Enumerating objects: 5614, done.
remote: Total 5614 (delta 0), reused 0 (delta 0), pack-reused 5614
接收对象中: 100% (5614/5614), 2.97 MiB | 225.00 KiB/s, 完成.
处理 delta 中: 100% (3606/3606), 完成.

#安装webvirtmgr
[root@kvm-web src]# cd webvirtmgr/
[root@kvm-web webvirtmgr]# 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)
    100% |████████████████████████████████| 8.1MB 91kB/s 
Collecting gunicorn==19.5.0 (from -r requirements.txt (line 2))
  Downloading https://files.pythonhosted.org/packages/f9/4e/f4076a1a57fc1e75edc0828db365cfa9005f9f6b4a51b489ae39a91eb4be/gunicorn-19.5.0-py2.py3-none-any.whl (113kB)
    100% |████████████████████████████████| 122kB 1.5MB/s 
Collecting lockfile>=0.9 (from -r requirements.txt (line 5))
  Downloading https://files.pythonhosted.org/packages/c8/22/9460e311f340cb62d26a38c419b1381b8593b0bb6b5d1f056938b086d362/lockfile-0.12.2-py2.py3-none-any.whl
Installing collected packages: django, gunicorn, lockfile
  Running setup.py install for django ... done
Successfully installed django-1.5.5 gunicorn-19.5.0 lockfile-0.12.2
You are using pip version 8.1.2, however version 21.3 is available.
You should consider upgrading via the 'pip install --upgrade pip' command.


#初始化账号信息
[root@kvm-web webvirtmgr]# python
Python 2.7.5 (default, Nov 16 2020, 22:23:17) 
[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]# 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		//问你是否创建超级管理员帐号
Username (leave blank to use 'root'): admin		//指定超级管理员帐号用户名,默认留空为root
Email address: 1@2.com		//设置超级管理员邮箱
Password: 		//设置超级管理员密码
Password (again): 		 //再次输入超级管理员密码
Superuser created successfully.
Installing custom SQL ...
Installing indexes ...
Installed 6 object(s) from 1 fixture(s)

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

#生成密钥
[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): 
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:V73NQ4AADyxZb3tXVzfDnzOJCFWagswOxZ/m4X0d9gA root@kvm-web
The key's randomart image is:
+---[RSA 2048]----+
|      ==..o.oo.oo|
|     o+o=. .E...=|
|     ..+.=ooo.oo=|
|      o .=oo .+@o|
|       .S.+. .+oB|
|         +.... .o|
|            .    |
|                 |
|                 |
+----[SHA256]-----+
[root@kvm-web ~]# ssh-copy-id 192.168.111.141
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/root/.ssh/id_rsa.pub"
The authenticity of host '192.168.111.141 (192.168.111.141)' can't be established.
ECDSA key fingerprint is SHA256:M55K1WE4IQkTBu6mvhszdufPrKh0hripkeHuF9Em52k.
ECDSA key fingerprint is MD5:11:9b:42:bc:29:ae:63:96:04:de:b7:35:97:d9:5a:7d.
Are you sure you want to continue connecting (yes/no)? 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
root@192.168.111.141's password: 

Number of key(s) added: 1

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


#配置端口转发
[root@kvm-web ~]# ssh 192.168.111.141 -L localhost:8000:localhost:8000 -L localhost:6080:localhost:60
Last login: Wed Oct 20 20:01:05 2021 from 192.168.8.1



#配置nginx
[root@kvm-web ~]# vim /etc/nginx/nginx.conf
    server {
        listen       80;
        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;
        }

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

        error_page 500 502 503 504 /50x.html;
        location = /50x.html {
        }
    }


[root@kvm-web ~]# vim /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;
    }
}

#确保绑定的端口为8000
[root@kvm-web ~]# vim /var/www/webvirtmgr/conf/gunicorn.conf.py 
bind = '0.0.0.0:8000'

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

#设置supervisor
[root@kvm-web ~]# vim /etc/supervisord.conf		//文件最后加上以下内容
[program:webvirtmgr]
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@kvm-web ~]# systemctl enable --now supervisord
Created symlink /etc/systemd/system/multi-user.target.wants/supervisord.service → /usr/lib/systemd/system/supervisord.service.
[root@kvm-web ~]# ss -antl
State       Recv-Q Send-Q              Local Address:Port                             Peer Address:Port              
LISTEN      0      100                             *:6080                                        *:*                  
LISTEN      0      128                             *:8000                                        *:*                  
LISTEN      0      128                             *:80                                          *:*                  
LISTEN      0      128                             *:22                                          *:*                  
LISTEN      0      100                     127.0.0.1:25                                          *:*                  
LISTEN      0      128                            :::22                                         :::*                  
LISTEN      0      100                           ::1:25                                         :::*   

#配置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:hX/6QlHkMXiEyq0L2bk/A9nXoSuzRphoS8oORGom3+o nginx@kvm-web
The key's randomart image is:
+---[RSA 2048]----+
|           ==    |
|         .o.oo   |
|  .    ..o.o.    |
| o      ooo   .  |
|oo.    +SB...o . |
|+o .  * O +oo .  |
|  o..+ o *.. .   |
|   oo . o B..    |
| .E..    ooB.    |
+----[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 root@192.168.111.143
/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.111.143' (ECDSA) to the list of known hosts.
root@192.168.111.143's password: 

Number of key(s) added: 1

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

-bash-4.2$ exit
登出

[root@kvm-web ~]# vim /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 ~]# systemctl restart nginx

[root@KVM ~]# systemctl restart libvirtd


kvm部署
kvm部署

kvm部署
kvm部署
kvm部署

kvm部署
上传镜像然后刷新
kvm部署

kvm部署
kvm部署kvm部署

kvm部署
kvm部署
kvm部署
kvm部署

kvm部署

kvm部署
kvm部署
kvm部署
kvm部署

kvm部署

上一篇:虚拟化KVM


下一篇:KVM部署