KVM虚拟化
虚拟化介绍
虚拟化是云计算的基础。简单的说,虚拟化使得在一台物理的服务器上可以跑多台虚拟机,虚拟机共享物理机的 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。
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 命令行工具
kvm部署
环境说明:
主机名 | IP | 系统 |
localhost | 192.168.100.20 | redhat8 |
部署前请确保你的CPU虚拟化功能已开启。分为两种情况:
- 虚拟机要关机设置CPU虚拟化
- 物理机要在BIOS里开启CPU虚拟化
//关闭防火墙与SELINUX [root@localhost~]# systemctl disable --now firewalld [root@localhost~]# sed -ri 's/^(SELINUX=).*/\1disabled/g' /etc/selinux/config [root@localhost~]# setenforce 0 //验证CPU是否支持KVM;如果结果中有vmx(Intel)或svm(AMD)字样,就说明CPU的支持的 [root@localhost~]# egrep -o 'vmx|svm' /proc/cpuinfo vmx //搭建yum [root@localhostyum.repos.d]# curl -o /etc/yum.repos.d/CentOS7-Base-163.repo http://mirrors.163.com/.help/CentOS7-Base-163.repo [root@localhost~]# sed -i 's/\$releasever/7/g' /etc/yum.repos.d/CentOS7-Base-163.repo [root@localhost~]# sed -i 's/^enabled=.*/enabled=1/g' /etc/yum.repos.d/CentOS7-Base-163.repo [root@localhost~]# yum -y install epel-release vim wget net-tools unzip zip gcc gcc-c++ [root@localhost~]# yum -y install qemu-localhostqemu-kvm-common qemu-img virt-manager libvirt python3-libvirt libvirt-client virt-install virt-viewer bridge-utils libguestfs-tools //将kvm服务器网卡设置为桥接模式,使其与当前机器处于同一网段 //此处我的网卡是ens160,所以用br0来桥接ens160网卡 [root@localhost~]# cp /etc/sysconfig/network-scripts/ifcfg-ens160 /etc/sysconfig/network-scripts/ifcfg-br0 [root@localhostnetwork-scripts]# vim ifcfg-br0 TYPE=Bridge DEVICE=br0 BOOTPROTO=static NAME=br0 ONBOOT=yes IPADDR=192.168.100.20 PREFIX=24 GATEWAY=192.168.100.254 DNS1=114.114.114.114 DNS2=8.8.8.8 [root@localhost network-scripts]# vim ifcfg-ens160 TYPE=Ethernet BOOTPROTO=static ONBOOT=yes NAME=ens160 DEVICE=ens160 BRIDGE=br0 NM_CONTROLLED=no //重启网络 [root@localhost~]# systemctl restart NetworkManager [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:f9:ec:35 brd ff:ff:ff:ff:ff:ff 4: br0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP group default qlen 1000 link/ether 00:0c:29:f9:ec:35 brd ff:ff:ff:ff:ff:ff inet 192.168.100.20/24 brd 192.168.100.255 scope global noprefixroute br0 valid_lft forever preferred_lft forever inet6 fe80::20c:29ff:fef9:ec35/64 scope link valid_lft forever preferred_lft forever //启动服务 [root@localhost~]# systemctl enable --now libvirtd //验证安装结果 [root@localhost~]# lsmod|grep kvm kvm_intel 188740 0 localhost 637289 1 kvm_intel irqbypass 13503 1 kvm //测试并验证安装结果 [root@localhost~]# virsh -c qemu:///system list Id Name State -------------------- [root@localhost~]# virsh --version 4.5.0 [root@localhost~]# virt-install --version 1.5.0 [root@localhost~]# ln -s /usr/libexec/qemu-localhost/usr/bin/qemu-kvm [root@localhost~]# ll /usr/bin/qemu-kvm lrwxrwxrwx. 1 root root 21 May 19 16:49 /usr/bin/qemu-localhost-> /usr/libexec/qemu-kvm //查看网桥信息 [root@localhost~]# brctl show bridge name bridge id STP enabled interfaces br0 8000.000c29f9ec35 no ens160 virbr0 8000.52540004c5dd yes virbr0-nic
kvm web管理界面安装
kvm的web管理界面是由 webvirtmgr 程序提供的
//安装依赖包 [root@localhost ~]# yum -y install git python-pip libvirt-python libxml2-python python-websockify supervisor nginx python-devel //从github上下载webvirtmgr代码 [root@localhost src]# cd /usr/local/src/ [root@localhost src]# git clone git://github.com/retspen/webvirtmgr.git //安装webvirtmgr [root@localhost src]# cd webvirtmgr/ [root@localhost webvirtmgr]# pip install -r requirements.txt //检查sqlite3是否安装 [root@localhost 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@localhost 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'): //指定超级管理员帐号用户名,默认留空为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@localhost webvirtmgr]# mkdir /var/www [root@localhost webvirtmgr]# cp -r /usr/local/src/webvirtmgr /var/www/ [root@localhost webvirtmgr]# chown -R nginx.nginx /var/www/webvirtmgr/ //生成密钥 [root@localhost ~]# ssh-keygen -t rsa 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:Ib8cqf0pRIEUIY5KHXZF+s1QMPL/xtMnw/Q/4unV5/A root@localhost The key's randomart image is: +---[RSA 2048]----+ | o.+*O.. | | ooo.= + | | ......o.. | |.. .o*o | |. oS+ . | | +.oo + . .| | ..+ = =.+o| | ......*=o| | .o o+. E| +----[SHA256]-----+ //由于这里webvirtmgr和localhost服务部署在同一台机器,所以这里本地信任。如果localhost部署在其他机器,那么下面应该修改为它的ip [root@localhost ~]# ssh-copy-id 192.168.100.20 /usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/root/.ssh/id_rsa.pub" The authenticity of host '192.168.100.20 (192.168.100.20)' can't be established. ECDSA key fingerprint is SHA256:PBvp8WcEc84ov5UnkhgFk9nx38WO3/92neCocTzh6dI. ECDSA key fingerprint is MD5:85:b6:72:78:46:11:53:0d:fc:de:b0:e7:10:88:ba:2a. 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.100.20's password: Number of key(s) added: 1 Now try logging into the machine, with: "ssh '192.168.100.20'" and check to make sure that only the key(s) you wanted were added. //配置端口转发 [root@localhost ~]# ssh 192.168.100.20 -L localhost:8000:localhost:8000 -L localhost:6080:localhost:60 Last login: Sat May 22 12:06:26 2021 from 192.168.100.250 [root@localhost ~]# 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:6010 *:* LISTEN 0 128 127.0.0.1:6011 *:* 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]:6010 [::]:* LISTEN 0 128 [::1]:6011 [::]:* LISTEN 0 128 [::1]:6080 [::]:* LISTEN 0 128 [::1]:8000 [::]:* //配置nginx [root@localhost ~]# vi /etc/nginx/nginx.conf user nginx; worker_processes auto; error_log /var/log/nginx/error.log; pid /run/nginx.pid; include /usr/share/nginx/modules/*.conf; events { worker_connections 1024; } http { log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"'; access_log /var/log/nginx/access.log main; sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 65; types_hash_max_size 2048; include /etc/nginx/mime.types; default_type application/octet-stream; include /etc/nginx/conf.d/*.conf; server { listen 80; server_name localhost; include /etc/nginx/default.d/*.conf; location / { root html; index index.html index.htm; } error_page 404 /404.html; location = /40x.html { } error_page 500 502 503 504 /50x.html; location = /50x.html { } } } [root@localhost ~]# vi /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 ~]# vi /var/www/webvirtmgr/conf/gunicorn.conf.py bind = '0.0.0.0:8000' //确保此处绑定的是本机的8000端口,这个在nginx配置中定义了,被代理的端口 backlog = 2048 //重启nginx [root@localhost ~]# systemctl restart nginx [root@localhost ~]# 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:6010 *:* LISTEN 0 128 127.0.0.1:6011 *:* 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]:6010 [::]:* LISTEN 0 128 [::1]:6011 [::]:* LISTEN 0 128 [::1]:6080 [::]:* LISTEN 0 128 [::1]:8000 [::]:* //设置supervisor [root@localhost ~]# vi /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@localhost ~]# systemctl enable --now supervisord Created symlink from /etc/systemd/system/multi-user.target.wants/supervisord.service to /usr/lib/systemd/system/supervisord.service. //配置nginx用户 [root@localhost ~]# 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:kxON1W6vknnxk4kC6LIIoq+Eu0x5em+fY9LmWsse1U0 nginx@localhost The key's randomart image is: +---[RSA 2048]----+ | .. | | + . | | o .. E | | o. = | | .S. o o | |. . . oo . . | |++ . ..o . o = o | |*ooo.o+=+ = + = | |=*+ +=OB. + . | +----[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.100.20 /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.100.20' (ECDSA) to the list of known hosts. root@192.168.100.20's password: Number of key(s) added: 1 Now try logging into the machine, with: "ssh 'root@192.168.100.20'" and check to make sure that only the key(s) you wanted were added. -bash-4.2$ exit [root@localhost ~]# vi /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 ~]# chown -R root.root /etc/polkit-1/localauthority/50-local.d/50-libvirt-remote-access.pkla [root@localhost ~]# systemctl restart nginx [root@localhost ~]# systemctl restart libvirtd
kvm web界面管理
在浏览器上输入192.168.100.1/login
此时会发现访问不了,且命令行报错 too many open files
解决方法:
[root@localhost ~]# 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; //添加此行配置 # Load dynamic modules. See /usr/share/nginx/README.dynamic. [root@localhost ~]# systemctl restart nginx [root@localhost ~]# systemctl enable --now nginx [root@localhost ~]# vim /etc/security/limits.conf # End of file * soft nofile 655350 * hard nofile 655350
此时再访问就可以成功
kvm web界面管理
没配置用户名的话默认用户名是root,密码是123456(密码是你初始化帐号信息的时候设置的)
做完上面步骤后需要给虚拟机添加一个磁盘,用来安装系统(此步骤需要在虚拟机关机的状态下进行)
磁盘分区格式化
[root@localhost ~]# fdisk /dev/sdb 命令(输入 m 获取帮助):n Partition type: p primary (0 primary, 0 extended, 4 free) e extended Select (default p): Using default response p 分区号 (1-4,默认 1): 起始 扇区 (2048-41943039,默认为 2048): 将使用默认值 2048 Last 扇区, +扇区 or +size{K,M,G} (2048-41943039,默认为 41943039): 将使用默认值 41943039 分区 1 已设置为 Linux 类型,大小设为 20 GiB 命令(输入 m 获取帮助):p 磁盘 /dev/sdb:21.5 GB, 21474836480 字节,41943040 个扇区 Units = 扇区 of 1 * 512 = 512 bytes 扇区大小(逻辑/物理):512 字节 / 512 字节 I/O 大小(最小/最佳):512 字节 / 512 字节 磁盘标签类型:dos 磁盘标识符:0x00391384 设备 Boot Start End Blocks Id System /dev/sdb1 2048 41943039 20970496 83 Linux 命令(输入 m 获取帮助):w The partition table has been altered! Calling ioctl() to re-read partition table. 正在同步磁盘。 //格式化并且挂载 [root@localhost ~]# partprobe [root@localhost ~]# mkfs.xfs /dev/sdb1 [root@localhost ~]# blkid /dev/sdb1 /dev/sdb1: UUID="e4acaf60-93e9-4ef7-85a9-830221ed5fbf" TYPE="xfs" [root@localhost images]# vim /etc/fstab #在文件最下方加入下面一行 UUID="e4acaf60-93e9-4ef7-85a9-830221ed5fbf" /kvmdata xfs defaults 0 0 [root@localhost ~]# mkdir /kvmdata [root@localhost ~]# mount -a
通过远程连接软件上传ISO镜像文件至存储,目录为刚才创建并挂载的 /kvmdata
[root@KVM ~]# ls /kvmdata/ rhel-8.0-x86_64-dvd.iso
kvm网络管理
实例(虚拟机)创建
虚拟机插入光盘
显示已断开就是连接上了
设置在 web 上访问虚拟机的密码
之后就是正常安装虚拟机系统的流程
注意:web界面配置完成后有时可能会报以下错误
解决方法是安装novnc并通过novnc_server启动一个vnc
[root@localhost ~]# yum -y install novnc [root@localhost ~]# ll /etc/rc.local lrwxrwxrwx. 1 root root 13 Aug 6 2018 /etc/rc.local -> rc.d/rc.local [root@localhost ~]# ll /etc/rc.d/rc.local -rw-r--r-- 1 root root 513 Mar 11 22:35 /etc/rc.d/rc.local [root@localhost ~]# chmod +x /etc/rc.d/rc.local [root@localhost ~]# ll /etc/rc.d/rc.local -rwxr-xr-x 1 root root 513 Mar 11 22:35 /etc/rc.d/rc.local [root@localhost ~]# vim /etc/rc.d/rc.local # that this script will be executed during boot. touch /var/lock/subsys/local nohup novnc_server 192.168.100.20:5920 & [root@localhost ~]# . /etc/rc.d/rc.local