虚拟化:在一台计算机上虚拟出多个逻辑的计算机,而且每个逻辑计算机
它可以是不同操作系统
通俗来讲:就是在我们已经部署好的虚拟机中,为了节省服务器资源空间的利用,而进行的虚套虚模式,进行多台互访完成构建。
虚拟化技术:可以扩大硬件容量,单个cpu模拟出多个cpu并行,
允许一个平台上同时运行多个操作系统,应用程序都可以在相互独立的空间内运行,而且互不影响。
为什么企业使用虚拟化技术
1、节约成本
2、提高效率物理机我们一般称为宿主机(Host),宿主机上面的虚拟机称为客户机(Guest)。
那么 Host 是如何将自己的硬件资源虚拟化,并提供给 Guest 使用的呢?
这个主要是通过一个叫做 Hypervisor 的程序实现的。
Hypervisor:一种运行在物理服务器硬件与操作系统之间的中间软件层
可允许多个操作系统和应用来共享硬件资源
根据 Hypervisor 的实现方式和所处的位置,虚拟化又分为两种:
完全虚拟化:直接在物理机上部署虚拟化,且不需要修改操作系统内核
半虚拟化:需要修改操作系统内核,使其支持虚拟化驱动来实现虚拟化技术
1、完全虚拟化
Hypervisor 直接安装在物理机上,多个虚拟机在 Hypervisor 上运行。Hypervisor 实现方式一般是一个特殊定制的 Linux 系统。Xen 和 VMWare 的 ESXi 都属于这个类型
2、半虚拟化
理论上讲:
完全虚拟化一般对硬件虚拟化功能进行了特别优化,性能上比半虚拟化要高;
半虚拟化因为基于普通的操作系统,会比较灵活,比如支持虚拟机嵌套。嵌套意味着可以在KVM虚拟机中再运行KVM。
kVM 全称是 Kernel-Based Virtual Machine。也就是说 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
1、libvirtd是服务程序,接收和处理 API 请求;
2、API 库使得其他人可以开发基于 Libvirt 的高级工具,比如 virt-manager,这是个图形化的 KVM 管理工具;
3、virsh 是我们经常要用的 KVM 命令行工具
环境说明:
系统:CentOS7
IP:192.168.47.146
1、CPU虚拟化功能
部署前请确保你的CPU虚拟化功能已开启,分为两种情况:
(1)虚拟机要关机设置CPU虚拟化
(2)物理机要在BIOS里开启CPU虚拟化
2、虚拟机设置(内存:8G 磁盘:200G 虚拟化功能:开启)
//设置虚拟机内存,添加一块200G的硬盘,开启虚拟化
//新建分区,将硬盘所有大小都给这个分区
[root@kvm ~]# lsblk
NAME MAJ:MIN RM SIZE RO TYPE MOUNTPOINT
sda 8:0 0 300G 0 disk
├─sda1 8:1 0 1G 0 part /boot
└─sda2 8:2 0 299G 0 part
├─centos-root 253:0 0 50G 0 lvm /
├─centos-swap 253:1 0 7.9G 0 lvm [SWAP]
└─centos-home 253:2 0 241.1G 0 lvm /home
sdb 8:16 0 200G 0 disk //刚添加的200G内存
print:列出当前磁盘的分区。
mkpart:创建分区命令,后面不需要参数,全部靠交互指定
//使用parted
[root@kvm ~]# parted /dev/sdb
GNU Parted 3.1
Using /dev/sdb
Welcome to GNU Parted! Type 'help' to view a list of commands.
(parted)
align-check mklabel(分区类型) print resizepart toggle
disk_set mkpart quit rm unit
disk_toggle mktable rescue select version
help name resize set
(parted) print
Error: /dev/sdb: unrecognised disk label
Model: VMware, VMware Virtual S (scsi)
Disk /dev/sdb: 215GB
Sector size (logical/physical): 512B/512B
Partition Table: unknown //此时分区表中没有磁盘的类型,需要我们添加类型
Disk Flags:
New disk label type? **msdos**
(parted) p
Model: VMware, VMware Virtual S (scsi)
Disk /dev/sdb: 215GB
Sector size (logical/physical): 512B/512B
Partition Table: msdos //添加成功
Disk Flags:
Number Start End Size Type File system Flags
添加以单元为字节
(parted) **unit**
Unit? [compact]?
% chs cyl GiB kiB MiB TB
B compact GB kB MB s TiB
Unit? [compact]? **mib** //选择mib单位
(parted)
align-check mklabel print resizepart toggle
disk_set mkpart quit rm unit
disk_toggle mktable rescue select version
help name resize set
(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?
Partition type? primary/extended? **primary** //主分区
File system type? [ext2]? xfs //文件类型
Start? 10MiB //起始大小
End? 204790MiB //结束大小
(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 204790MiB 204780MiB primary
(parted) q
Information: You may need to update /etc/fstab.
[root@kvm ~]# udevadm settle //保存系统同步
//格式化,挂载
[root@kvm ~]# mkfs.xfs /dev/sdb1
meta-data=/dev/sdb1 isize=512 agcount=4, agsize=13105920 blks
= sectsz=512 attr=2, projid32bit=1
= crc=1 finobt=0, sparse=0
data = bsize=4096 blocks=52423680, imaxpct=25
= sunit=0 swidth=0 blks
naming =version 2 bsize=4096 ascii-ci=0 ftype=1
log =internal log bsize=4096 blocks=25597, version=2
= sectsz=512 sunit=0 blks, lazy-count=1
realtime =none extsz=4096 blocks=0, rtextents=0
[root@kvm ~]# blkid /dev/sdb1
/dev/sdb1: UUID="574dc791-8097-47cd-a354-7306c502975c" TYPE="xfs"
[root@kvm ~]# mkdir /kvmdata
[root@kvm ~]# vi
vi view vigr vipw virt-what visudo
[root@kvm ~]# vi /etc/fstab
[root@kvm ~]# tail -1 /etc/fstab
UUID="574dc791-8097-47cd-a354-7306c502975c" /kvmdata xfs defaults 0 0
[root@kvm ~]# mount -a
[root@kvm ~]# df -hT | grep /kvmdata
/dev/sdb1 xfs 200G 33M 200G 1% /kvmdata
磁盘部署完成,部署KVM准备工作
关闭防火墙和selinux
[root@cy ~]# systemctl stop firewalld
[root@cy ~]# systemctl disable firewalld
[root@cy ~]# cat /etc/sysconfig/selinux
SELINUX=disabled
[root@cy ~]# reboot
[root@kvm yum.repos.d]# curl -o /etc/yum.repos.d/CentOS-Base.repo https://mirrors.aliyun.com/repo/Centos-7.repo
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
100 2523 100 2523 0 0 3424 0 --:--:-- --:--:-- --:--:-- 3423
[root@kvm yum.repos.d]# ls
CentOS-Base.repo
安装相应软件包
[root@kvm ~]# yum -y install epel-release vim wget net-tools unzip zip gcc gcc-c++
//验证cpu是否支持kvm,vmx是intel的 svm是AMD的
[root@kvm ~]# egrep -o 'vmx|svm' /proc/cpuinfo //过滤出支持以AMD真实机的CPU
svm
svm
svm
svm
安装kvm软件包
[root@kvm ~]# 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 network-scripts]# nmcli con show
NAME UUID TYPE DEVICE
ens33 a0518646-31f9-4e85-9254-38ade0571a71 ethernet ens33
[root@kvm network-scripts]# cp ifcfg-ens33 ifcfg-br0
[root@kvm network-scripts]# ls
ifcfg-br0
ifcfg-ens33
[root@kvm network-scripts]# cat ifcfg-br0
TYPE=Bridge
BOOTPROTO=none
NAME=br0
DEVICE=br0
ONBOOT="yes"
IPADDR=192.168.47.146
PREFIX=24
GATEWAY=192.168.47.254
DNS1=8.8.8.8
[root@kvm network-scripts]# cat ifcfg-ens33
TYPE=Ethernet
BOOTPROTO=none
NAME="ens33"
DEVICE="ens33"
ONBOOT="yes"
BRIDGE=br0 //主机网卡指定br的桥接模式
重启网卡服务
[root@kvm network-scripts]# systemctl restart NetworkManager
[root@kvm network-scripts]# nmcli con up br0
Connection successfully activated (master waiting for slaves) (D-Bus active path: /org/freedesktop/NetworkManager/ActiveConnection/3)
[root@kvm network-scripts]# ifdown ens33 ; ifup ens33
Device 'ens33' successfully disconnected.
Connection successfully activated (D-Bus active path: /org/freedesktop/NetworkManager/ActiveConnection/4)
[root@kvm network-scripts]# ip a
2: ens33: mtu 1500 qdisc pfifo_fast master br0 state UP group default qlen 1000
link/ether 00:0c:29:d7:72:f3 brd ff:ff:ff:ff:ff:ff
3: br0: mtu 1500 qdisc noqueue state UP group default qlen 1000
link/ether 00:0c:29:d7:72:f3 brd ff:ff:ff:ff:ff:ff
inet 192.168.47.146/24 brd 192.168.47.255 scope global noprefixroute br0
valid_lft forever preferred_lft forever
inet6 fe80::20c:29ff:fed7:72f3/64 scope link
valid_lft forever preferred_lft forever
重启libvirtd服务,并设置下次启动生效
[root@kvm network-scripts]# systemctl restart libvirtd
[root@kvm network-scripts]# systemctl enable libvirtd
[root@kvm network-scripts]# lsmod | grep kvm
kvm_amd 2176426 0
kvm 578518 1 kvm_amd
irqbypass 13503 1 kvm
验证安装结果
[root@kvm ~]# virsh --version
4.5.0
[root@kvm ~]# virt-install --version
1.5.0
将qemu-kvm这个命令做一个软链接到/usr/bin/qemu-kvm
[root@kvm ~]# ln -s /usr/libexec/qemu-kvm /usr/bin/qemu-kvm
[root@kvm ~]# ll /usr/bin/qemu-kvm
lrwxrwxrwx 1 root root 21 Oct 1 11:49 /usr/bin/qemu-kvm -> /usr/libexec/qemu-kvm
查看网桥信息
[root@kvm ~]# brctl show
bridge name bridge id STP enabled interfaces
br0 8000.000c29d772f3 no ens33 //已通信
virbr0 8000.525400d46a65 yes virbr0-nic
这时我们kvm基本信息配置坏了,但需要通过web界面进行管理
Kvm的web界面是由webvirtmgr程序提供的
//安装依赖包
通过用git拉取环境,并部署nginx战点
[root@kvm ~]# yum -y install git python-pip libvirt-python libxml2-python python-websockify supervisor nginx python-devel
//从github上下载webvirtmgr代码
当写KVM时遇见HTTP code = 301报错:
[root@kvm src]# git clone http://github.com/retspen/webvirtmgr.git
Cloning into 'webvirtmgr'...
error: RPC failed; result=35, HTTP code = 301
fatal: The remote end hung up unexpectedly
解决:
1、确认虚拟机防火墙是否完全关闭
2、由于次网站是外网,一般公司路由和家庭路由对其网站做了访问规则,只需切换自己手机热点测试访问网页,在完成第三步即可
3、在web上使用浏览器访问测试 http://github.com/retspen/webvirtmgr.git该网站,
如访问被拒绝则修改浏览器DNS解析
//成功
[root@kvm src]# git clone http://github.com/retspen/webvirtmgr.git
Cloning into 'webvirtmgr'...
remote: Enumerating objects: 5614, done.
remote: Total 5614 (delta 0), reused 0 (delta 0), pack-reused 5614
Receiving objects: 100% (5614/5614), 2.97 MiB | 1.87 MiB/s, done.
Resolving deltas: 100% (3606/3606), done.
**安装webvirtmgr**
[root@kvm webvirtmgr]# pip install -r requirements.txt
....下载忽略不计
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 22.2.2 is available.
You should consider upgrading via the 'pip install --upgrade pip' command.
/检查sqlite3是否安装
[root@kvm 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
Use exit() or Ctrl-D (i.e. EOF) to exit
>>> exit()
//初始化账号信息
[root@kvm webvirtmgr]# python manage.py syncdb
.....忽略不计
Would you like to create one now? (yes/no): yes //是否创建超级管理员账号
Username (leave blank to use 'root'): //默认为root
Email address: [email protected] //自定义邮箱
Password: //输入密码
Password (again):
Superuser created successfully.
Installing custom SQL ...
Installing indexes ...
Installed 6 object(s) from 1 fixture(s)
//拷贝web网页到nginx指定目录,以便web识别
[root@kvm webvirtmgr]# mkdir /var/www
[root@kvm webvirtmgr]# cp -r /usr/local/src/webvirtmgr/ /var/www/
[root@kvm webvirtmgr]# chown -R nginx.nginx /var/www/webvirtmgr/
[root@kvm webvirtmgr]# ll /var/www/
total 4
drwxr-xr-x 20 nginx nginx 4096 Oct 1 12:47 webvirtmgr
//生成一对公钥与私钥,由于这里webvirtmgr和kvm服务部署在同一台主机中,所以这里本地信任只需传输给自己。如果kvm部署在其他机器上的时候,那么就需要把公钥发送到kvm主机中
[root@kvm webvirtmgr]# ssh-keygen
+---[RSA 2048]----+
|.*=++ . |
|*oEB . + |
|=.= = . + |
|oo + + |
|o.. o . S |
|o= o o o |
|*+o.o |
|*=o . |
|X==o |
+----[SHA256]-----+
[root@kvm webvirtmgr]# ssh-copy-id -i ~/.ssh/id_rsa.pub [email protected]
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
[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.
//配置端口转发
[root@kvm webvirtmgr]# ssh 192.168.47.146 -L localhost:8000:localhost:8000 -L localhost:6080:localhost:60
Last login: Sat Oct 1 11:46:25 2022 from 192.168.47.1
[root@kvm ~]# ss -antl
State Recv-Q Send-Q Local Address:Port Peer Address:Port
LISTEN 0 128 127.0.0.1:6080 *:*
LISTEN 0 128 127.0.0.1:8000 *:*
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:6010 *:*
LISTEN 0 128 ::1:6080 :::*
LISTEN 0 128 ::1:8000 :::*
LISTEN 0 128 :::111 :::*
LISTEN 0 128 :::22 :::*
LISTEN 0 100 ::1:25 :::*
LISTEN 0 128 ::1:6010 :::*
//配置nginx
做一个备份
[root@kvm ~]# cp /etc/nginx/nginx.conf /etc/nginx/nginx.conf.bak
//在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@kvm ~]# vim /etc/nginx/nginx.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@kvm ~]# vim /var/www/webvirtmgr/conf/gunicorn.conf.py
//省略多行
bind = '127.0.0.1:8000' //确保此处绑定的是本机的8000端口,这个在nginx配置中定义了,被代理的端口
backlog = 2048
[root@kvm ~]# systemctl restart nginx
[root@kvm ~]# ss -antl
State Recv-Q Send-Q Local Address:Port Peer Address:Port
LISTEN 0 128 127.0.0.1:6080 *:*
LISTEN 0 128 127.0.0.1:8000 *:*
[root@kvm ~]# systemctl enable nginx
Created symlink from /etc/systemd/system/multi-user.target.wants/nginx.service to /usr/lib/systemd/system/nginx.service.
//设置supervisor
[root@kvm ~]# 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@kvm ~]# systemctl restart supervisord.service
[root@kvm ~]# systemctl enable supervisord.service
Created symlink from /etc/systemd/system/multi-user.target.wants/supervisord.service to /usr/lib/systemd/system/supervisord.service.
//配置nginx用户访问信息
[root@kvm ~]# su - nginx -s /bin/bash
-bash-4.2$ ssh-keygen
SHA256:sf2520utVBRZTqduWaWXmQPQuyfBsLHJAS0lF/CyBoI nginx@kvm
The key's randomart image is:
+---[RSA 2048]----+
| +==+. .B|
| . .+= ..*B|
| E . ...o.O +==|
| . .+o= = =.|
| So. * .|
| . . = + |
| o = .|
| = . |
| 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 [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.47.146' (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$ ssh [email protected]
Warning: Permanently added '192.168.47.146' (ECDSA) to the list of known hosts.
Last login: Sat Oct 1 12:54:12 2022 from kvm
[root@kvm ~]# exit
logout
Connection to 192.168.47.146 closed.
-bash-4.2$ exit
logout
//设置ssh连接信息
[root@kvm ~]# 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 ~]# chown -R root.root /etc/polkit-1/localauthority/50-local.d/50-libvirt-remote-access.pkla
[root@kvm ~]# systemctl restart nginx
[root@kvm ~]# systemctl restart libvirtd
1、使用浏览器访问192.168.100.100,服务器出现了accept:Too many open files
关闭页面在开一台
解决方法:
//修改nginx配置文件
[root@kvm ~]# 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@kvm ~]# vim /etc/security/limits.conf
//在文件最末尾写入
* soft nofile 655350
* hard nofile 655350
//重启服务,重读文件
[root@kvm ~]# sysctl -p
[root@kvm ~]# systemctl restart nginx
2、上传镜像,使用xftp或者xshell,再或者其他工具,将镜像文件上传到服务器的/kvmdata目录下存放
[root@kvm kvmdata]# ls
rhel-8.3-x86_64-dvd.iso
//实例管理,现在去创建一个虚拟机
3、如果出现了连接超时,则做如下步骤,如果没有出现,则不管
解决方法:
//安装novnc,并通过novnc_server启动一个vnc
[root@cy ~]# yum -y install novnc
[root@kvm ~]# chmod +x /etc/rc.d/rc.local
[root@kvm ~]# vim /etc/rc.d/rc.local
//在最末尾加入如下行
nohup novnc_server 192.168.47.146:5920 &
[root@kvm ~]# . /etc/rc.d/rc.local
[root@kvm ~]# nohup: ignoring input and appending output to ‘nohup.out’