KVM虚拟化用WEB界面安装一台虚拟机

虚拟化介绍

虚拟化是云计算的基础。简单的说,虚拟化使得在一台物理的服务器上可以跑多台虚拟机,虚拟机共享物理机的 CPU、内存、IO 硬件资源,但逻辑上虚拟机之间是相互隔离的。

物理机我们一般称为宿主机(Host),宿主机上面的虚拟机称为客户机(Guest)。

那么 Host 是如何将自己的硬件资源虚拟化,并提供给 Guest 使用的呢?
这个主要是通过一个叫做 Hypervisor 的程序实现的。

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

  • 全虚拟化
  • 半虚拟化

全虚拟化:
Hypervisor 直接安装在物理机上,多个虚拟机在 Hypervisor 上运行。Hypervisor 实现方式一般是一个特殊定制的 Linux 系统。Xen 和 VMWare 的 ESXi 都属于这个类型

半虚拟化:
物理机上首先安装常规的操作系统,比如 Redhat、Ubuntu 和 Windows。Hypervisor 作为 OS 上的一个程序模块运行,并对管理虚拟机进行管理。KVM、VirtualBox 和 VMWare Workstation 都属于这个类型

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

2. kvm介绍

kVM 全称是 Kernel-Based Virtual Machine。也就是说 KVM 是基于 Linux 内核实现的。
KVM有一个内核模块叫 kvm.ko,只用于管理虚拟 CPU 和内存。

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

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

大家在网上看 KVM 相关文章的时候肯定经常会看到 Libvirt 这个东西。

Libvirt 就是 KVM 的管理工具。

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

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

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

3. kvm部署

环境说明:

系统类型 IP
RHEL7 192.168.142.136
[root@Soap ~]# parted /dev/sdb
GNU Parted 3.2
Using /dev/sdb
Welcome to GNU Parted! Type 'help' to view a list of commands.
(parted)
align-check  help         mktable      quit         resizepart   set          version
disk_set     mklabel      name         rescue       rm           toggle
disk_toggle  mkpart       print        resize       select       unit
(parted) mklabel
New disk label type? msdos
(parted) unit
Unit?  [compact]? MiB
(parted) p
Model: VMware, VMware Virtual S (scsi)
Disk /dev/sdb: 102400MiB
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? 102200MIB
(parted) p
Model: VMware, VMware Virtual S (scsi)
Disk /dev/sdb: 102400MiB
Sector size (logical/physical): 512B/512B
Partition Table: msdos
Disk Flags:

Number  Start    End        Size       Type     File system  Flags
 1      10.0MiB  102200MiB  102190MiB  primary  xfs          lba

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

[root@Soap ~]# udevadm settle
[root@Soap ~]# lsblk
NAME        MAJ:MIN RM  SIZE RO TYPE MOUNTPOINT
sda           8:0    0   20G  0 disk
├─sda1        8:1    0    1G  0 part /boot
└─sda2        8:2    0   19G  0 part
  ├─cs-root 253:0    0   17G  0 lvm  /
  └─cs-swap 253:1    0    2G  0 lvm  [SWAP]
