虚拟化介绍
虚拟化:在一台计算机上虚拟出多个逻辑的计算机,而且每个逻辑计算机
它可以是不同操作系统
虚拟化技术:可以扩大硬件容量,单个cpu模拟出多个cpu并行,
允许一个平台上同时运行多个操作系统,应用程序都可以在相互独立
的空间内运行,而且互不影响。
为什么企业使用虚拟化技术
1、节约成本
2、提高效率物理机我们一般称为宿主机(Host),宿主机上面的虚拟机称为客户机(Guest)。
那么 Host 是如何将自己的硬件资源虚拟化,并提供给 Guest 使用的呢?
这个主要是通过一个叫做 Hypervisor 的程序实现的。
Hypervisor:一种运行在物理服务器硬件与操作系统之间的中间软件层
可允许多个操作系统和应用来共享硬件资源
根据 Hypervisor 的实现方式和所处的位置,虚拟化又分为两种:
完全虚拟化:直接在物理机上部署虚拟化,且不需要修改操作系统内核
半虚拟化:需要修改操作系统内核,使其支持虚拟化驱动来实现虚拟化技术
1、完全虚拟化
Hypervisor 直接安装在物理机上,多个虚拟机在 Hypervisor 上运行。Hypervisor 实现方式一般是一个特殊定制的 Linux 系统。Xen 和 VMWare 的 ESXi 都属于这个类型
2、半虚拟化
理论上讲:
完全虚拟化一般对硬件虚拟化功能进行了特别优化,性能上比半虚拟化要高;
半虚拟化因为基于普通的操作系统,会比较灵活,比如支持虚拟机嵌套。嵌套意味着可以在KVM虚拟机中再运行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 命令行工具
KVM部署
环境说明:
系统:CentOS 7
IP:192.168.40.111
CPU虚拟化功能
部署前请确保你的CPU虚拟化功能已开启,分为两种情况:
(1)虚拟机要关机设置CPU虚拟化
(2)物理机要在BIOS里开启CPU虚拟化
开启虚拟化
虚拟机设置(内存:8G 磁盘:200G 虚拟化功能:开启)
设置虚拟机内存,添加一块200G的硬盘
新建分区,将硬盘所有大小都给这个分区
[root@niuma ~]# parted /dev/sdb
GNU Parted 3.2
使用 /dev/sdb
Welcome to GNU Parted! Type 'help' to view a list of commands.
(parted) mklabel
新的磁盘标签类型?
aix amiga atari bsd dvh gpt loop mac msdos pc98 sun
新的磁盘标签类型? msdos
警告: The existing disk label on /dev/sdb will be destroyed and all data on this disk will be lost. Do
you want to continue?
是/Yes/否/No? yes
(parted)
align-check help mktable quit resizepart set version
disk_set mklabel name rescue rm toggle
disk_toggle mkpart print resize select unit
(parted) unit
Unit? [compact]?
% chs cyl GiB kiB MiB TB
B compact GB kB MB s TiB
Unit? [compact]? MiB
(parted)
align-check help mktable quit resizepart set version
disk_set mklabel name rescue rm toggle
disk_toggle mkpart print resize select unit
(parted) mkpart
分区类型? primary/主分区/extended/扩展分区? primary
文件系统类型? [ext2]? ext4
起始点? 1Mib
结束点? 204798MiB
(parted) q
信息: You may need to update /etc/fstab.
[root@niuma ~]# udevadm settle
格式化分区
[root@niuma ~]# mkfs.ext4 /dev/sdb1
mke2fs 1.45.6 (20-Mar-2020)
创建含有 52428032 个块(每块 4k)和 13107200 个inode的文件系统
文件系统UUID:8de9298f-388c-4833-9ffb-ef8cbf1daaf1
超级块的备份存储于下列块:
32768, 98304, 163840, 229376, 294912, 819200, 884736, 1605632, 2654208,
4096000, 7962624, 11239424, 20480000, 23887872
正在分配组表: 完成
正在写入inode表: 完成
创建日志(262144 个块)完成
写入超级块和文件系统账户统计信息: 已完成
[root@niuma ~]#
挂载
[root@niuma ~]# mkdir /KVM
[root@niuma ~]# vim /etc/fstab
[root@niuma ~]# mount -a
[root@niuma ~]# df -Th
文件系统 类型 容量 已用 可用 已用% 挂载点
devtmpfs devtmpfs 1.8G 0 1.8G 0% /dev
tmpfs tmpfs 1.9G 0 1.9G 0% /dev/shm
tmpfs tmpfs 1.9G 9.6M 1.8G 1% /run
tmpfs tmpfs 1.9G 0 1.9G 0% /sys/fs/cgroup
/dev/mapper/cs-root xfs 64G 5.0G 59G 8% /
/dev/mapper/cs-home xfs 32G 255M 31G 1% /home
/dev/sda1 xfs 1014M 255M 760M 26% /boot
tmpfs tmpfs 371M 12K 371M 1% /run/user/42
tmpfs tmpfs 371M 0 371M 0% /run/user/0
/dev/sdb1 ext4 196G 61M 186G 1% /KVM
KVM安装
关闭防火墙和selinux
[root@niuma ~]# systemctl stop firewalld.service
[root@niuma ~]# systemctl disable firewalld.service
Removed /etc/systemd/system/multi-user.target.wants/firewalld.service.
Removed /etc/systemd/system/dbus-org.fedoraproject.FirewallD1.service.
[root@niuma ~]# vim /etc/sysconfig/selinux
SELINUX=disabled
[root@niuma ~]# setenforce 0
[root@niuma ~]# getenforce
Disabled
配置yum源
[root@niuma ~]# cd /etc/yum.repos.d/
[root@niuma yum.repos.d]# rm -rf *
[root@niuma yum.repos.d]# curl -o /etc/yum.repos.d/CentOS-Base.repo https://mirrors.aliyun.com/repo/Centos-7.repo
安装所需软件包
[root@niuma ~]# yum -y install epel-release vim wget net-tools unzip zip gcc gcc-c++ --allowerasing
验证cpu是否支持kvm,vmx是intel的 svm是AMD的
[root@niuma ~]# egrep -o 'vmx|svm' /proc/cpuinfo
vmx
vmx
vmx
vmx
vmx
vmx
vmx
vmx
安装kvm
[root@niuma ~]# 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的网卡配置成桥接模式
TYPE=Bridge
BOOTPROTO=none
NAME=br0
DEVICE=br0
ONBOOT=yes
IPADDR=192.168.40.111
PREFIX=24
GATEWAY=192.168.100.254
DNS1=8.8.8.8
[root@niuma network-scripts]# cat ifcfg-ens33
TYPE=Ethernet
BOOTPROTO=none
NAME=ens33
DEVICE=ens33
ONBOOT=yes
BRIDGE=br0
[root@niuma network-scripts]#
重启网卡服务
重启libvirtd服务,并设置下次启动生效
[root@niuma ~]# systemctl restart libvirtd
[root@niuma ~]# systemctl enable libvirtd
查看kvm模块是否加载
root@niuma ~]# lsmod | grep kvm
kvm_intel 174841 0
kvm 578518 1 kvm_intel
irqbypass 13503 1 kvm
验证结果
[root@niuma ~]# virsh -c qemu:///system list
Id Name State
----------------------------------------------------
[root@niuma ~]# virsh --version
4.5.0
[root@niuma ~]# virt-install --version
1.5.0
将qemu-kvm这个命令做一个软链接到/usr/bin/qemu-kvm
[root@niuma ~]# ln -s /usr/libexec/qemu-kvm /usr/bin/qemu-kvm
[root@niuma ~]# ll /usr/bin/qemu-kvm
lrwxrwxrwx. 1 root root 21 Oct 1 07:41 /usr/bin/qemu-kvm -> /usr/libexec/qemu-kvm
[root@niuma ~]#
查看网桥信息
[root@niuma ~]# brctl show
bridge name bridge id STP enabled interfaces
br0 8000.000c2907e20c no ens33
virbr0 8000.525400c79725 yes virbr0-nic
KVM管理界面安装
Kvm的web界面是由webvirtmgr程序提供的
安装依赖包
[root@niuma ~]# yum -y install git python-pip libvirt-python libxml2-python python-websockify supervisor nginx python-devel
从github上下载webvirtmgr代码
如果下载不了,虚拟机浏览器也访问不了
解决方法
[root@niuma ~]# cd /usr/local/src/
[root@niuma src]# ls
[root@niuma src]# git clone http://github.com/retspen/webvirtmgr.git
正克隆到 'webvirtmgr'...
warning: 重定向到 https://github.com/retspen/webvirtmgr.git/
remote: Enumerating objects: 5614, done.
remote: Total 5614 (delta 0), reused 0 (delta 0), pack-reused 5614
接收对象中: 100% (5614/5614), 2.97 MiB | 1.43 MiB/s, 完成.
处理 delta 中: 100% (3606/3606), 完成.
[root@niuma src]# ls
webvirtmgr
安装webvirtmgr
[root@RS1 webvirtmgr]# pip install -r requirements.txt
WARNING: Running pip install with root privileges is generally not a good idea. Try `pip3 install --user` instead.
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 22kB/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 21kB/s
Collecting lockfile>=0.9 (from -r requirements.txt (line 5))
Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.VerifiedHTTPSConnection object at 0x7fdb74194e48>: Failed to establish a new connection: [Errno 101] 网络不可达',)': /simple/lockfile/
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
##如果上面报错就用下面的
[root@localhost webvirtmgr]# pip install -i https://pypi.douban.com/simple -r requirements.txt
检查sqlite3是否安装
[root@niuma ~]# 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@niuma ~]#
初始化账号信息
[root@niuma webvirtmgr]# cd /usr/local/src/webvirtmgr/
[root@niuma webvirtmgr]# python manage.py syncdb
[root@niuma 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: hehe@example.com //设置超级管理员邮箱
Password: //设置超级管理员密码此处我设置为1也可以
Password (again): //再次输入确认超级管理员密码
Superuser created successfully.
Installing custom SQL ...
Installing indexes ...
Installed 6 object(s) from 1 fixture(s)
[root@niuma webvirtmgr]#
拷贝web网页到指定目录
[root@niuma webvirtmgr]# cp -r /usr/local/src/webvirtmgr/ /var/www/
[root@niuma webvirtmgr]# chown -R nginx.nginx /var/www/webvirtmgr/
[root@niuma webvirtmgr]#
生成一对公钥与私钥,由于这里webvirtmgr和kvm服务部署在同一台主机中,所以这里本地信任。如果kvm部署在其他机器上的时候,那么就需要把公钥发送到kvm主机中
[root@niuma webvirtmgr]# ssh-keygen
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:YPiqRP1r+C/9lijD3Hmwp3Jci5rFxfMUfKGyLLRBjw4 root@niuma
The key's randomart image is:
+---[RSA 3072]----+
| . . |
| . . o . . . |
| . E + o + . |
| . o = = o o |
| . . . S * . |
| . o ..o.+ |
| . .+.+oB o. |
| . .. O+X * |
| . o=Oo*. |
+----[SHA256]-----+
[root@niuma webvirtmgr]# ssh-copy-id -i ~/.ssh/id_rsa.pub root@192.168.40.111
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/root/.ssh/id_rsa.pub"
The authenticity of host '192.168.40.111 (192.168.40.111)' can't be established.
ECDSA key fingerprint is SHA256:CpwzTyA+TDEgnsVkB3eHsGG+klmfSTzcJXmbNJpj5pY.
Are you sure you want to continue connecting (yes/no/[fingerprint])? 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.40.111's password:
Number of key(s) added: 1
Now try logging into the machine, with: "ssh 'root@192.168.40.111'"
and check to make sure that only the key(s) you wanted were added.
[root@niuma webvirtmgr]#
配置端口转发
[root@niuma webvirtmgr]# ssh 192.168.40.111 -L localhost:8000:localhost:8000 -L localhost:6080:localhost:60
Activate the web console with: systemctl enable --now cockpit.socket
Last login: Sat Oct 1 12:21:25 2022 from 192.168.40.1
[root@niuma ~]# ss -antlp
State Recv-Q Send-Q Local Address:Port Peer Address:Port Process
LISTEN 0 128 127.0.0.1:6080 0.0.0.0:* users:(("ssh",pid=6718,fd=9))
LISTEN 0 128 127.0.0.1:8000 0.0.0.0:* users:(("ssh",pid=6718,fd=7))
LISTEN 0 128 0.0.0.0:111 0.0.0.0:* users:(("rpcbind",pid=917,fd=4),("systemd",pid=1,fd=321))
LISTEN 0 32 192.168.122.1:53 0.0.0.0:* users:(("dnsmasq",pid=1992,fd=6))
LISTEN 0 128 0.0.0.0:22 0.0.0.0:* users:(("sshd",pid=1002,fd=4))
LISTEN 0 5 127.0.0.1:631 0.0.0.0:* users:(("cupsd",pid=1106,fd=10))
LISTEN 0 128 [::1]:6080 [::]:* users:(("ssh",pid=6718,fd=8))
LISTEN 0 128 [::1]:8000 [::]:*
配置nginx
[root@niuma ~]# cp /etc/nginx/nginx.conf /etc/nginx/nginx.conf.bak
[root@niuma ~]# 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;
}
配置nginx虚拟主机
[root@niuma ~]# 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;
}
}
确保bind绑定本机的8000端口
[root@niuma ~]# vim /var/www/webvirtmgr/conf/gunicorn.conf.py
//省略多行
bind = '127.0.0.1:8000' //确保此处绑定的是本机的8000端口,这个在nginx配置中定义了,被代理的端口
backlog = 2048
//省略多行
重启nginx服务,查看端口是否开启
[root@niuma ~]# systemctl restart nginx.service
[root@niuma ~]# systemctl enable nginx.service
Created symlink /etc/systemd/system/multi-user.target.wants/nginx.service → /usr/lib/systemd/system/nginx.service.
[root@niuma ~]#
设置supervisor
[root@niuma ~]# 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@niuma ~]# systemctl restart supervisord.service
[root@niuma ~]# systemctl enable supervisord.service
Created symlink /etc/systemd/system/multi-user.target.wants/supervisord.service → /usr/lib/systemd/system/supervisord.service.
[root@niuma ~]#
配置nginx用户
[root@niuma webvirtmgr]# 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:FFffKx6el+eoq/PyyBtAMW1ZfXn4+DcKQg/kmyKcJ2k nginx@rs1
The key's randomart image is:
+---[RSA 2048]----+
| +..+o. ..|
| *+ .ooo|
| =. .+o|
| o + . o|
| . o S = o o |
| E o = oo +.+|
| . + . o .+.o+|
| .oo ..o.|
| =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.40.111
/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.40.111' (ECDSA) to the list of known hosts.
root@192.168.40.111's password:
Number of key(s) added: 1
Now try logging into the machine, with: "ssh 'root@192.168.40.111'"
and check to make sure that only the key(s) you wanted were added.
验证基于密钥认证是否成功
-bash-4.2$ ssh root@192.168.40.111
Warning: Permanently added '192.168.40.111' (ECDSA) to the list of known hosts.
Last login: Fri Sep 30 23:20:39 2022 from rs1
[root@rs1 ~]# exit
登出
Connection to 192.168.40.111 closed.
-bash-4.2$ exit
登出
[root@niuma ~]# 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@niuma ~]# systemctl restart nginx.service
[root@niuma ~]# systemctl restart libvirtd
KVM web界面管理
使用浏览器访问192.168.40.111,服务器出现了accept:Too many open files
解决方法:
/修改nginx配置文件
[root@niuma ~]# 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@niuma ~]# vim /etc/security/limits.conf
//在文件最末尾写入
* soft nofile 655350
* hard nofile 655350
重启服务,重读文件
[root@niuma ~]# sysctl -p
[root@niuma ~]# systemctl restart nginx
再次使用浏览器访问
添加连接
创建虚拟机
新建存储
上传镜像,使用xftp或者xshell,再或者其他工具,将镜像文件上传到服务器的/KVM目录下存放
添加网络
实例管理,现在去创建一个虚拟机
自定义
创建
如果出现了连接超时,则做如下步骤,如果没有出现,则不管
解决方法
//安装novnc,并通过novnc_server启动一个vnc
[root@niuma ~]#yum -y install novnc
[root@niuma ~]#chmod +x /etc/rc.d/rc.local
[root@niuma ~]# vim /etc/rc.d/rc.local
//在最末尾加入如下行
nohup novnc_server 192.168.100.100:5920 &
[root@niuma ~]# . /etc/rc.d/rc.loca