虚拟化配置
1. 虚拟化介绍
虚拟化是云计算的基础。简单的说,虚拟化使得在一台物理的服务器上可以跑多台虚拟机,虚拟机共享物理机的 CPU、内存、IO 硬件资源,但逻辑上虚拟机之间是相互隔离的。
物理机我们一般称为宿主机(Host),宿主机上面的虚拟机称为客户机(Guest)。
那么 Host 是如何将自己的硬件资源虚拟化,并提供给 Guest 使用的呢?
这个主要是通过一个叫做 Hypervisor 的程序实现的。
根据 Hypervisor 的实现方式和所处的位置,虚拟化又分为两种:
- 全虚拟化
- 半虚拟化
全虚拟化:
Hypervisor 直接安装在物理机上,多个虚拟机在 Hypervisor 上运行。Hypervisor 实现方式一般是一个特殊定制的 Linux 系统。Xen 和 VMWare 的 ESXi 都属于这个类型
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 命令行工具
部署kvm
环境说明
主机名 | IP | 系统 |
---|---|---|
kvm | 192.168.174.168 | centos 8 |
首先先修改机器配置
- 内存尽量给大点,cpu虚拟化功能都勾选,虚拟计数器看情况勾选
[root@kvm ~]# lsblk
NAME MAJ:MIN RM SIZE RO TYPE MOUNTPOINT
sda 8:0 0 100G 0 disk
├─sda1 8:1 0 1G 0 part /boot
└─sda2 8:2 0 99G 0 part
├─cl_192-root 253:0 0 63.9G 0 lvm /
├─cl_192-swap 253:1 0 4G 0 lvm [SWAP]
└─cl_192-home 253:2 0 31.2G 0 lvm /home
sdb 8:16 0 200G 0 disk
sr0 11:0 1 10.1G 0 rom
[root@kvm ~]# parted /dev/sdb
GNU Parted 3.2
Using /dev/sdb
Welcome to GNU Parted! Type 'help' to view a list of commands.
(parted) mklabel
New disk label type? msdos
(parted) unit
Unit? [compact]? MiB
(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? primary
File system type? [ext2]? xfs
Start? 10
End? 204790
(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 xfs lba
(parted) q
Information: You may need to update /etc/fstab.
//刷新分区表
[root@kvm ~]# udevadm settle
[root@kvm ~]# lsblk
NAME MAJ:MIN RM SIZE RO TYPE MOUNTPOINT
sda 8:0 0 100G 0 disk
├─sda1 8:1 0 1G 0 part /boot
└─sda2 8:2 0 99G 0 part
├─cl_192-root 253:0 0 63.9G 0 lvm /
├─cl_192-swap 253:1 0 4G 0 lvm [SWAP]
└─cl_192-home 253:2 0 31.2G 0 lvm /home
sdb 8:16 0 200G 0 disk
└─sdb1 8:17 0 200G 0 part
sr0 11:0 1 10.1G 0 rom
//格式化并挂载
[root@kvm ~]# mkfs.xfs /dev/sdb1
[root@kvm ~]# blkid /dev/sdb1
/dev/sdb1: UUID="1114fa6d-a18e-43f2-9543-39d4ea0d88f7" BLOCK_SIZE="512" TYPE="xfs" PARTUUID="70fdc2c0-01"
[root@kvm ~]# mkdir /kvmdata
[root@kvm ~]# vim /etc/fstab
UUID="1114fa6d-a18e-43f2-9543-39d4ea0d88f7" /kvmdata xfs defaults 0 0
[root@kvm ~]# mount -a
[root@kvm ~]# df -Th
Filesystem Type Size Used Avail Use% Mounted on
devtmpfs devtmpfs 3.8G 0 3.8G 0% /dev
tmpfs tmpfs 3.8G 0 3.8G 0% /dev/shm
tmpfs tmpfs 3.8G 9.0M 3.8G 1% /run
tmpfs tmpfs 3.8G 0 3.8G 0% /sys/fs/cgroup
/dev/mapper/cl_192-root xfs 64G 2.0G 62G 4% /
/dev/mapper/cl_192-home xfs 32G 255M 31G 1% /home
/dev/sda1 xfs 1014M 214M 801M 22% /boot
tmpfs tmpfs 775M 0 775M 0% /run/user/0
/dev/sdb1 xfs 200G 1.5G 199G 1% /kvmdata
//关闭防火墙和selinux
[root@kvm ~]# setenforce 0
[root@kvm ~]# sed -ri 's/^(SELINUX=).*/\1disabled/g' /etc/selinux/config
[root@kvm ~]# systemctl disable --now firewalld.service
//配置yum源
[root@kvm ~]# curl -o /etc/yum.repos.d/CentOS-Base.repo https://mirrors.aliyun.com/repo/Centos-vault-8.5.2111.repo
[root@kvm ~]# sed -i -e '/mirrors.cloud.aliyuncs.com/d' -e '/mirrors.aliyuncs.com/d' /etc/yum.repos.d/CentOS-Base.repo
//安装所需软件包
[root@kvm ~]# yum -y install epel-release
[root@kvm ~]# yum -y install vim wget net-tools unzip zip gcc gcc-c++ qemu-kvm qemu-img virt-manager libvirt libvirt-client virt-install virt-viewer libguestfs-tools
[root@kvm ~]# wget http://mirror.centos.org/centos/7/os/x86_64/Packages/qemu-kvm-tools-1.5.3-175.el7.x86_64.rpm
[root@kvm ~]# wget http://mirror.centos.org/centos/7/os/x86_64/Packages/libvirt-python-4.5.0-1.el7.x86_64.rpm
[root@kvm ~]# wget http://mirror.centos.org/centos/7/os/x86_64/Packages/bridge-utils-1.5-9.el7.x86_64.rpm
[root@kvm ~]# rpm -ivh --nodeps libvirt-python-4.5.0-1.el7.x86_64.rpm
[root@kvm ~]# rpm -ivh --nodeps qemu-kvm-tools-1.5.3-175.el7.x86_64.rpm
//验证cpu是否支持kvm,vmx是intel的 svm是AMD的
[root@kvm ~]# egrep -o 'vmx|svm' /proc/cpuinfo
vmx
vmx
vmx
vmx
//安装kvm
//安装kvm
[root@kvm ~]# yum -y install qemu-kvm \
> qemu-kvm \
> qemu-img \
> virt-manager \
> libvirt \
> libvirt-python3 \
> libvirt-client \
> virt-install \
> virt-viewer \
> bridge-utils \
> libguestfs-tools
//配置网络,因为虚拟机中的网络,我们一般是都和公司服务器处在同一网段的,所以我们需要把kvm的网卡配置成桥接模式
[root@kvm ~]# cd /etc/sysconfig/network-scripts/
[root@kvm network-scripts]# cp ifcfg-ens33 ifcfg-br0
[root@kvm network-scripts]# vim ifcfg-br0
[root@kvm network-scripts]# cat ifcfg-br0
TYPE=Bridge
BOOTPROTO=none
NAME=br0
DEVICE=br0
ONBOOT=yes
IPADDR=192.168.174.168
PREFIX=24
GATEWAY=192.168.174.2
DNS1=8.8.8.8
[root@kvm network-scripts]# vim ifcfg-ens33
[root@kvm network-scripts]# cat ifcfg-ens33
TYPE=Ethernet
BOOTPROTO=none
NAME=ens33
DEVICE=ens33
ONBOOT=yes
BRIDGE=br0
//重启网卡
[root@kvm ~]# nmcli connection reload
[root@kvm ~]# nmcli connection up ens33
[root@kvm ~]# nmcli connection up br0
[root@kvm ~]# 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: ens33: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc fq_codel master br0 state UP group default qlen 1000
link/ether 00:0c:29:aa:c1:01 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:aa:c1:01 brd ff:ff:ff:ff:ff:ff
inet 192.168.174.168/24 brd 192.168.174.255 scope global noprefixroute br0
valid_lft forever preferred_lft forever
//启动libvirtd服务
[root@kvm ~]# systemctl enable --now libvirtd
//查看kvm模块是否加载
[root@kvm ~]# lsmod |grep kvm
kvm_intel 323584 0
kvm 880640 1 kvm_intel
irqbypass 16384 1 kvm
//将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 7 13:53 /usr/bin/qemu-kvm -> /usr/libexec/qemu-kvm
[root@kvm ~]# yum -y install console-bridge console-bridge-devel
[root@kvm ~]# rpm -ivh bridge-utils-1.5-9.el7.x86_64.rpm
//查看网桥信息
[root@kvm ~]# brctl show
bridge name bridge id STP enabled interfaces
br0 8000.000c29aac101 no ens33
KVM管理界面安装
Kvm的web界面是由webvirtmgr程序提供的
//安装依赖包
[root@kvm ~]# yum -y install git python2-pip supervisor nginx python2-devel
[root@kvm ~]# wget http://mirror.centos.org/centos/7/os/x86_64/Packages/libxml2-python-2.9.1-6.el7.5.x86_64.rpm
//下载webvirtmgr
[root@kvm ~]# wget https://download-ib01.fedoraproject.org/pub/epel/7/x86_64/Packages/p/python-websockify-0.6.0-2.el7.noarch.rpm
[root@kvm ~]# rpm -ivh --nodeps libxml2-python-2.9.1-6.el7.5.x86_64.rpm
warning: libxml2-python-2.9.1-6.el7.5.x86_64.rpm: Header V3 RSA/SHA256 Signature, key ID f4a80eb5: NOKEY
Verifying... ################################# [100%]
Preparing... ################################# [100%]
Updating / installing...
1:libxml2-python-2.9.1-6.el7.5 ################################# [100%]
[root@kvm ~]# rpm -ivh --nodeps python-websockify-0.6.0-2.el7.noarch.rpm
warning: python-websockify-0.6.0-2.el7.noarch.rpm: Header V3 RSA/SHA256 Signature, key ID 352c64e5: NOKEY
Verifying... ################################# [100%]
Preparing... ################################# [100%]
Updating / installing...
1:python-websockify-0.6.0-2.el7 ################################# [100%]
//升级pip
[root@kvm ~]# pip2 install --upgrade pip
WARNING: Running pip install with root privileges is generally not a good idea. Try `pip2 install --user` instead.
Collecting pip
Downloading https://files.pythonhosted.org/packages/27/79/8a850fe3496446ff0d584327ae44e7500daf6764ca1a382d2d02789accf7/pip-20.3.4-py2.py3-none-any.whl (1.5MB)
100% |████████████████████████████████| 1.5MB 18kB/s
Installing collected packages: pip
Found existing installation: pip 9.0.3
Uninstalling pip-9.0.3:
Successfully uninstalled pip-9.0.3
Successfully installed pip-20.3.4
You are using pip version 20.3.4, however version 22.2.2 is available.
You should consider upgrading via the 'pip install --upgrade pip' command.
//github拉取webvirtmgr
[root@kvm ~]# cd /usr/local/src/
[root@kvm src]# git clone http://github.com/retspen/webvirtmgr.git
Cloning into 'webvirtmgr'...
warning: redirecting to https://github.com/retspen/webvirtmgr.git/
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 | 895.00 KiB/s, done.
Resolving deltas: 100% (3606/3606), done.
[root@kvm src]# cd webvirtmgr/
[root@kvm webvirtmgr]# ls
conf hostdetail manage.py secrets templates
console images MANIFEST.in serverlog Vagrantfile
create instance networks servers vrtManager
deploy interfaces README.rst setup.py webvirtmgr
dev-requirements.txt locale requirements.txt storages
//安装webvirtmgr
[root@kvm webvirtmgr]# pip install -r requirements.txt
//检查sqlite3是否安装
[root@kvm webvirtmgr]# python3
Python 3.6.8 (default, Jan 19 2022, 23:28:49)
[GCC 8.5.0 20210514 (Red Hat 8.5.0-7)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import sqlite3
>>> exit()
//初始化账号信息
[root@kvm webvirtmgr]# python2 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@kvm ~]# mkdir /var/www
[root@kvm ~]# cp -r /usr/local/src/webvirtmgr/ /var/www/
[root@kvm ~]# chown -R nginx.nginx /var/www/webvirtmgr/
//配置密钥认证
由于这里webvirtmgr和kvm服务部署在同一台机器,所以这里是本地信任;如果kvm部署在其他机器上的时候,那么就需要把公钥发送到kvm主机中
[root@kvm ~]# 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:1WwTuruPDDjrRNskZLDxAwJPW0lpkXCOFzSZT40TRsQ root@kvm
The key's randomart image is:
+---[RSA 3072]----+
|..++%@=+ . |
| o BBXE . + . |
| +.+o=. o = |
| . o.. . o . |
| o S . |
| . * . |
| = o . |
| . o o o |
| .o +.. |
+----[SHA256]-----+
[root@kvm ~]# ssh-copy-id -i ~/.ssh/id_rsa.pub root@192.168.174.168
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/root/.ssh/id_rsa.pub"
The authenticity of host '192.168.174.168 (192.168.174.168)' can't be established.
ECDSA key fingerprint is SHA256:sfUIHR7r4pLw+1JpJPet9brqYcJdceEQPBZhtYpej4I.
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.174.168's password:
Number of key(s) added: 1
Now try logging into the machine, with: "ssh 'root@192.168.174.168'"
and check to make sure that only the key(s) you wanted were added.
//配置端口转发
[root@kvm ~]# ssh 192.168.174.168 -L localhost:8000:localhost:8000 -L localhost:6080:localhost:60
//查看端口
[root@kvm ~]# ss -anlt
State Recv-Q Send-Q Local Address:Port Peer Address:Port Process
LISTEN 0 128 127.0.0.1:6080 0.0.0.0:*
LISTEN 0 128 127.0.0.1:8000 0.0.0.0:*
LISTEN 0 128 0.0.0.0:111 0.0.0.0:*
LISTEN 0 32 192.168.122.1:53 0.0.0.0:*
LISTEN 0 128 0.0.0.0:22 0.0.0.0:*
LISTEN 0 128 [::1]:6080 [::]:*
LISTEN 0 128 [::1]:8000 [::]:*
LISTEN 0 128 [::]:111 [::]:*
LISTEN 0 128 [::]:22 [::]:*
//配置nginx
[root@kvm ~]# cp /etc/nginx/nginx.conf /etc/nginx/nginx.conf.bak
[root@kvm ~]# vim /etc/nginx/nginx.conf
删除listen [::]:80;行
参数server_name行改成server_name localhost;
删除root /usr/share/nginx/html;行
server {
listen 80 ;
server_name localhost;
在include /etc/nginx/default.d/*.conf;行下添加
location / {
root html;
index index.html index.htm;
}
//配置nginx虚拟机
[root@kvm ~]# vim /etc/nginx/conf.d/webvirtmgr.conf
[root@kvm ~]# 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;
}
}
//确保bind绑定本机的8000端口
[root@kvm ~]# grep "bind" /var/www/webvirtmgr/conf/gunicorn.conf.py
# bind - The socket to bind.
bind = '127.0.0.1:8000'
//重启nginx服务,并查看端口
[root@kvm ~]# systemctl restart nginx.service
[root@kvm ~]# ss -anlt
State Recv-Q Send-Q Local Address:Port Peer Address:Port Process
LISTEN 0 128 0.0.0.0:22 0.0.0.0:*
LISTEN 0 128 127.0.0.1:6080 0.0.0.0:*
LISTEN 0 128 127.0.0.1:8000 0.0.0.0:*
LISTEN 0 128 0.0.0.0:111 0.0.0.0:*
LISTEN 0 128 0.0.0.0:80 0.0.0.0:*
LISTEN 0 32 192.168.122.1:53 0.0.0.0:*
LISTEN 0 128 [::]:22 [::]:*
LISTEN 0 128 [::1]:6080 [::]:*
LISTEN 0 128 [::1]:8000 [::]:*
LISTEN 0 128 [::]:111 [::]:*
//设置supervisor
[root@kvm ~]# 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
//启动并开机自启
[root@kvm ~]# systemctl enable --now supervisord.service
//配置nginx用户
[root@kvm ~]# su - nginx -s /bin/bash
[nginx@kvm ~]$ 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:Wr3WNb/Jfo03ozZDcXN04rEJBp/clZIRoV3utfexJcQ nginx@kvm
The key's randomart image is:
+---[RSA 3072]----+
| .. +=.o|
| o=*=oo|
| o++EBo|
| . o=o+|
| S . *+=|
| o o o +*|
| . o o o+|
| . +oo*|
| ..=*+|
+----[SHA256]-----+
[nginx@kvm ~]$ echo -e "StrictHostKeyChecking=no\nUserKnownHostsFile=/dev/null" > ~/.ssh/config
[nginx@kvm ~]$ cat .ssh/config
StrictHostKeyChecking=no
UserKnownHostsFile=/dev/null
[nginx@kvm ~]$ chmod 600 .ssh/config
[nginx@kvm ~]$ ssh-copy-id root@192.168.174.168
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/var/lib/nginx/.ssh/id_rsa.pub"
/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
Warning: Permanently added '192.168.174.168' (ECDSA) to the list of known hosts.
root@192.168.174.168's password:
Number of key(s) added: 1
Now try logging into the machine, with: "ssh 'root@192.168.174.168'"
and check to make sure that only the key(s) you wanted were added.
[nginx@kvm ~]$ exit
logout
[root@kvm ~]# vim /etc/polkit-1/localauthority/50-local.d/50-libvirt-remote-access.pkla
[root@kvm ~]# 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@kvm ~]# systemctl restart nginx.service
[root@kvm ~]# systemctl restart libvirtd