sdb           8:16   0  100G  0 disk
└─sdb1        8:17   0 99.8G  0 part
sr0          11:0    1 10.4G  0 rom
[root@Soap ~]# mkfs.xfs /dev/sdb1
[root@Soap ~]# blkid /dev/sdb1
/dev/sdb1: UUID="c745e19f-81d6-4bb9-8762-54921a019d51" BLOCK_SIZE="512" TYPE="xfs" PARTUUID="e4678aad-01"
[root@Soap ~]# vim /etc/fstab
[root@Soap ~]# cat /etc/fstab
UUID="c745e19f-81d6-4bb9-8762-54921a019d51"     /kvmdata        xfs     defaults        0 0
[root@Soap ~]# systemctl stop firewalld
[root@Soap ~]# systemctl disable firewalld
[root@Soap ~]# vim /etc/sysconfig/selinux
[root@Soap ~]# cat /etc/sysconfig/selinux
SELINUX=disabled
[root@Soap ~]# reboot
[root@Soap ~]# yum -y install epel-release vim wget net-tools unzip zip gcc gcc-c++
[root@Soap ~]# egrep -o 'vmx|svm' /proc/cpuinfo
vmx
[root@soap ~]# 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
[root@soap ~]# cd /etc/sysconfig/network-scripts/
[root@soap network-scripts]# ls
ifcfg-ens33  ifdown-ipv6    ifdown-TeamPort  ifup-ippp   ifup-routes       network-functions
ifcfg-lo     ifdown-isdn    ifdown-tunnel    ifup-ipv6   ifup-sit          network-functions-ipv6
ifdown       ifdown-post    ifup             ifup-isdn   ifup-Team
ifdown-bnep  ifdown-ppp     ifup-aliases     ifup-plip   ifup-TeamPort
ifdown-eth   ifdown-routes  ifup-bnep        ifup-plusb  ifup-tunnel
ifdown-ib    ifdown-sit     ifup-eth         ifup-post   ifup-wireless
ifdown-ippp  ifdown-Team    ifup-ib          ifup-ppp    init.ipv6-global
[root@soap network-scripts]# cp ifcfg-ens33 ifcfg-br0
[root@soap network-scripts]# vim ifcfg-ens33
[root@soap network-scripts]# cat ifcfg-ens33
TYPE="Ethernet"
BOOTPROTO=none
NAME="ens33"
DEVICE="ens33"
ONBOOT="yes"
BRIDGE=br0
[root@soap network-scripts]# cat ifcfg-br0
TYPE=bridge
BOOTPROTO=none
NAME=br0
DEVICE=br0
ONBOOT="yes"
IPADDR=192.168.142.136
PREFIX=24
GATEWAY=192.168.142.2
DNS1=114.114.114.114
[root@soap network-scripts]# systemctl restart NetworkManager
[root@soap network-scripts]# ifdown ens33 ;ifup ens33
[root@soap network-scripts]# cd
[root@soap ~]# systemctl restart libvirtd
[root@soap ~]# systemctl enable libvirtd
[root@soap ~]# systemctl status libvirtd
 libvirtd.service - Virtualization daemon
   Loaded: loaded (/usr/lib/systemd/system/libvirtd.service; enabled; vendor preset: enabled)
   Active: active (running) since Fri 2022-09-30 06:29:16 EDT; 15s ago
     Docs: man:libvirtd(8)
           https://libvirt.org
 Main PID: 12546 (libvirtd)
   CGroup: /system.slice/libvirtd.service
           ├─12546 /usr/sbin/libvirtd
           ├─12656 /usr/sbin/dnsmasq --conf-file=/var/lib/libvirt/dnsmasq/default.conf --leasefile-...
           └─12657 /usr/sbin/dnsmasq --conf-file=/var/lib/libvirt/dnsmasq/default.conf --leasefile-...
Sep 30 06:29:16 soap dnsmasq[12649]: listening on virbr0(#4): 192.168.122.1
Sep 30 06:29:16 soap dnsmasq[12656]: started, version 2.76 cachesize 150
Sep 30 06:29:16 soap dnsmasq[12656]: compile time options: IPv6 GNU-getopt DBus no-i18n IDN DHC...tify
Sep 30 06:29:16 soap dnsmasq-dhcp[12656]: DHCP, IP range 192.168.122.2 -- 192.168.122.254, lease... 1h
Sep 30 06:29:16 soap dnsmasq-dhcp[12656]: DHCP, sockets bound exclusively to interface virbr0
Sep 30 06:29:16 soap dnsmasq[12656]: reading /etc/resolv.conf
Sep 30 06:29:16 soap dnsmasq[12656]: using nameserver 8.8.8.8#53
Sep 30 06:29:16 soap dnsmasq[12656]: read /etc/hosts - 2 addresses
Sep 30 06:29:16 soap dnsmasq[12656]: read /var/lib/libvirt/dnsmasq/default.addnhosts - 0 addresses
Sep 30 06:29:16 soap dnsmasq-dhcp[12656]: read /var/lib/libvirt/dnsmasq/default.hostsfile
[root@soap ~]# lsmod | grep kvm
kvm_intel             170086  0
kvm                   566340  1 kvm_intel
irqbypass              13503  1 kvm
[root@soap ~]# virsh -c qemu:///system list
 Id    Name                           State
----------------------------------------------------
[root@soap ~]# virsh --version
4.5.0
[root@soap ~]# virt-install --version
1.5.0
[root@soap ~]# ln -s /usr/libexec/qemu-kvm /usr/bin/qemu-kvm
[root@soap ~]# ll /usr/bin/qemu-kvm
lrwxrwxrwx 1 root root 21 Sep 30 06:31 /usr/bin/qemu-kvm -> /usr/libexec/qemu-kvm
[root@soap ~]# brctl show
bridge name     bridge id               STP enabled     interfaces
br0             8000.000c29ffce46       no              ens33
virbr0          8000.5254001acd78       yes             virbr0-nic
[root@soap ~]# yum -y install git python-pip libvirt-python libxml2-python python-websockify supervisor nginx python-devel
[root@soap ~]# cd /usr/local/src/
[root@cy src]# git clone http://github.com/retspen/webvirtmgr.git
[root@soap src]# ls
webvirtmgr
[root@soap src]# cd webvirtmgr/
[root@soap src]# cd webvirtmgr/
[root@soap 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 99MB/s
Collecting gunicorn==18.0 (from -r requirements.txt (line 2))
  Retrying (Retry(total=4, connect=None, read=None, redirect=None)) after connection broken by 'NewConnectionError('<pip._vendor.requests.packages.urllib3.connection.VerifiedHTTPSConnection object at 0x7f98c9cb0810>: Failed to establish a new connection: [Errno 101] Network is unreachable',)': /simple/gunicorn/
  Retrying (Retry(total=4, connect=None, read=None, redirect=None)) after connection broken by 'ReadTimeoutError("HTTPSConnectionPool(host='pypi.org', port=443): Read timed out. (read timeout=15)",)': /simple/gunicorn/
  Downloading https://files.pythonhosted.org/packages/cc/8f/82d9d1ae8cd417421f4ccb04bf8a8d75767b324c50bc83a9be9d4122c01a/gunicorn-18.0.tar.gz (366kB)
    100% |████████████████████████████████| 368kB 99MB/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
  Running setup.py install for gunicorn ... done
Successfully installed django-1.5.5 gunicorn-18.0 lockfile-0.12.2
You are using pip version 8.1.2, however version 22.2.2 is available.
You should consider upgrading via the 'pip install --upgrade pip' command.
[root@soap webvirtmgr]# python
Python 2.7.5 (default, Jun 28 2022, 15:30:04)
[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@soap webvirtmgr]# cd /usr/local/src/webvirtmgr/
[root@soap 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'):
Email address: 1548126326@qq.com
Password:
Password (again):
Superuser created successfully.
Installing custom SQL ...
Installing indexes ...
Installed 6 object(s) from 1 fixture(s)
[root@soap webvirtmgr]# mkdir /var/www
[root@soap webvirtmgr]# cp -r /usr/local/src/webvirtmgr/ /var/www/
[root@soap webvirtmgr]# chown -R nginx.nginx /var/www/webvirtmgr/
[root@soap webvirtmgr]# 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:
SHA256:0k+O1712+vhxJdtMKm7KQfkrt7LgEsdav+cfl6iLqFU root@soap
The key's randomart image is:
+---[RSA 2048]----+
|                 |
|                 |
|                 |
|       .   .     |
|      ..SE+   . o|
|      ..=* o ..Bo|
|       *o.= +.=o=|
|      +..+=o=o.=+|
|     ..o..=&*+==o|
+----[SHA256]-----+
[root@soap webvirtmgr]# ssh-copy-id -i ~/.ssh/id_rsa.pub root@192.168.142.136
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/root/.ssh/id_rsa.pub"
The authenticity of host '192.168.142.136 (192.168.142.136)' can't be established.
ECDSA key fingerprint is SHA256:KOgLpkxA9uKybJA08nxWwbbe9qS6stzAQFBLRNsXB3Q.
ECDSA key fingerprint is MD5:48:15:30:1d:4f:91:3a:de:7b:d5:a1:98:fc:fc:c5:e5.
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.142.136's password:

Number of key(s) added: 1
[root@soap webvirtmgr]# ssh 192.168.142.136 -L localhost:8000:localhost:8000 -L localhost:6080:localhost:60
Now try logging into the machine, with:   "ssh 'root@192.168.142.136'"
and check to make sure that only the key(s) you wanted were added.

[root@soap ~]# ss -antl
State      Recv-Q Send-Q      Local Address:Port                     Peer Address:Port
LISTEN     0      128                     *:111                                 *:*
LISTEN     0      5           192.168.122.1:53                                  *:*
LISTEN     0      128                     *:22                                  *:*
LISTEN     0      100             127.0.0.1:25                                  *:*
LISTEN     0      128             127.0.0.1:6080                                *:*
LISTEN     0      128             127.0.0.1:8000                                *:*
LISTEN     0      128                    :::111                                :::*
LISTEN     0      128                    :::22                                 :::*
LISTEN     0      100                   ::1:25                                 :::*
LISTEN     0      128                   ::1:6080                               :::*
LISTEN     0      128                   ::1:8000                               :::*
[root@soap ~]# cp /etc/nginx/nginx.conf /etc/nginx/nginx.conf.bak
[root@soap ~]#  vim /etc/nginx/nginx.conf
//在server参数中进行修改
删除listen       [::]:80;行
参数server_name行改成server_name  localhost;
删除root         /usr/share/nginx/html;行
在include /etc/nginx/default.d/*.conf;行下添加
location / {
       root    html;
       index   index.html index.htm;
      }
[root@soap ~]# vim /etc/nginx/conf.d/webvirtmgr.conf
[root@soap ~]# 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;
    }
}
[root@soap ~]# vim /var/www/webvirtmgr/conf/gunicorn.conf.py
[root@soap ~]# grep bind /var/www/webvirtmgr/conf/gunicorn.conf.py
# bind - The socket to bind.
bind = '127.0.0.1:8000'			//确认此处必须是8000,好处是不用跟端口号可以直接进行访问
[root@soap ~]# systemctl restart nginx
[root@soap ~]# ss -antl
State      Recv-Q Send-Q      Local Address:Port                     Peer Address:Port
LISTEN     0      128                     *:111                                 *:*
LISTEN     0      128                     *:80                                  *:*
LISTEN     0      5           192.168.122.1:53                                  *:*
LISTEN     0      128                     *:22                                  *:*
LISTEN     0      100             127.0.0.1:25                                  *:*
LISTEN     0      128             127.0.0.1:6080                                *:*
LISTEN     0      128             127.0.0.1:8000                                *:*
LISTEN     0      128                    :::111                                :::*
LISTEN     0      128                    :::80                                 :::*
LISTEN     0      128                    :::22                                 :::*
LISTEN     0      100                   ::1:25                                 :::*
LISTEN     0      128                   ::1:6080                               :::*
LISTEN     0      128                   ::1:8000                               :::*
[root@soap ~]# 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
[root@soap ~]# systemctl restart supervisord.service
[root@soap ~]# systemctl enable supervisord.service
Created symlink from /etc/systemd/system/multi-user.target.wants/supervisord.service to /usr/lib/systemd/system/supervisord.service.
[root@soap ~]# su - nginx -s /bin/bash
-bash-4.2$ ssh-keygen
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:vRo3Yn6D7K6C6xMqiOb1Hx9Zj4T8rjTaZrWFgM2BIJY nginx@soap
The key's randomart image is:
+---[RSA 2048]----+
|   o... .        |
|  .E.  . .       |
|        + .      |
|       ..=.      |
|        Sooo.    |
|  .       =+o.   |
|o. +   o+*=oo.   |
|=.+ o  oOB*o     |
|+ooo oo*B=.o     |
+----[SHA256]-----+
-bash-4.2$ touch ~/.ssh/config
-bash-4.2$ echo -e "StrictHostKeyChecking=no\nUserKnownHostsFile=/dev/null" >> ~/.ssh/config
-bash-4.2$ chmod 0600 ~/.ssh/config
-bash-4.2$ ssh-copy-id -i ~/.ssh/id_rsa.pub root@192.168.142.136
/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.142.136' (ECDSA) to the list of known hosts.
root@192.168.142.136's password:

Number of key(s) added: 1

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

-bash-4.2$ ssh root@192.168.142.136
Warning: Permanently added '192.168.142.136' (ECDSA) to the list of known hosts.
Last login: Fri Sep 30 08:23:06 2022 from 192.168.142.136
[root@soap ~]#
[root@soap ~]# vim /etc/polkit-1/localauthority/50-local.d/50-libvirt-remote-access.pkla
[root@soap ~]# 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@soap ~]# chown -R root.root /etc/polkit-1/localauthority/50-local.d/50-libvirt-remote-access.pkla
[root@soap ~]# ll /etc/polkit-1/localauthority/50-local.d/50-libvirt-remote-access.pkla
-rw-r--r-- 1 root root 133 Sep 30 08:39 /etc/polkit-1/localauthority/50-local.d/50-libvirt-remote-access.pkla
[root@soap ~]# systemctl restart nginx
[root@soap ~]# systemctl restart libvirtd
[root@soap ~]# vim /etc/nginx/nginx.conf
user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;
worker_rlimit_nofile 655350;   //添加此行
[root@soap ~]# vim /etc/security/limits.conf
//在文件最末尾写入
* soft nofile 655350
* hard nofile 655350
[root@soap ~]# sysctl -p
[root@soap ~]# systemctl restart nginx
[root@soap]# yum -y install novnc
[root@soap]# chmod +x /etc/rc.d/rc.local
[root@soap]# vim /etc/rc.d/rc.local
//在最末尾加入如下行
nohup novnc_server 192.168.100.100:5920 &
[root@soap ~]# . /etc/rc.d/rc.local

posted @   姜翎  阅读(329)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
点击右上角即可分享
微信分享提示