虚拟化基础

传统的物理机部署方案

1

  • IDC选择,如:联通,电信,世纪互联,鹏博士等
  • 网络和存储规划
  • 服务器选型及采购
  • 服务器系统选择、系统安装、上架、配置网络
  • 应用规划及部署
  • 域名选择及注册,DNS配置名称解析
  • 测试外网访问

传统数据中心面临的问题:

  • 服务器和网络设备资源利用率过低,并且无法共享,导致资源浪费

    据统计大部分数据中心中的服务器和网络设备的利用率仅在24%~30%之间,有的CPU利用率、硬盘利用率都在10%以下

  • 资源分配后进行调整困难

    资源分配不合理也是传统网络架构存在的问题,因为资源不能动态调配,分配出去的资源是固定的,不能随意添加或删除。

  • 难以实现自动化

    初始化成本高,服务器迁移和升级很繁琐,无法实现自动化

  • 成本高昂

    集群环境需要大量的服务器主机,硬件投入和后期维护管理成本巨大

虚拟化

什么是虚拟化

虚拟化(Virtualization)是一种资源分配和管理技术,是将计算机的各种实体资源,比如CPU、内存、磁盘空间、网络适配器等,进行抽象转换后虚拟的设备,可以实现灵活地分割、组合为一个或多个计算机配置环境,并还支持重新分割、重新组合,以达到最大化合理利用物理资源的目的。

参考资料: https://www.vmware.com/cn/solutions/virtualization.html

虚拟化优势

虚拟化可以提高 IT 敏捷性、灵活性和可扩展性,同时大幅节约成本。更高的工作负载移动性、更高的性能和资源可用性、自动化运维 - 这些都是虚拟化的优势,虚拟化技术可以使 IT 部门更轻松地进行管理以及降低拥有成本和运维成本。其优势包括:

  • 资源超分,如实际的物理内存只有128G,可以给虚拟机分配200G内存
  • 降低资金成本和运维成本
  • 最大限度减少或消除停机
  • 提高 IT 部门的工作效率和响应能力
  • 加快应用和资源的调配速度
  • 提高业务连续性和灾难恢复能力
  • 简化数据中心管理
  • 减少资源,比如IP和端口的冲突

虚拟化的发展史

2

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
1959年,计算机科学家Christopher Strachey发表了一篇名为《大型高速计算机中的时间共享》(Time Sharing in Large Fast Computers)的学术报告,他在文中首次提出了虚拟化的基本概念,被认为是虚拟化技术的最早论述
1964年,IBM推出了专为 System/360 Mainframe 量身订造的操作系统 CP-40,首次实现了虚拟内存和虚拟机。
1967年,第一个管理程序(hypervisor)诞生,5年之后,IBM 发布用于创建灵活大型主机的虚拟机(VM)技术,该技术可根据动态的需求快速而有效地使用各种资源。从此,虚拟化这一词汇正式被引入了IT的现实世界。
20世纪70年代的 System 370 系列中通过虚拟机监控器(Virtual Machine Monitor,VMM)的程序在物理硬件之上生成多个可以独立运行操作系统软件的虚拟机实例
20世纪 90 年代 Windows 的广泛使用以及 Linux 作为服务器系统的出现奠定了 x86 服务器的行业标准地位。
1998年VMware公司在美国成立,1999年VMware发布了它的第一款产品VMware Workstation、 2001年发布VMware GSX Server和VMware ESXi Server宣布进入服务器虚拟化市场, 2003年VMware推出了VMware Virtual Center, 2004年推出了64位支持版本,同年被EMC收购,2013年收入52.1亿美元。
2015年10月12日,戴尔与数据存储公司EMC的并购宣布完成,最终戴尔以670亿美元收购了EMC
2003年,Xen实现半虚拟化
2005年,HVM硬件辅助的虚拟化,Intel VT-x,AMD-V
2005年,openVZ出现,在Linux平台上的容器化技术实现
2006年,QEMU
2007年,KVM(Kernel-based Virtual Machine)基于内核Linux 2.6.20
2007年8月21日,思杰宣布5亿美元收购XenSource公司,并推出服务器虚拟化XenServer、桌面虚拟化XenDesktop和应用虚拟化XenApp,2013年收入29亿美元。
2008年,LXC发布
2008年3月13日微软在北京发布Windows Server 2008,内置虚拟化技术hyper-v。
2008年9月,红帽以1.07亿美元的价格收购KVM的以色列母公司Qumranet,并推出企业级虚拟化解决方案RHEV,目前最新版本3.3,2013年收入超过13亿美元
2013年,docker发布
2017年11月全球最大公有云厂商AWS宣布了全新的C5实例,该实例完全基于新的虚拟机监控程序(Hypervisor):KVM。在之前的11年里,AWS的所有虚拟化实例都是基于XEN技术实现的。也就是说AWS也开始转向了KVM之路而不再坚持使用从其诞生之日起一直使用的XEN技术,事实上国内的阿里云早在2015年就开始从XEN切换到KVM

虚拟化类型

服务器虚拟化

服务器虚拟化支持在单个物理服务器上运行多个操作系统,每个操作系统作为虚拟机独立运行。

网络虚拟化

通过软件定义网络(Software Defined Network,SDN),即网络的创建不再依赖于物理设备,如公有云厂商支持用户自己通过配置界面创建新的网络,在 KVM、docker、kubernetes、openstack等虚拟化技术中都使用到了网络虚拟化。

桌面虚拟化

将桌面部署为托管的服务,使 IT 组织能够更快地响应不断变化的工作场所需求和新出现的机会。还可以将虚拟化桌面和应用快速、轻松地交付给分支机构、外包和远程员工以及使用 iPad 和 Android 平板电脑的移动员工。

Citrix 思杰公司在云计算虚拟化、虚拟桌面和远程接入技术领域的处于优势地位

应用虚拟化

将软件应用通过网络实现虚拟化,比如 office 365,钉钉,企业微信

存储虚拟化

将存储用软件虚拟化实现, 如 SAN/NAS(NFS/Samba)/GlusterFS/ceph等

库虚拟化

在Linux上使用 wine来运行Windows 程序,在Mac系统使用CrossOver来运行Windows程序

容器虚技术

当前比较火的虚拟化技术,典型代表: Docker、Podman、Linux Container(LXC)、Pouch

虚拟机

虚拟机

虚拟计算机称为“虚拟机”(VM,Virtual Machine),它是一种严密隔离且内含操作系统和应用的软件容器。每个虚拟机都是完全独立的。通过将多台虚拟机放置在一台物理计算机上,可仅在一台物理服务器或“主机”上运行多个操作系统和应用,名为“hypervisor”的精简软件层可将虚拟机与主机分离开来,并根据需要为每个虚拟机动态分配计算资源。

虚拟机的主要特性

虚拟机具有以下特征,这些特征可提供多项优势

分区

可在一台物理机上运行多个操作系统

可在虚拟机之间分配系统资源。

隔离

可在硬件级别进行故障和安全隔离。

可利用高级资源控制功能保持性能

封装

可将虚拟机的完整状态保存到文件中。

移动和复制虚拟机就像移动和复制文件一样轻松

独立于硬件

可将任意虚拟机调配或迁移到任意物理服务器上

安装系统不会受硬件兼容性的影响

Hypervisor类型

Hypervisor 介绍

3

  • Hypervisor是一种运行在基础物理服务器和操作系统之间的中间软件层,其可以允许多个操作系统和应用共享底层的内存、CPU、磁盘等物理硬件,也可叫做VMM( virtual machine monitor),即虚拟机监视器。
  • Hypervisor是所有虚拟化技术的核心,非中断地支持多工作负载迁移的能力是Hypervisor的基本功能,当服务器启动并执行Hypervisor时,它会给每一台虚拟机分配适量的内存、CPU、网络和磁盘,并加载所有虚拟机的客户操作系统。
  • Hypervisor 允许多种操作系统在相同的物理系统中运行
  • Hypervisor 控制硬件并向来宾操作系统提供访问底层硬件的途径
  • Hypervisor 向来宾操作系统提供虚拟化的硬件

X86 CPU 的保护环

4

注意:CPU为了保证程序代码执行的安全性、多用户的独立性、保护OS的正常运行,提出了CPU执行状态的概念。这样能够限制不同程序之间的访问能力,避免一个程序获取另一个程序的内存数据造成数据混乱,同时也避免了程序错误的操作物理硬件。一般CPU都会划分为用户态和内核态 ,x86的CPU架构更是细分为了Ring3~0四种状态。

5

Ring3 用户态(User Mode):运行在用户态的程序代码需要受到CPU的检查,用户态程序代码只能访问内存页表项中规定能被用户态程序代码访问的页面虚拟地址(受限的内存访问),而且还只能访问任务描述符TSS中的I/O Permission Bitmap中规定能被用户态程序代码访问的端口。甚至不能直接访问外围硬件设备、不能抢占CPU。所有的应用程序都运行在用户态上。当运行在用户态的Application需要调用只能被核心态代码直接访问的硬件设备时,CPU会通过特别的接口去调用核心态的代码,以此来实现Application对硬件设备的调用。如果用户态的Application直接调用硬件设备时,就会被Host OS捕捉到并触发异常,弹出警告窗口。

Ring0 核心态(Kernel Mode):是Host OS Kernel运行的模式,运行在核心态的代码可以无限制的对系统内存、设备驱动程序、网卡接口、显卡接口等外围硬件设备进行访问。只有Host OS能够无限制的访问磁盘、键盘等外围硬件设备的数据,但是首先需要在Host OS上安装驱动程序

Hypervisor 分类

1974年Gerald J.Popek和Robert P.Goldberg的文章“Formal Requirements forVirtualizable Third Generation Architectures” 将Hypervisor分为两类:

6
7

类型 I : 裸金属型

直接运行到物理机的Hypervisor上,这种架构搭建的虚拟化环境称为裸机虚拟化环境(Bare-Metal Hardware)

1
2
3
4
5
6
7
8
KVM
XEN
vmware esxi
rhev hypervisor
Hyper-v Server

#Redhat将KVM划分到类型I即裸机型:
https://www.redhat.com/zh/topics/virtualization/what-is-KVM

类型 II : 宿主型

即需要运行在具有虚拟化功能的操作系统上的Hypervisor,构建的是主机虚拟化环境(Hosted Virtualization)

1
2
3
4
vmware workstation
Microsoft Hyper-V
VirtualBox
paralles desktop #Mac系统最强虚拟机技术

虚拟化技术分类

模拟器/软件仿真

8

  • 通过软件模拟完整的硬件环境来虚拟化来宾平台。
  • 可以模拟X86、ARM 、PowerPC等多种CPU
  • 效率比较低
  • 产品或方案:QEMU、Bochs、PearPC

模拟器

1
https://yuzu-emu.org/

全虚拟机化 full virtualization / 本地虚拟化 native virtualization

不需要对GuestOS操作系统软件的源代码做任何的修改,就可以运行在这样的VMM中

在全虚拟化的虚拟平台中,GuestOS并不知道自己是一台虚拟机,它会认为自己就是运行在计算机物理硬件设备上的HostOS。全虚拟化的GuestOS具有完全的物理机特性。因为全虚拟化的VMM会将一个OS所能够操作的CPU、内存、外设等物理设备逻辑抽象成为虚拟CPU、虚拟内存、虚拟外设等虚拟设备后,再交由GuestOS来操作使用。这样的GuestOS会将底层硬件平台视为自己所有的,但是实际上,这些都是VMM为GuestOS制造了这种假象。

全虚拟化/本地虚拟化不做CPU和内存模拟,只对CPU和内存做相应的分配等操作

全虚拟化又分为:软件辅助的全虚拟化 & 硬件辅助的全虚拟化

软件辅助的全虚拟化

9

在Intel等CPU厂商还没有发布x86 CPU虚拟化技术之前,完全虚拟化都是通过软件辅助的方式来实现的。

代表技术: Vmware Workstation,QEMU,Virtual PC

当使用GuestOS的时候,不可避免的会调用GuestOS中的虚拟设备驱动程序 和核心调度程序来操作硬件设备。与HostOS的不同在于,HostOS运行在CPU的核心态中,这就表示HostOS可以直接对硬件设备进行操作。但GuestOS作为一个运行在CPU用户态中应用程序,不能够直接的操作硬件设备。

简而言之,软件辅助虚拟化能够成功的将所有在GuestOS中执行的系统内核特权指令进行捕获、翻译,使之成为只能对GuestOS生效的虚拟特权指令。之所以需要这么做的前提是因为CPU并不能准确的去判断一个特权指令到底是由GuestOS发出的还是由HostOS发出的,这样也就无法针对一个正确的OS去将这一个特权指令执行。

由于全虚拟化VMM会频繁的捕获这些核心态的和敏感的指令,将这些指令进行转换之后,再交给CPU执行。所以经过了转换,导致其效率低,但全虚拟化VMM应用程序的好处在于其不需要对GuestOS的核心源码做修改,所以全虚拟化的VMM可以安装绝大部分的OS(暂时来说只有已Linux、open soralis、BSD等几种OS开源了内核代码)。

直到后来CPU厂商们发布了能够判断特权指令归属的标准x86 CPU之后,迎来了硬件辅助全虚拟化。

硬件辅助的全虚拟化 HVM(Hardware Virtual Machine)

10

2005年Intel提出并开发了由CPU直接支持的虚拟化技术。这种虚拟化技术引入新的CPU运行模式和新的指令集,使得VMM和GuestOS运行于不同的模式下(VMM=Root Mode;GuestOS=Non-Root Mode),GuestOS运行于受控模式,原来的一些敏感指令在受控模式下会全部陷入VMM,由VMM来实现模拟,这样就解决了部分非内核态敏感指令的陷入——模拟难题,而且模式切换时上下文的保存恢复由硬件来完成,这样就大大提高了陷入——模拟时上下文切换的效率 。该技术的引入使x86 CPU可以很容易地实现完全虚拟化。故皆被几乎所有之前分歧的各大流派所采用,包括KVM-x86,VMWare ESX Server 3,Xen 3.0。

虚拟化CPU形成了新的CPU执行状态 Non-Root Mode 和 Root Mode .GuestOS运行在Non-Root Mode 的Ring 0核心态中,这意味着GuestOS能够直接执行特权指令,而不再需要特权解除和陷入模拟机制。并且在硬件层上面紧接的就是虚拟化层的VMM,而不需要HostOS。这是因为在硬件辅助全虚拟化的VMM会以一种更具协作性的方式来实现虚拟化 —— 将虚拟化模块加载到HostOS的内核中,例如:KVM,KVM通过在HostOS内核中加载KVM Kernel Module来将HostOS转换成为一个VMM。所以此时VMM可以看作是HostOS,反之亦然。

硬件辅助全虚拟化主要使用了支持虚拟化功能的CPU进行支撑,CPU可以明确的分辨出来自GuestOS的特权指令,并针对GuestOS进行特权操作,而不会影响到HostOS。

硬件辅助全虚拟化需要物理硬件的支持,比如需要CPU必须支持并且打开虚拟化功能,例如Intel的 Intel VT-X/EPT,AMD的AMD-V/RVI,以在CPU 层面支持虚拟化功能和内存虚拟化技术

1
2
3
4
5
6
7
8
全虚拟化软件(硬件辅助全虚拟化):
vmware esxi
Xen3.0
KVM
Microsoft Hyper-V
vmware workstation #https://www.vmware.com/cn/products/workstation-pro.html
VirtualBox
paralles desktop

KVM 是硬件辅助的虚拟化技术

主要负责比较繁琐的 CPU 和内存虚拟化,而 Qemu 则负责 I/O 虚拟化,两者合作各自发挥自身的功能

半虚拟化 para virtualization

11

半虚拟化是需要GuestOS协助的虚拟化。因为在半虚拟化VMM中运行的GuestOS,都需要将其内核源码进行都进过了特别的修改。

通过修改客户操作系统代码,将原来在物理机上执行的一些特权指令(主要是修改GuestOS指令集中的敏感指令和核心态指令),修改成可以和VMM直接交互的方式,实现操作系统的定制化。这样,就不会有捕获异常、翻译和模拟的过程,性能损耗比较少。

半虚拟化VMM在处理敏感指令和内核态指令的流程上相对更简单一些。让HostOS在捕抓到GuestOS内核态指令或敏感指令时,HostOS也能够准确的判断出该指令是否属于GuestOS(GuestOS知道自己是虚拟机)。这样就可以高效的避免了上述问题。典型的半虚拟化软件有——Xen、KVM-PowerPC(简易指令集)

半虚拟化除了修改内核外还有另外一种实现方法——在每一个GuestOS中安装半虚拟化软件,如: VMTools、RHEVTools。

注意:若使用KVM运行Windows时,一定要安装半虚拟化驱动Tools,否则无法工作。现在主流的半虚拟化驱动是由IBM和redhat联合开发一个通用半虚拟机驱动virtio 。

半虚拟化要求guest OS 的内核是知道自己运行在虚拟化环境当中的,因此guest OS的系统架构必须和宿主机的系统架构相同,并且要求对guest OS的内核做相应的修改,因此半虚拟化只支持开源内核的系统,不支持闭源的系统,比较常见的半虚拟化就是早期版本的XEN,但是Xen 从其3.0 版本开始,可以支持利用硬件辅助虚拟化技术

KVM架构和部署

KVM 概述

KVM 介绍

12

KVM( Kernel-based Virtual Machine)是一个完整的虚拟化解决方案,适用于包含虚拟化扩展(Intel VT或AMD-V)的x86硬件上的Linux。目前也支持ARM等其它硬件平台. 它由可加载的内核模块kvm.ko组成,它提供核心虚拟化基础架构和处理器特定模块,kvm-intel.ko或kvm-amd.ko,KVM的用户空间组件包含在QEMU1.3后续版本中,KVM目前已成为学术界的主流 VMM (virtual machine monitor,虚拟机监视器,也称为 hypervisor)之一

KVM是开源软件,可运行多个运行未修改的Linux或Windows映像的虚拟机

依赖于HVM;Intel VT-x, AMD AMD-V

官网: https://www.Linux-kvm.org

2006年10月,以色列 Qumranet 公司发布 KVM,早期开发者 Avi Kivity

2007年2月,KVM内核组件收录至Linux 2.6.20及后续版本中

2008年9月,Redhat 1.7亿美元收购

2009年9月, RHEL5.4 中在集成XEN的同时,也将KVM添加进来

2011年11月,RHEL6使用KVM代替XEN

13

红帽 kvm 介绍

1
https://www.redhat.com/zh/topics/virtualization/what-is-KVM

RedHat虚拟化指南

1
https://access.redhat.com/documentation/zh-cn/red_hat_enterprise_Linux/7/html/virtualization_getting_started_guide/index

RedHat创建虚拟机数量限制:

1
https://access.redhat.com/articles/rhel-kvm-limits

14

KVM架构

KVM 是基于虚拟化扩展(Intel VT 或者 AMD-V)的 X86 硬件的开源的 Linux 原生的全虚拟化解决方案。KVM 中,虚拟机被实现为常规的 Linux 进程,由标准 Linux 调度程序进行调度;虚机的每个虚拟CPU被实现为一个常规的 Linux 进程。这使得 KVM 能够使用 Linux 内核的已有功能。

但是,KVM 本身不执行任何硬件模拟,需要客户空间程序通过 /dev/kvm 接口设置一个客户机虚拟服务器的地址空间,向它提供模拟的 I/O,并将它的视频显示映射回宿主的显示屏。目前这个应用程序使用QEMU。

KVM 体系结构

15

  • KVM: 初始化CPU硬件,打开虚拟机模式,负责CPU,内存,中断控制器,时钟. 由内核模块kvm_xxx.ko实现,工作于hypervisor,设备/dev/kvm,是一个字符设备,在用户空间可通过ioctl()系统调用来完成VM创建、启动,为VM分配内存、读写VCPU的寄存器、向VCPU注入中断、时钟等管理功能
  • QEMU进程:工作于用户空间,主要用于实现模拟IO设备,如显卡,网卡,硬盘等, qemu-kvm进程:工作于用户空间,用于实现一个虚拟机实例
  • Libvirt:提供统一API,守护进程libvirtd和相关工具,如:virsh,virt-manager等

KVM 模块载入后的系统的运行模式

16

内核模式:HostOS执行I/O类操作,或其它的特殊指令的操作;称作内核模式

用户模式:GuestOS的I/O类操作

来宾模式:GuestOS非I/O类操作,称作虚拟机的用户模式更贴切

KVM 集中管理与控制

KVM是运行在单机的系统,需要其它软件实现跨主机的统一的管理。常见的虚拟化管理平台如下:

http://www.Linux-kvm.org/page/Management_Tools

17

  • oVirt

    功能强大,是Redhat虚拟化管理平台RHEV的开源版本。

    http://www.ovirt.org/

  • WebVirtMgr

    https://www.webvirtmgr.net

    virt-manager的Web模式的替代品

  • OpenStack

    最主流的开源虚拟化管理平台

  • Proxmox virtualization environment

    简称PVE,是一个开源免费的基于Linux的企业级虚拟化方案,功能不输专业收费的VMware。是一个完整的企业虚拟化开源平台。借助内置的Web界面,您可以轻松管理VM和容器,软件定义的存储和网络,高可用性集群以及单个解决方案上的多个开箱即用工具。

宿主机环境准备

KVM需要宿主机CPU必须支持虚拟化功能,因此如果是在vmware workstation上使用虚拟机做宿主机,那么必须要在虚拟机配置界面的处理器选项中开启虚拟机化功能。

CPU开启虚拟化

注意: 给宿主机的CPU和内存分配足够多的配置

18

验证开启虚拟化

1
2
3
4
grep -Em 1  "vmx|svm" /proc/cpuinfo 

#Intel CPU 对应 vmx
#AMD CPU 对应 svm

范例: 验证是否开启虚拟化支持

1
2
3
4
5
6
7
8
9
[root@centos8 ~]# grep -Em 1 "vmx|svm" /proc/cpuinfo 
flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat
pse36 clflush mmx fxsr sse sse2 syscall nx mmxext fxsr_opt pdpe1gb rdtscp lm
constant_tsc rep_good nopl tsc_reliable nonstop_tsc cpuid extd_apicid pni
pclmulqdq ssse3 fma cx16 sse4_1 sse4_2 x2apic movbe popcnt aes xsave avx f16c
rdrand hypervisor lahf_lm svm extapic cr8_legacy abm sse4a misalignsse
3dnowprefetch osvw ssbd ibpb vmmcall fsgsbase bmi1 avx2 smep bmi2 rdseed adx smap
clflushopt clwb sha_ni xsaveopt xsavec xsaves clzero arat npt svm_lock nrip_save
vmcb_clean flushbyasid decodeassists overflow_recov succor

19
20

范例: 查看AMD主机的内核模块

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
[root@centos8 ~]# lscpu|grep svm
Flags: fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca
cmov pat pse36 clflush mmx fxsr sse sse2 syscall nx mmxext fxsr_opt pdpe1gb
rdtscp lm constant_tsc rep_good nopl tsc_reliable nonstop_tsc cpuid extd_apicid
pni pclmulqdq ssse3 fma cx16 sse4_1 sse4_2 x2apic movbe popcnt aes xsave avx f16c
rdrand hypervisor lahf_lm svm extapic cr8_legacy abm sse4a misalignsse
3dnowprefetch osvw ssbd ibpb vmmcall fsgsbase bmi1 avx2 smep bmi2 rdseed adx smap
clflushopt clwb sha_ni xsaveopt xsavec xsaves clzero arat npt svm_lock nrip_save
vmcb_clean flushbyasid decodeassists overflow_recov succor

[root@centos8 ~]# lsmod |grep kvm
kvm_amd 110592 0
ccp 98304 1 kvm_amd
kvm 786432 1 kvm_amd
irqbypass 16384 1 kvm

[root@centos8 ~]# ll /dev/kvm
crw-rw-rw- 1 root kvm 10, 232 Sep 13 21:21 /dev/kvm

安装KVM工具包

KVM 相关工具包介绍

  • qemu-kvm: 为kvm提供底层仿真支持
  • libvirt-daemon: libvirtd守护进程,管理虚拟机
  • libvirt-client: 用户端软件,提供客户端管理命令
  • libvirt-daemon-driver-qemu: libvirtd连接qemu的驱动
  • libvirt: 使用最多的KVM虚拟化管理工具和应用程序接口,即通过libvirt调用KVM创建虚拟机,libvirt是KVM通用的访问API,其不但能管理KVM,还能管理VMware、Xen、Hyper-V、virtualBox等虚拟化方案。
  • virt-manager: 图形界面管理工具,其底层也是调用libvirt API来完成对虚拟机的操作,包括虚拟机的创建、删除、启动、停止以及一些简单的监控功能等。
  • virt-install: 虚拟机命令行安装工具
  • virsh: 命令行工具是基于 libvirt API 创建的命令行工具,它可以作为图形化的 virt-manager 应用的备选工具。virsh 命令可以被用来创建虚拟化任务管理脚本,如安装、启动和停止虚拟机
  • virt-viewer: 通过 VNC 和 SPICE 协议显示虚拟机器图形控制台的最小工具。该工具在其同名软件包中:virtviewer
  • cockpit: CentOS8 专门提供的基于Web的虚拟机管理界面

libvirt 包功能

libvirt 介绍

21

libvirt 程序包是一个与虚拟机监控程序相独立的虚拟化应用程序接口,它可以与操作系统的一系列虚拟化性能进行交互

libvirt 程序包提供:

  • 一个稳定的通用层来安全地管理主机上的虚拟机。
  • 一个管理本地系统和连网主机的通用接口。

在虚拟机监控程序支持的情况下,部署、创建、修改、监测、控制、迁移以及停止虚拟机操作都需要这些API。尽管 libvirt 可同时访问多个主机,但 API 只限于单节点操作

libvirt 程序包被设计为用来构建高级管理工具和应用程序,例如 virt-manager 与 virsh 命令行管理工具。libvirt 主要的功能是管理单节点主机,并提供 API 来列举、监测和使用管理节点上的可用资源,其中包括CPU、内存、储存、网络和非一致性内存访问(NUMA)分区。管理工具可以位于独立于主机的物理机上,并通过安全协议和主机进行交流

libvirt 结构图

22

安装KVM相关包

Ubuntu 安装 KVM

Ubuntu 18.04:

官方文档: https://ubuntu.com/server/docs/virtualization-libvirt

1
2
3
4
5
6
7
8
9
10
11
12
13
[root@ubuntu2204 ~]# apt -y install cpu-checker
[root@ubuntu2004 ~]# apt -y install cpu-checker

#如果CPU不支持会如下提示
[root@ubuntu2004 ~]# kvm-ok
INFO: Your CPU does not support KVM extensions
KVM acceleration can NOT be used

# apt install qemu-kvm virt-manager libvirt-daemon-system
# kvm-ok #验证是否支持kvm,只有Ubuntu支持,CentOS 不支持
#如果CPU支持,如下提示
INFO: /dev/kvm exists
KVM acceleration can be used

范例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
[root@ubuntu2004 ~]# apt update
[root@ubuntu2204 ~]# apt -y install qemu-kvm virt-manager libvirt-daemon-system
[root@ubuntu2004 ~]# apt -y install qemu-kvm virt-manager libvirt-daemon-system
[root@ubuntu1804 ~]# apt -y install qemu-kvm virt-manager libvirt-daemon-system
[root@ubuntu1804 ~]# 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: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc fq_codel state UP
group default qlen 1000
link/ether 00:0c:29:40:27:06 brd ff:ff:ff:ff:ff:ff
inet 10.0.0.100/24 brd 10.0.0.255 scope global eth0
valid_lft forever preferred_lft forever
inet6 fe80::20c:29ff:fe40:2706/64 scope link
valid_lft forever preferred_lft forever
3: virbr0: <NO-CARRIER,BROADCAST,MULTICAST,UP> mtu 1500 qdisc noqueue state DOWN
group default qlen 1000
link/ether 52:54:00:8d:a6:fe brd ff:ff:ff:ff:ff:ff
inet 192.168.122.1/24 brd 192.168.122.255 scope global virbr0
valid_lft forever preferred_lft forever
4: virbr0-nic: <BROADCAST,MULTICAST> mtu 1500 qdisc fq_codel master virbr0 state
DOWN group default qlen 1000
link/ether 52:54:00:8d:a6:fe brd ff:ff:ff:ff:ff:ff

[root@ubuntu2204 ~]# apt -y install bridge-utils
[root@ubuntu2204 ~]# brctl show
bridge name bridge id STP enabled interfaces
virbr0 8000.5254005655f6 yes

#如果没有开启CPU虚拟化功能会提示以下信息
[root@ubuntu1804 ~]# kvm-ok
INFO: Your CPU does not support KVM extensions
KVM acceleration can NOT be used

#添加CPU的虚拟化支持再执行
[root@ubuntu1804 ~]# kvm-ok
INFO: /dev/kvm exists
KVM acceleration can be used

CentOS 安装 KVM

使用虚拟化,需要至少 qemu-kvm 和 qemu-img(安装qemu-kvm会自动安装) 软件包

建议安装:yum install qemu-kvm libvirt virt-manager virt-install

范例: CentOS 8 安装 KVM相关工具

1
2
[root@centos8 ~]# yum -y install qemu-kvm libvirt   virt-manager virt-install virt-viewer
[root@centos8 ~]# systemctl enable --now libvirtd

范例: CentOS 8 还提供基于Web的虚拟机管理方式

1
2
3
4
5
6
7
[root@centos8 ~]# yum -y install cockpit cockpit-machines
[root@centos8 ~]# systemctl enable --now cockpit.socket
Created symlink /etc/systemd/system/sockets.target.wants/cockpit.socket →
/usr/lib/systemd/system/cockpit.socket.

#打开浏览器,访问以下地址:
https://centos8主机:9090

23

图形化工具 virt-manager

范例: CentOS 上管理工具 virt-manager

1
2
3
4
5
6
7
[root@centos8 ~]# export DISPLAY=10.0.0.1:0.0
[root@centos8 ~]# virt-manager
libGL error: No matching fbConfigs or visuals found
libGL error: failed to load driver: swrast

#如果出现乱码,设置语言
[root@ubuntu2204 ~]# localectl set-locale LANG=en_US.UTF-8;exit

24

范例: Ubuntu 上管理工具 virt-manager

1
[root@ubuntu1804 ~]# virt-manager

25

默认网络配置

安装完虚拟工具后,会自动生成一个 virbr0 网卡,类似于Vmware workstation 生成的VMnet8 网卡,充当虚拟机的 NAT 网卡

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
[root@centos8 ~]# 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: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc fq_codel state UP
group default qlen 1000
link/ether 00:0c:29:8a:51:21 brd ff:ff:ff:ff:ff:ff
inet 10.0.0.8/24 brd 10.0.0.255 scope global noprefixroute eth0
valid_lft forever preferred_lft forever
inet6 fe80::20c:29ff:fe8a:5121/64 scope link
valid_lft forever preferred_lft forever
3: virbr0: <NO-CARRIER,BROADCAST,MULTICAST,UP> mtu 1500 qdisc noqueue state DOWN
group default qlen 1000
link/ether 52:54:00:97:eb:e3 brd ff:ff:ff:ff:ff:ff
inet 192.168.122.1/24 brd 192.168.122.255 scope global virbr0
valid_lft forever preferred_lft forever
4: virbr0-nic: <BROADCAST,MULTICAST> mtu 1500 qdisc fq_codel master virbr0 state
DOWN group default qlen 1000
link/ether 52:54:00:97:eb:e3 brd ff:ff:ff:ff:ff:ff

[root@centos8 ~]# grep -R 192.168.122.1 /etc/libvirt/*
/etc/libvirt/qemu/networks/autostart/default.xml: <ip address='192.168.122.1' netmask='255.255.255.0'>
/etc/libvirt/qemu/networks/default.xml: <ip address='192.168.122.1' netmask='255.255.255.0'>

[root@centos8 ~]# ip a show virbr0
3: virbr0: <NO-CARRIER,BROADCAST,MULTICAST,UP> mtu 1500 qdisc noqueue state DOWN
group default qlen 1000
link/ether 52:54:00:97:eb:e3 brd ff:ff:ff:ff:ff:ff
inet 192.168.122.1/24 brd 192.168.122.255 scope global virbr0
valid_lft forever preferred_lft forever

[root@centos8 ~]# cat /etc/libvirt/qemu/networks/default.xml
<network>
<name>default</name>
<uuid>1ebc4504-5da9-4b7e-b367-90b8cb20029b</uuid>
<forward mode='nat'/>
<bridge name='virbr0' stp='on' delay='0'/>
<mac address='52:54:00:97:eb:e3'/>
<ip address='192.168.122.1' netmask='255.255.255.0'>
<dhcp>
<range start='192.168.122.2' end='192.168.122.254'/>
</dhcp>
</ip>
</network>

[root@centos8 ~]# nmcli connection show virbr0
connection.id: virbr0
connection.uuid: 54c671c1-28be-4ce7-8a0e-30ee0ecdca64
connection.stable-id: --
connection.type: bridge
connection.interface-name: virbr0
connection.autoconnect: no
connection.autoconnect-priority: 0
connection.autoconnect-retries: -1 (default)
connection.multi-connect: 0 (default)
connection.auth-retries: -1
connection.timestamp: 1596945412
connection.read-only: no
connection.permissions: --
connection.zone: --
connection.master: --
connection.slave-type: --
connection.autoconnect-slaves: -1 (default)
connection.secondaries: --
connection.gateway-ping-timeout: 0
connection.metered: unknown
connection.lldp: default
connection.mdns: -1 (default)
connection.llmnr: -1 (default)
connection.wait-device-timeout: -1
ipv4.method: manual
ipv4.dns: --
ipv4.dns-search: --
ipv4.dns-options: --
ipv4.dns-priority: 100
ipv4.addresses: 192.168.122.1/24
ipv4.gateway: --
ipv4.routes: --
ipv4.route-metric: -1
ipv4.route-table: 0 (unspec)
ipv4.routing-rules: --
ipv4.ignore-auto-routes: no
ipv4.ignore-auto-dns: no
ipv4.dhcp-client-id: --
ipv4.dhcp-iaid: --
ipv4.dhcp-timeout: 0 (default)
ipv4.dhcp-send-hostname: yes
ipv4.dhcp-hostname: --
ipv4.dhcp-fqdn: --
ipv4.dhcp-hostname-flags: 0x0 (none)
ipv4.never-default: no
ipv4.may-fail: yes
ipv4.dad-timeout: -1 (default)
ipv6.method: ignore
ipv6.dns: --
ipv6.dns-search: --
ipv6.dns-options: --
ipv6.dns-priority: 100
ipv6.addresses: --
ipv6.gateway: --
ipv6.routes: --
ipv6.route-metric: -1
ipv6.route-table: 0 (unspec)
ipv6.routing-rules: --
ipv6.ignore-auto-routes: no
ipv6.ignore-auto-dns: no
ipv6.never-default: no
ipv6.may-fail: yes
ipv6.ip6-privacy: -1 (unknown)
ipv6.addr-gen-mode: stable-privacy
ipv6.ra-timeout: 0 (default)
ipv6.dhcp-duid: --
ipv6.dhcp-iaid: --
ipv6.dhcp-timeout: 0 (default)
ipv6.dhcp-send-hostname: yes
ipv6.dhcp-hostname: --
ipv6.dhcp-hostname-flags: 0x0 (none)
ipv6.token: --
bridge.mac-address: --
bridge.stp: yes
bridge.priority: 32768
bridge.forward-delay: 2
bridge.hello-time: 2
bridge.max-age: 20
bridge.ageing-time: 300
bridge.group-forward-mask: 0
bridge.multicast-snooping: yes
bridge.vlan-filtering: no
bridge.vlan-default-pvid: 1
bridge.vlans: --
proxy.method: none
proxy.browser-only: no
proxy.pac-url: --
proxy.pac-script: --
GENERAL.NAME: virbr0
GENERAL.UUID: 54c671c1-28be-4ce7-8a0e-30ee0ecdca64
GENERAL.DEVICES: virbr0
GENERAL.IP-IFACE: virbr0
GENERAL.STATE: activated
GENERAL.DEFAULT: no
GENERAL.DEFAULT6: no
GENERAL.SPEC-OBJECT: --
GENERAL.VPN: no
GENERAL.DBUS-PATH: /org/freedesktop/NetworkManager/ActiveConnection/3
GENERAL.CON-PATH: /org/freedesktop/NetworkManager/Settings/2
GENERAL.ZONE: --
GENERAL.MASTER-PATH: --
IP4.ADDRESS[1]: 192.168.122.1/24
IP4.GATEWAY: --
IP4.ROUTE[1]: dst = 192.168.122.0/24, nh = 0.0.0.0, mt = 0
IP6.GATEWAY: --

范例: Ubuntu 网络配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
[root@ubuntu1804 ~]# 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: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc fq_codel state UP
group default qlen 1000
link/ether 00:0c:29:40:27:06 brd ff:ff:ff:ff:ff:ff
inet 10.0.0.100/24 brd 10.0.0.255 scope global eth0
valid_lft forever preferred_lft forever
inet6 fe80::20c:29ff:fe40:2706/64 scope link
valid_lft forever preferred_lft forever
3: virbr0: <NO-CARRIER,BROADCAST,MULTICAST,UP> mtu 1500 qdisc noqueue state DOWN
group default qlen 1000
link/ether 52:54:00:8d:a6:fe brd ff:ff:ff:ff:ff:ff
inet 192.168.122.1/24 brd 192.168.122.255 scope global virbr0
valid_lft forever preferred_lft forever
4: virbr0-nic: <BROADCAST,MULTICAST> mtu 1500 qdisc fq_codel master virbr0 state
DOWN group default qlen 1000
link/ether 52:54:00:8d:a6:fe brd ff:ff:ff:ff:ff:ff

[root@ubuntu1804 ~]# brctl show
bridge name bridge id STP enabled interfaces
virbr0 8000.5254008da6fe yes virbr0-nic

[root@ubuntu1804 ~]# cat /etc/libvirt/qemu/networks/default.xml
<network>
<name>default</name>
<uuid>a3235b68-6dc0-4951-8a35-7a60a567f1a7</uuid>
<forward mode='nat'/>
<bridge name='virbr0' stp='on' delay='0'/>
<mac address='52:54:00:8d:a6:fe'/>
<ip address='192.168.122.1' netmask='255.255.255.0'>
<dhcp>
<range start='192.168.122.2' end='192.168.122.254'/>
</dhcp>
</ip>
</network>

准备安装系统的ISO相关文件

将需要安装的系统的ISO文件上传到宿主机

1
2
3
4
5
[root@centos8 ~]# mkdir -pv /data/isos/
[root@centos8 ~]# ls /data/isos/
CentOS-7-x86_64-Minimal-2009.iso
CentOS-8.2.2004-x86_64-minimal.iso
cn_Windows_server_2008_r2_standard_enterprise_datacenter_and_web_with_sp1_vl_build_x64_dvd_617396.iso

AMD CPU 创建虚拟机时的故障排错

AMD CPU 使用virt-manager 或 virt-install 在创建虚拟机可能会出错,用下面方法解决

AMD CPU 使用virt-manager创建虚拟机出错提示

26

AMD CPU 使用virt-install创建虚拟机出错提示

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
[root@centos8 ~]# virt-install --virt-type kvm --name centos7 --ram 1024 --vcpus 2 \
--cdrom=/data/isos/CentOS-7-x86_64-Minimal-2009.iso --disk path=/var/lib/libvirt/images/centos7.qcow2 \
--network network=default --graphics vnc,listen=0.0.0.0 --noautoconsole

WARNING No operating system detected, VM performance may suffer. Specify an OS
with --os-variant for optimal results.

Starting install...
ERROR internal error: qemu unexpectedly closed the monitor: 2020-08-09T15:57:08.872365Z qemu-kvm: error: failed to set MSR 0xe1 to 0x0
qemu-kvm: /builddir/build/BUILD/qemu-2.12.0/target/i386/kvm.c:2119:
kvm_buf_set_msrs: Assertion `ret == cpu->kvm_msr_buf->nmsrs' failed.
Domain installation does not appear to have been successful.
If it was, you can restart your domain by running:
virsh --connect qemu:///system start centos7
otherwise, please restart your installation.

AMD CPU 创建虚拟机故障修复方法

1
2
3
4
5
6
7
#修复以上故障
[root@centos8 ~]# tee /etc/modprobe.d/qemu-system-x86.conf << EOF
> options kvm ignore_msrs=1
> EOF
options kvm ignore_msrs=1

[root@centos8 ~]# reboot

创建虚拟机

使用 virt-manager 创建虚拟机

virt-manager 是一个图形化虚拟机管理工具,方便管理和查看虚拟机

注意:此方式创建虚拟机的磁盘空间为立即分配,所以不要分太大!

1
2
3
4
[root@centos8 ~]# export DISPLAY=10.0.0.1:0.0
[root@centos8 ~]# virt-manager
libGL error: No matching fbConfigs or visuals found
libGL error: failed to load driver: swrast

27
28
29
30
31
32
33
34
35

此处指定的磁盘会生成一个qcow2的稀疏格式文件,此处可以指定文件最大容量,但实际只占用实际的空间大小,使用du -sh 文件可以观察到实际大小,使用ls -l 命令看到是此处指定的大小

36
37
38
39
40
41
42
43
44

范例: 生成的虚拟机相关文件

1
2
3
4
5
6
#保存虚拟机磁盘
[root@centos8 ~]# ll /var/lib/libvirt/images/centos8.qcow2 -h
-rw------- 1 qemu qemu 21G Sep 13 20:08 /var/lib/libvirt/images/centos8.qcow2

#保存虚拟机配置
[root@centos8 ~]# ll /etc/libvirt/qemu/centos8.xml

使用 virt-install 创建虚拟机

虽然使用virt-manager 可以方便的管理虚拟机,但如果需要批量进行虚拟机的创建管理,命令行工具virt-install 更加方便和适合

virt-install 使用说明

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
# virt-install --help
usage: virt-install --name NAME --ram RAM STORAGE INSTALL [options]

使用 '--option=?' 或者 '--option help' 查看可用子选项
有关示例及完整选项语法,请查看 man page。

使用指定安装介质新建虚拟机
optional arguments:
-h, --help show this help message and exit
--version show program's version number and exit
--connect URI 使用 libvirt URI 连接到 hypervisor

通用选项:
-n NAME, --name NAME 客户端虚拟机的名称
--memory MEMORY 配置虚拟机内存分配

例如:
--memory 1024 (in MiB)
--memory 512,maxmemory=1024
--vcpus VCPUS 为虚拟机配置的 vcpus 数。

例如:
--vcpus 5
--vcpus 5,maxcpus=10,cpuset=1-4,6,8
--vcpus sockets=2,cores=4,threads=2
--cpu CPU CPU 型号及功能。

例如:
--cpu coreduo,+x2apic
--cpu host
--metadata METADATA 配置虚拟机元数据

例如:
--metadata name=foo,title="My pretty title",uuid=...
--metadata description="My nice long description"

安装方法选项:
--cdrom CDROM 光驱安装介质
-l LOCATION, --location LOCATION 安装源

例如:
nfs:host:/path
http://host/path
ftp://host/path

--pxe 使用 PXE 协议从网络引导
--import 在磁盘映像中构建虚拟机
--livecd 将光驱介质视为 Live CD
-x EXTRA_ARGS, --extra-args EXTRA_ARGS 附加到使用 --location 引导的内核的参数
--initrd-inject INITRD_INJECT 使用 --location 为 initrd 的 root 添加给定文件
--os-variant DISTRO_VARIANT 在其中安装 OS 变体的虚拟机,比
如:'fedora18'、'rhel6'、'winxp' 等等

--boot BOOT 配置虚拟机引导设置。
例如:
--boot hd,cdrom,menu=on
--boot init=/sbin/init (for containers)

--idmap IDMAP 为 LXC 容器启用用户名称空间。
例如:
--idmap uid_start=0,uid_target=1000,uid_count=10

设备选项:
--disk DISK 使用不同选项指定存储。例如:
--disk size=10 (new 10GiB image in default location)
--disk /my/existing/disk,cache=none
--disk device=cdrom,bus=scsi
--disk=?

-w NETWORK, --network NETWORK 配置虚拟机网络接口。
例如:
--network bridge=mybr0
--network network=my_libvirt_virtual_net
--network network=mynet,model=virtio,mac=00:11...
--network none
--network help

--graphics GRAPHICS 配置虚拟机显示设置。
例如:
--graphics vnc
--graphics spice,port=5901,tlsport=5902
--graphics none
--graphics vnc,password=foobar,port=5910,keymap=ja

--controller CONTROLLER 配置虚拟机控制程序设备。
例如:
--controller type=usb,model=ich9-ehci1

--input INPUT 配置虚拟机输入设备。
例如:
--input tablet
--input keyboard,bus=usb

--serial SERIAL 配置虚拟机串口设备
--parallel PARALLEL 配置虚拟机并口设备
--channel CHANNEL 配置虚拟机沟通频道
--console CONSOLE 配置虚拟机与主机之间的文本控制台连接
--hostdev HOSTDEV 将物理 USB/PCI/etc 主机设备配置为与虚拟机共享
--filesystem FILESYSTEM 将主机目录传递给虚拟机。
例如:
--filesystem /my/source/dir,/dir/in/guest
--filesystem template_name,/,type=template

--sound [SOUND] 配置虚拟机声音设备模拟
--watchdog WATCHDOG 配置虚拟机 watchdog 设备
--video VIDEO 配置虚拟机视频硬件。
--smartcard SMARTCARD 配置虚拟机智能卡设备。例如:--smartcard mode=passthrough

--redirdev REDIRDEV 配置虚拟机重定向设备。例如:--redirdev usb,type=tcp,server=192.168.1.1:4000
--memballoon MEMBALLOON 配置虚拟机 memballoon 设备。例如:--memballoon model=virtio
--tpm TPM 配置虚拟机 TPM 设备。例如:--tpm /dev/tpm
--rng RNG 配置虚拟机 RNG 设备。例如:--rng /dev/random

--panic PANIC 配置虚拟机 panic 设备。例如:--panic default
虚拟机配置选项:
--security SECURITY 设定域安全驱动器配置。
--numatune NUMATUNE 为域进程调整 NUMA 策略。
--memtune MEMTUNE 为域进程调整内粗策略。
--blkiotune BLKIOTUNE为域进程调整 blkio 策略。
--memorybacking MEMORYBACKING 为域进程设置内存后备策略。例如:
--memorybacking hugepages=on
--features FEATURES 设置域 <features> XML。
例如:
--features acpi=off
--features apic=on,eoi=on

--clock CLOCK 设置域 <clock> XML。例如:--clock
offset=localtime,rtc_tickpolicy=catchup
--pm PM 配置 VM 电源管理功能
--events EVENTS 配置 VM 生命周期管理策略
--resource RESOURCE 配置 VM 资源分区(cgroups)

虚拟化平台选项:
-v, --hvm 客户端应该是一个全虚拟客户端
-p, --paravirt 这个客户端一个是一个半虚拟客户端
--container 这台虚拟机需要一个容器客户端
--virt-type HV_TYPE 要使用的管理程序名称(kvm、qemu、xen等等)
--arch ARCH 模拟的 CPU 构架
--machine MACHINE 要模拟的机器类型

其它选项:
--autostart 引导主机时自动启动域。
--wait WAIT 等待安装完成的分钟数。
--noautoconsole 不要自动尝试连接到客户端控制台
--noreboot 完成安装后不要引导虚拟机。
--print-xml [XMLONLY] 输出所生成域 XML,而不是创建虚拟机。
--dry-run 完成安装步骤,但不要创建设备或者定义虚拟机。
--check CHECK 启用或禁用验证检查。例如:
--check path_in_use=off
--check all=off
-q, --quiet 禁止无错误输出
-d, --debug 输入故障排除信息

virt-install 命令创建虚拟机

利用 qemu-img命令创建虚拟磁盘

注意: qemu-img create 一定要确认对应路径下没有此文件,如果存在将覆盖原文件

1
2
3
4
5
6
7
[root@centos8 ~]# qemu-img create -f qcow2 /var/lib/libvirt/images/centos7.qcow2 20G
Formatting '/var/lib/libvirt/images/centos7.qcow2', fmt=qcow2 size=21474836480
cluster_size=65536 lazy_refcounts=off refcount_bits=16

#观察文件虚拟磁盘大小,比较用virt-manager创建的虚拟机磁盘文件大小
[root@centos8 ~]# ll -h /var/lib/libvirt/images/centos7.qcow2
-rw-r--r-- 1 root root 193K Sep 13 21:25 /var/lib/libvirt/images/centos7.qcow2

利用 osinfo-query命令查看支持的OS版本

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
[root@ubuntu2004 ~]# apt install libosinfo-bin
[root@ubuntu2004 ~]# osinfo-query os |grep -i rhel

#查看支持的OS
[root@centos8 ~]# osinfo-query os | grep centos
centos-stream8 | CentOS Stream 8 | 8 | http://centos.org/centos-stream/8
centos-stream9 | CentOS Stream 9 | 9 | http://centos.org/centos-stream/9
centos5.0 | CentOS 5.0 | 5.0 | http://centos.org/centos/5.0
centos5.1 | CentOS 5.1 | 5.1 | http://centos.org/centos/5.1
centos5.10 | CentOS 5.10 | 5.10 | http://centos.org/centos/5.10
centos5.11 | CentOS 5.11 | 5.11 | http://centos.org/centos/5.11
centos5.2 | CentOS 5.2 | 5.2 | http://centos.org/centos/5.2
centos5.3 | CentOS 5.3 | 5.3 | http://centos.org/centos/5.3
centos5.4 | CentOS 5.4 | 5.4 | http://centos.org/centos/5.4
centos5.5 | CentOS 5.5 | 5.5 | http://centos.org/centos/5.5
centos5.6 | CentOS 5.6 | 5.6 | http://centos.org/centos/5.6
centos5.7 | CentOS 5.7 | 5.7 | http://centos.org/centos/5.7
centos5.8 | CentOS 5.8 | 5.8 | http://centos.org/centos/5.8
centos5.9 | CentOS 5.9 | 5.9 | http://centos.org/centos/5.9
centos6.0 | CentOS 6.0 | 6.0 | http://centos.org/centos/6.0
centos6.1 | CentOS 6.1 | 6.1 | http://centos.org/centos/6.1
centos6.10 | CentOS 6.10 | 6.10 | http://centos.org/centos/6.10
centos6.2 | CentOS 6.2 | 6.2 | http://centos.org/centos/6.2
centos6.3 | CentOS 6.3 | 6.3 | http://centos.org/centos/6.3
centos6.4 | CentOS 6.4 | 6.4 | http://centos.org/centos/6.4
centos6.5 | CentOS 6.5 | 6.5 | http://centos.org/centos/6.5
centos6.6 | CentOS 6.6 | 6.6 | http://centos.org/centos/6.6
centos6.7 | CentOS 6.7 | 6.7 | http://centos.org/centos/6.7
centos6.8 | CentOS 6.8 | 6.8 | http://centos.org/centos/6.8
centos6.9 | CentOS 6.9 | 6.9 | http://centos.org/centos/6.9
centos7.0 | CentOS 7 | 7 | http://centos.org/centos/7.0
centos8 | CentOS 8 | 8 | http://centos.org/centos/8

创建虚拟机使用光盘启动并手动安装

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#创建默认NAT模式的虚拟机,并不自动打开virt-viewer连接console,需要手动打开virt-manager 连接,并手动安装系统
[root@centos8 ~]# virt-install --virt-type kvm --name centos7 --ram 1024 --vcpus 2 \
--cdrom=/data/isos/CentOS-7-x86_64-Minimal-2009.iso --disk \
path=/var/lib/libvirt/images/centos7.qcow2 --network network=default \
--graphics vnc,listen=0.0.0.0 --noautoconsole --os-variant=centos7.0


Starting install...
Domain installation still in progress. You can reconnect to
the console to complete the installation process


[root@centos8 ~]# export DISPLAY=10.0.0.1:0.0
[root@centos8 ~]# virt-manager

#查看虚拟硬盘大小,注意到只要正在运行的虚拟对应的硬盘文件所有者和组为qemu,而虚拟机关机的为root
[root@centos8 ~]# ll /var/lib/libvirt/images/ -h
total 22G
-rw-r--r-- 1 qemu qemu 1.6G Sep 13 22:05 centos7.qcow2
-rw------- 1 root root 21G Sep 13 22:05 centos8.qcow2

#安装过程略
#示例:使用桥接网络
[root@centos8 ~]# virt-install --virt-type kvm --name centos7 --ram 1024 --vcpus 2 \
--cdrom=/data/isos/CentOS-7-x86_64-Minimal-2009.iso --disk \
path=/var/lib/libvirt/images/centos7.qcow2 --network \
--network=bridge:virbr0,model=virtio --graphics vnc,listen=0.0.0.0 --noautoconsole \
--os-variant=centos7.0

45

范例:

1
2
3
4
5
6
7
[root@ubuntu2204 ~]# qemu-img create -f qcow2 
/var/lib/libvirt/images/rocky8.qcow2 20G

[root@ubuntu2204 ~]# virt-install --virt-type kvm --name rocky8 --ram 2048 --vcpus 2 \
--cdrom=/data/isos/Rocky-8.5-x86_64-minimal.iso --disk \
path=/var/lib/libvirt/images/rocky8.qcow2 --network network=default \
--graphics vnc,listen=0.0.0.0 --noautoconsole --os-variant=rocky8.5

验证宿主机进程

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
[root@centos8 ~]# ps aux|grep qemu-kvm
qemu 6696 1.4 8.5 4021940 698296 ? Sl Sep21 0:45 /usr/libexec/qemu-kvm
......

[root@centos8 ~]# pstree -p |grep kvm
|-qemu-kvm(6696)-+-{qemu-kvm}(6709)
| |-{qemu-kvm}(6717)
| |-{qemu-kvm}(6718)
| |-{qemu-kvm}(6719)
| |-{qemu-kvm}(6721)
| `-{qemu-kvm}(6722)
|-qemu-kvm(7591)-+-{qemu-kvm}(7605)
| |-{qemu-kvm}(7611)
| |-{qemu-kvm}(7612)
| |-{qemu-kvm}(7613)
| |-{qemu-kvm}(7615)
| `-{qemu-kvm}(7616)

基于现有虚拟机磁盘为模版创建新的虚拟机

利用virt-manager实现

1
2
#基于已经安装好虚拟机磁盘文件,创建新的磁盘文件
[root@centos8 ~]# cp -a /var/lib/libvirt/images/centos7.qcow2 /var/lib/libvirt/images/centos7-2.qcow2

46
47

利用virt-install实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
[root@centos8 images]# pwd
/var/lib/libvirt/images

[root@centos8 images]# cp centos8.qcow2 centos8-2.qcow2
[root@centos8 images]# virt-install --virt-type kvm --name centos8-2 --ram 2048 --vcpus 2 \
--disk bus=virtio,path=/var/lib/libvirt/images/centos8-2.qcow2 --network \
network=default,model=virtio --graphics vnc,listen=0.0.0.0 --noautoconsole --autostart --boot hd


WARNING No operating system detected, VM performance may suffer. Specify an OS
with --os-variant for optimal results.
Starting install...
Domain creation completed.

#运行工具,可以看到下面出现新的虚拟机
[root@centos8 images]# virt-manager

利用virt-clone克隆实现

1
2
3
4
5
#基于已有的虚拟机克隆生成新的虚拟机
[root@ubuntu2004 ~]# virt-clone -o rocky8 -f /var/lib/libvirt/images/rocky8-3.qcow2 -n rocky8-3
-o rocky8 #指已存在的虚拟机的名称
-f /var/lib/libvirt/images/rocky8-3.qcow2 #新虚拟机磁盘文件路径,此文件自动生成,不需要事先创建
-n rocky8-3 #新虚拟机的名称

管理虚拟机

使用半虚拟化驱动 virtio

半虚拟化驱动virtio的工作原理

为了提高内存、硬盘、网络的性能,需要支持半虚拟化

48
49

virtio 是一种 I/O 半虚拟化解决方案,是一套通用 I/O 设备虚拟化的程序,是对半虚拟化 Hypervisor 中的一组通用 I/O 设备的抽象,提供了一套上层应用与各 Hypervisor 虚拟化设备(KVM,Xen,VMware等)之间的通信框架和编程接口,减少跨平台所带来的兼容性问题,大大提高驱动程序开发效率,Windows 系统需要单独安装virtio驱 动,Linux系统自带virtio驱动。

50

实现IO虚拟化主要有三种方式:全虚拟化、半虚拟化和透传,全虚拟化Guest OS不会感知到自己是虚拟机,也无需修改Guest OS,但是它的效率比较低,半虚拟化Guest OS知道自己是虚拟机,通过Frontend/Backend驱动模拟实现IO虚拟化,透传就是直接分配物理设备给VM用,但是需要解决单个硬件在多个虚拟机共享使用的问题。

性能比较

1
https://www.ilsistemista.net/index.php/virtualization/42-kvm-virtio-paravirtualized-drivers-why-they-matter.html?start=2

51

52

半虚拟化设备统一接口virtio

53

通过统一的接口virtio以支持的多种硬件设备

  • 不同的虚拟设备和不同的虚拟机可以有不同的前端驱动
  • 不同的硬件设备可以有不同的后端驱动
  • 两者之间的交互遵循virtio的标准

驱动获取

Linux 的 VirtIO 驱动

红帽RHEL 4.8之后的虚拟机会自动加载和安装virtio驱动

54

Windows 操作系统需要额外安装 virtio 的驱动

方法1∶如果有红帽的RHN订阅,可以从以下位置下载virtio-win包

1
https://rhn.redhat.com/rhn/software/packages/details/Overview.do?pid=868414

方法2∶从社区获得

1
2
3
4
http://www.Linux-kvm.org/page/Downloads
https://fedorapeople.org/groups/virt/virtio-win/direct-downloads/
https://fedorapeople.org/groups/virt/virtio-win/direct-downloads/archive-virtio/
https://docs.fedoraproject.org/en-US/quick-docs/creating-Windows-virtual-machines-using-virtio-drivers/index.html

55
56
57
58

Linux 测试安装virtio驱动前后的虚拟机性能变化

默认虚拟机使用的是全虚拟化IDE磁盘,以下测试性能

使用dd 或 hdparm测试

1
[root@centos8 ~]# dd | hdparm -t /dev/vda

59

将硬盘默认的总线IDE修改为VirtIO

60

重新启动后,执行相同的操作,比较性能

61

默认网卡为e1000,将之修改网卡驱动为virtIO

62

安装 Windows Server 虚拟机

下载并准备相关文件

1
2
3
4
5
# virtio下载地址:
https://fedorapeople.org/groups/virt/virtio-win/direct-downloads/

# virtio 历史版本下载地址:
https://fedorapeople.org/groups/virt/virtio-win/direct-downloads/archive-virtio/

63

1
2
3
4
5
6
[root@centos8 ~]# ll /data/isos/
total 6031060
-rw-r--r-- 1 qemu qemu 1085276160 Aug 9 16:38 CentOS-7-x86_64-Minimal-2009.iso
-rw-r--r-- 1 qemu qemu 1718616064 Aug 9 16:31 CentOS-8.2.2004-x86_64-minimal.iso
-rw-r--r-- 1 root root 3368962048 Aug 11 12:00 cn_Windows_server_2008_r2_standard_enterprise_datacenter_and_web_with_sp1_vl_build_x64_dvd_617396.iso
-rw-r--r-- 1 root root 2949120 Aug 11 12:01 virtio-win-0.1.141_amd64.vfd

创建 Windows Server 2008 虚拟机

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#创建磁盘文件
[root@centos8 ~]#qemu-img create -f qcow2 /var/lib/libvirt/images/Windows-2008_r2-x86_64.qcow2 20G

#查看支持的Windows版本
[root@centos8 ~]# osinfo-query os| grep win
win1.0 | Microsoft Windows 1.0 | 1.0 | http://microsoft.com/win/1.0
win10 | Microsoft Windows 10 | 10.0 | http://microsoft.com/win/10
win11 | Microsoft Windows 11 | 11.0 | http://microsoft.com/win/11
win2.0 | Microsoft Windows 2.0 | 2.0 | http://microsoft.com/win/2.0
win2.1 | Microsoft Windows 2.1 | 2.1 | http://microsoft.com/win/2.1
win2k | Microsoft Windows 2000 | 5.0 | http://microsoft.com/win/2k
win2k12 | Microsoft Windows Server 2012 | 6.3 | http://microsoft.com/win/2k12
win2k12r2 | Microsoft Windows Server 2012 R2 | 6.3 | http://microsoft.com/win/2k12r2
win2k16 | Microsoft Windows Server 2016 | 10.0 | http://microsoft.com/win/2k16
win2k19 | Microsoft Windows Server 2019 | 10.0 | http://microsoft.com/win/2k19
win2k22 | Microsoft Windows Server 2022 | 10.0 | http://microsoft.com/win/2k22
win2k3 | Microsoft Windows Server 2003 | 5.2 | http://microsoft.com/win/2k3
win2k3r2 | Microsoft Windows Server 2003 R2 | 5.2 | http://microsoft.com/win/2k3r2
win2k8 | Microsoft Windows Server 2008 | 6.0 | http://microsoft.com/win/2k8
win2k8r2 | Microsoft Windows Server 2008 R2 | 6.1 | http://microsoft.com/win/2k8r2
win3.1 | Microsoft Windows 3.1 | 3.1 | http://microsoft.com/win/3.1
win7 | Microsoft Windows 7 | 6.1 | http://microsoft.com/win/7
win8 | Microsoft Windows 8 | 6.2 | http://microsoft.com/win/8
win8.1 | Microsoft Windows 8.1 | 6.3 | http://microsoft.com/win/8.1
win95 | Microsoft Windows 95 | 4.0 | http://microsoft.com/win/95
win98 | Microsoft Windows 98 | 4.1 | http://microsoft.com/win/98
winme | Microsoft Windows Millennium Edition | 4.9 | http://microsoft.com/win/me
winnt3.1 | Microsoft Windows NT Server 3.1 | 3.1 | http://microsoft.com/winnt/3.1
winnt3.5 | Microsoft Windows NT Server 3.5 | 3.5 | http://microsoft.com/winnt/3.5
winnt3.51 | Microsoft Windows NT Server 3.51 | 3.51 | http://microsoft.com/winnt/3.51
winnt4.0 | Microsoft Windows NT Server 4.0 | 4.0 | http://microsoft.com/winnt/4.0
winvista | Microsoft Windows Vista | 6.0 | http://microsoft.com/win/vista
winxp | Microsoft Windows XP | 5.1 | http://microsoft.com/win/xp



#下面版本成功
[root@ubuntu2004 ~]# virt-install --virt-type kvm --name Win2008 --memory 3072 --vcpus=2 \
--os-variant=win2k8r2 --cdrom=/data/isos/cn_windows_server_2008_r2_standard_enterprise_datacenter_and_we
b_with_sp1.iso \
--disk path=/var/lib/libvirt/images/Windows-2008_r2-x86_64.qcow2,format=qcow2,bus=virtio \
--disk path=/data/isos/virtio-win-0.1.141_amd64.vfd,device=floppy --network bridge=virbr0,model=virtio \
--graphics vnc,listen=0.0.0.0 --noautoconsole --autostart

#创建 Windows 虚拟机,新版不支持下面格式,可以通过virt-manager进行安装
[root@cetos8 ~]# virt-install --virt-type kvm --name Win2008 --memory 3072 --vcpus=2 \
--os-variant=win2k8r2 --cdrom=/data/isos/cn_Windows_server_2008_r2_standard_enterprise_datacenter_and_we
b_with_sp1_vl_build_x64_dvd_617396.iso \
--disk path=/var/lib/libvirt/images/Windows-2008_r2-x86_64.qcow2,format=qcow2,bus=virtio \
--disk path=/data/isos/virtio-win-0.1.141_amd64.vfd,device=floppy --network \
bridge=virbr0,model=virtio --graphics vnc,listen=0.0.0.0 --noautoconsole --autostart

Starting install...
Domain installation still in progress. You can reconnect to
the console to complete the installation process.

[root@centos8 ~]# virt-manager

安装 Windows Server 2008

64
65
66
67
68
69
70
71
72

注意: 不要选中 GPU

73
74
75
76
77
78
79

验证 Windows virtio 驱动

80

安装PCI 内存管理驱动

挂载virtio-win的141的ISO光盘文件virtio-win-0.1.141.iso进行安装驱动

注意:不要安装其它版本,比如189版本会蓝屏死机,185安装后显示黄色,工作不正常

81
82
83
84
85
86

生成Windows Server 2008 镜像模版

利用sysprep工具,清除个性信息,下次Windows开机时, 会自动生成初始化个性信息

87

下次开机需要重新初始化

88

基于模版创建新的Windows的虚拟机

1
2
3
4
5
6
7
[root@centos7 images]# pwd
/var/lib/libvirt/images

[root@centos7 images]# cp windows2008.qcow2 windows2008-2.qcow2
[root@centos7 ~]# virt-install --virt-type kvm --name Win2008-2 --memory 3072 --vcpus=2 \
--os-variant=win2k8r2 --disk path=/var/lib/libvirt/images/windows2008-2.qcow2,format=qcow2,bus=virtio \
--network bridge=virbr0,model=virtio --graphics vnc,listen=0.0.0.0 --noautoconsole --autostart --boot hd

libvirt 架构

89

注意: 如果libvirtd服务意外关闭,将导致相关工具,如:virt-manager等无法和虚拟机连接,但虚拟机仍会正常运行

范例: libvirtd 服务功能

1
2
3
4
5
6
7
8
9
10
11
12
13
[root@centos8 ~]# virsh list
Id Name State
----------------------------------------------------
2 centos8 running
3 Win_2008_r2-x86_64 running

[root@ubuntu2004 ~]# systemctl stop libvirtd libvirtd.socket libvirtd-admin.socket libvirtd-ro.socket

[root@centos8 ~]# systemctl stop libvirtd
[root@centos8 ~]# virsh list
error: failed to connect to the hypervisor
error: Failed to connect socket to '/var/run/libvirt/libvirt-sock': No such file or directory
#virt-manager工具也无法连接虚拟机

90

1
2
3
4
5
6
7
8
[root@centos8 ~]# systemctl start libvirtd
[root@centos8 ~]# virsh list
Id Name State
----------------------------------------------------
2 centos8 running
3 Win_2008_r2-x86_64 running

#virt-manager工具也恢复连接虚拟机

91

virt-manager 管理虚拟机

virt-manager是一个图形化工具,主要功能:

  • 定义和创建虚拟机
  • 硬件管理
  • 性能监视
  • 控制台
  • 在线和离线迁移
  • 虚拟机的保存和恢复、暂停和继续、关闭和启动

启动菜单

92

开机后,按提示按ESC键,会出下面启动菜单

93

远程管理KVM宿主机

Ubuntu20.04和Rocky8相互支持远程连接

可以连接到远程的宿主机进行虚拟机的管理

94
95
96

解决上面问题的方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#方法1:在本机安装openssh-askpass包
[root@ubuntu2004 ~]# apt install -y ssh-askpass
[root@centos8 ~]# yum -y install openssh-askpass

#方法2:实现基于本机到远程主机的key验证
[root@centos8 ~]# ssh-copy-id 10.0.0.18
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed:
"/root/.ssh/id_rsa.pub"
The authenticity of host '10.0.0.18 (10.0.0.18)' can't be established.
ECDSA key fingerprint is SHA256:divKS+okAaeOzwWk/rHnrmZXWo3DUBPkkAnbofk+rbA.
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@10.0.0.18's password:

Number of key(s) added: 1

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

再次连接成功

97
98
99

虚拟机的性能监控

先选择需要监控的项目

100

根据上面的项目,选择对应显示的项目(可选项由前一页的项目决定)

101

管理快照

102
103
104

virsh 命令行工具

virsh 命令说明

virsh是使用libvirt managementAPI构建的管理工具,相比virt-manager可以提高效率

virsh的名称的含义是virtualization shell

两种工作模式

  • 交互模式
  • 非交互模式

105
106

virsh 主要功能

1
2
3
4
5
6
7
8
9
10
11
12
13
[root@centos8 ~]# virsh help
Domain Management (help keyword 'domain'):
Domain Monitoring (help keyword 'monitor'):
Host and Hypervisor (help keyword 'host'):
Interface (help keyword 'interface'):
Network Filter (help keyword 'filter'):
Networking (help keyword 'network'):
Node Device (help keyword 'nodedev'):
Secret (help keyword 'secret'):
Snapshot (help keyword 'snapshot'):
Storage Pool (help keyword 'pool'):
Storage Volume (help keyword 'volume'):
Virsh itself (help keyword 'virsh'):

virsh 命令格式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
[root@centos8 ~]# virsh --help

virsh [options]... [<command_string>]
virsh [options]... <command> [args...]

options:
-c | --connect=URI hypervisor connection URI
-d | --debug=NUM debug level [0-4]
-e | --escape <char> set escape sequence for console
-h | --help this help
-k | --keepalive-interval=NUM
keepalive interval in seconds, 0 for disable
-K | --keepalive-count=NUM
number of possible missed keepalive messages
-l | --log=FILE output logging to file
-q | --quiet quiet mode
-r | --readonly connect readonly
-t | --timing print timing information
-v short version
-V long version
--version[=TYPE] version, TYPE is short or long (default short)

virsh 子命令说明

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
help                     #打印基本帮助信息
attach-device #使用XML文件中的设备定义在虚拟机中添加设备
attach-disk #在虚拟机中附加新磁盘设备
attach-interface #在虚拟机中附加新网络接口
create #从 XML 配置文件生成虚拟机并启动新虚拟机
define #为虚拟机输出XML配置文件
destroy #强制虚拟机停止
detach-device #从虚拟机中分离设备,使用同样的XML 描述作为命令attach-device
detach-disk #从虚拟机中分离磁盘设备
detach-interface #从虚拟机中分离网络接口
domblkstat #显示正在运行的虚拟机的块设备统计
domid #显示虚拟机ID
domifstat #显示正在运行的虚拟机的网络接口统计
dominfo #显示虚拟机信息
domname #显示虚拟机名称
domstate #显示虚以机状态
domuuid #显示虚拟机UUID
dumpxml #输出虚拟机 XML配置文件
list #列出所有虚拟机
migrate #将虚拟机迁移到另一台主机中
nodeinfo #有关管理程序的输出信息
quit #退出这个互动终端
reboot #重新启动虚拟机
restore #恢复以前保存在文件中的虚拟机
resume #恢复暂停的虚拟机
save #将虚拟机当前状态保存到某个文件中
setmaxmem #为管理程序设定内存上限
setmem #为虚拟机设定分配的内存
setvcpus #修改为虚拟机分配的虚拟CPU数目
shutdown #关闭某个虚拟机
start #启动未激活的虚拟机
suspend #暂停虚拟机
undefine #删除与虚拟机关联的所有文件
vepuinfo #显示虚以机的虚拟CPU信息
vcpupin #控制虚拟机的虚拟CPU亲和性
version #显示virsh版本

查看子命令帮助

1
virsh help COMMAND

范例: 查看子命令 list 命令用法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
[root@centos8 ~]# virsh help list
NAME
list - list domains


OPTIONS
--inactive list inactive domains
--all list inactive & active domains
--transient list transient domains
--persistent list persistent domains
--with-snapshot list domains with existing snapshot
--without-snapshot list domains without a snapshot
--state-running list domains in running state
--state-paused list domains in paused state
--state-shutoff list domains in shutoff state
--state-other list domains in other states
--autostart list domains with autostart enabled
--no-autostart list domains with autostart disabled
--with-managed-save list domains with managed save state
--without-managed-save list domains without managed save
--uuid list uuid's only
--name list domain names only
--table list table (default)
--managed-save mark inactive domains with managed save state
--title show domain title

启动和关闭虚拟机

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
#查看当前启动的虚拟机
[root@centos8 ~]# virsh list
Id Name State
----------------------------------------------------
1 Win_2008_r2-x86_64 running


#查看所有虚拟机
[root@centos8 ~]# virsh list --all
Id Name State
----------------------------------------------------
1 Win_2008_r2-x86_64 running
- centos7 shut off
- centos8 shut off
- centos8-vm2 shut off
- centos8-vm3 shut off
- centos8-vm4 shut off


#启动
[root@centos8 ~]# virsh start centos8
Domain centos8 started

[root@centos8 ~]# virsh list
Id Name State
----------------------------------------------------
1 Win_2008_r2-x86_64 running
2 centos8 running

#正常关机
[root@centos8 ~]# virsh shutdown 1
Domain 1 is being shutdown

[root@centos8 ~]# virsh list
Id Name State
----------------------------------------------------
1 Win_2008_r2-x86_64 running
2 centos8 running

#强制关机,慎重使用
[root@centos8 ~]# virsh destroy 1
Domain 1 destroyed

[root@centos8 ~]# virsh list
Id Name State
----------------------------------------------------
2 centos8 running


[root@centos8 ~]# virsh shutdown 2
Domain 2 is being shutdown

#列出开机状态虚拟机的UUID和名称
[root@centos8 ~]# virsh list --uuid --name
Id Name State
----------------------------------------------------
fee16012-fee9-4348-8cf3-8bb4e1af4a28 centos7.9
5c7b4e61-5f9f-4334-a304-4f9ce79afa01 rocky8-2
c58c587c-5595-4f2c-9ace-66d4c8b246dd k8s-node-03
5ebc9d1e-24f5-4cc4-a396-327f040f29e3 k8s-node-04
8cb644a3-3135-4603-8075-e65c38cc23ad rocky8-4
f0f91ab8-45e4-4bf5-97a3-1ae24de21809 k8s-node-05
37e82325-7ae9-46e2-8457-476b95de8aec k8s-node-06


#列出所有虚拟机的UUID和name
[root@ubuntu2004 ~]# virsh list --uuid --all --name
fee16012-fee9-4348-8cf3-8bb4e1af4a28 centos7.9
5c7b4e61-5f9f-4334-a304-4f9ce79afa01 rocky8-2
c58c587c-5595-4f2c-9ace-66d4c8b246dd k8s-node-03
5ebc9d1e-24f5-4cc4-a396-327f040f29e3 k8s-node-04
8cb644a3-3135-4603-8075-e65c38cc23ad rocky8-4
f0f91ab8-45e4-4bf5-97a3-1ae24de21809 k8s-node-05
37e82325-7ae9-46e2-8457-476b95de8aec k8s-node-06
92ef41cc-ca99-4828-a219-1a62179be37d k8s-node-01
87ae11e9-0847-4644-9146-0fe89e8348d2 k8s-node-02
e9bbdd61-238e-4986-a6a5-26de4d4703aa rocky8
840487ec-0dae-491b-88e0-68d446cdcc15 rocky8-3
6ae2e917-9ad9-4364-8b56-7fb2da46650b rocky8-template
33b4be03-92bb-457f-a50e-6cfff0c7edb4 Win2008-2
d4687970-a9fb-4c74-8c81-410dd04425dc Win2008-template

在virt-manager 中可以看到关机状态

107
108

查看虚拟机UUID,通过UUID启动关闭虚拟机

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
[root@centos8 ~]# virsh list
Id Name State
----------------------------------------------------
1 centos8 running

#查看虚拟机的UUID
[root@centos8 ~]# virsh domuuid 1
99765478-cfb1-4164-b038-f62004ccab9e

[root@centos8 ~]# virsh destroy 99765478-cfb1-4164-b038-f62004ccab9e
Domain 99765478-cfb1-4164-b038-f62004ccab9e destroyed

[root@centos8 ~]# virsh list
Id Name State
----------------------------------------------------

[root@centos8 ~]# virsh list --all
Id Name State
----------------------------------------------------
- centos7 shut off
- centos8 shut off
- centos8-vm2 shut off
- centos8-vm3 shut off
- centos8-vm4 shut off
- Win_2008_r2-x86_64 shut off

[root@centos8 ~]# virsh domuuid centos8
99765478-cfb1-4164-b038-f62004ccab9e

[root@centos8 ~]# virsh start 99765478-cfb1-4164-b038-f62004ccab9e
Domain centos8 started

[root@centos8 ~]# virsh list
Id Name State
----------------------------------------------------
2 centos8 running

[root@centos8 ~]# virsh domuuid centos8
99765478-cfb1-4164-b038-f62004ccab9e

暂停和恢复虚拟机

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
[root@centos8 ~]# virsh list
Id Name State
----------------------------------------------------
1 centos8 running

[root@centos8 ~]# virsh suspend centos8
Domain centos8 suspended

[root@centos8 ~]# virsh list
Id Name State
----------------------------------------------------
1 centos8 paused

#虚拟机暂停后,宿主机中还存有相关的进程
[root@centos8 ~]# ps aux|grep kvm
qemu 1699 36.9 16.0 4439296 1309300 ? Sl 10:10 5:28 /usr/libexec/qemu-kvm -name guest=centos8,debug-threads=on -S -object
secret,id=masterKey0,format=raw,file=/var/lib/libvirt/qemu/domain
......

[root@centos8 ~]# virsh resume 1
Domain 1 resumed

[root@centos8 ~]# virsh list
Id Name State
----------------------------------------------------
1 centos8 running

配置虚拟机开机自动启动

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
[root@centos8 ~]# virsh list --all
Id Name State
----------------------------------------------------
1 Win_2008_r2-x86_64 running
- centos7 shut off
- centos8 shut off
- centos8-vm2 shut off
- centos8-vm3 shut off
- centos8-vm4 shut off

[root@centos8 ~]# virsh autostart centos8
Domain centos8 marked as autostarted

#设置虚拟机随宿主机启动而自动启动,本质就是在下面目录生成软链接
[root@centos8 ~]# ll /etc/libvirt/qemu/autostart/
total 0
lrwxrwxrwx 1 root root 29 Sep 17 18:53 centos8.xml -> /etc/libvirt/qemu/centos8.xml
lrwxrwxrwx 1 root root 40 Sep 17 09:18 Win_2008_r2-x86_64.xml -> /etc/libvirt/qemu/Win_2008_r2-x86_64.xml

[root@centos8 ~]# virsh list
Id Name State
----------------------------------------------------
1 Win_2008_r2-x86_64 running

[root@centos8 ~]# virsh autostart 1 --disable
Domain 1 unmarked as autostarted

[root@centos8 ~]# ll /etc/libvirt/qemu/autostart/
total 0
lrwxrwxrwx 1 root root 29 Sep 17 18:53 centos8.xml -> /etc/libvirt/qemu/centos8.xml

[root@centos8 ~]# reboot
[root@centos8 ~]# virsh list
Id Name State
----------------------------------------------------
1 centos8 running

在virt-manager工具中也可以配置开机自启动

109

查看虚拟机配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
[root@centos8 ~]# virsh list --all
Id Name State
----------------------------------------------------
2 centos8 running
- centos7 shut off
- centos8-vm2 shut off
- centos8-vm3 shut off
- centos8-vm4 shut off
- Win_2008_r2-x86_64 shut off

#每个虚拟机配置都存放在/etc/libvirt/qemu目录下的xml文件中
[root@centos8 ~]# ls /etc/libvirt/qemu/ -l
total 32
drwxr-xr-x 2 root root 25 Sep 17 18:54 autostart
-rw------- 1 root root 3618 Sep 17 15:14 centos7.xml
-rw------- 1 root root 3673 Sep 13 22:43 centos8-vm2.xml
-rw------- 1 root root 3601 Sep 13 22:42 centos8-vm3.xml
-rw------- 1 root root 3379 Sep 14 00:15 centos8-vm4.xml
-rw------- 1 root root 6024 Sep 17 15:47 centos8.xml
drwx------ 3 root root 42 Sep 13 19:03 networks
-rw------- 1 root root 5369 Sep 17 11:31 Win_2008_r2-x86_64.xml


#查看指定虚拟机的配置,以下命令相当于查看 /etc/libvirt/qemu/centos8.xml
[root@centos8 ~]# virsh dumpxml centos8
......

删除虚拟机配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
[root@centos8 ~]# virsh list --all
Id Name State
----------------------------------------------------
2 centos8 running
- centos7 shut off
- centos8-vm2 shut off
- centos8-vm3 shut off
- centos8-vm4 shut off
- Win_2008_r2-x86_64 shut off

#删除虚拟机配置,但不删除磁盘文件
[root@centos8 ~]# virsh undefine centos8-vm4
Domain centos8-vm4 has been undefined

[root@centos8 ~]# virsh list --all
Id Name State
----------------------------------------------------
2 centos8 running
- centos7 shut off
- centos8-vm2 shut off
- centos8-vm3 shut off
- Win_2008_r2-x86_64 shut off

#对应虚拟机xml的配置文件被删除
[root@centos8 ~]# ll /etc/libvirt/qemu/
total 28
drwxr-xr-x 2 root root 25 Sep 17 18:54 autostart
-rw------- 1 root root 3618 Sep 17 15:14 centos7.xml
-rw------- 1 root root 3673 Sep 13 22:43 centos8-vm2.xml
-rw------- 1 root root 3601 Sep 13 22:42 centos8-vm3.xml
-rw------- 1 root root 6024 Sep 17 15:47 centos8.xml
drwx------ 3 root root 42 Sep 13 19:03 networks
-rw------- 1 root root 5369 Sep 17 11:31 Win_2008_r2-x86_64.xml

#对应的磁盘文件并没有删除
[root@centos8 ~]# ls /var/lib/libvirt/images/
centos7.qcow2 centos8.qcow2 centos8-vm2.qcow2 centos8-vm3.qcow2 centos8-vm4.qcow2 Windows-2008_r2-x86_64.qcow2

#删除虚拟机包括磁盘文件
[root@ubuntu2004 ~]# virsh undefine k8s-node-05 --remove-all-storage
Domain k8s-node-05 has been undefined
Volume 'vda'(/var/lib/libvirt/images/k8s-node-05.qcow2) removed.

迁移虚拟机

将一个宿主机的虚拟机迁移到另一台宿主机,注意: 不支持Ubuntu和Rocky8宿主机之间迁移

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#在一台目标宿主机安装相关虚拟化软件
[root@ubuntu2004 ~]# apt update
[root@ubuntu2004 ~]# apt -y install qemu-kvm virt-manager libvirt-daemon-system

#在源宿主机查看虚拟机的相关文件
[root@ubuntu2004 ~]# virsh dumpxml --domain rocky8-template
......
<disk type='file' device='disk'>
<driver name='qemu' type='qcow2'/>
<source file='/var/lib/libvirt/images/rocky8-template.qcow2'/>
.....

#或者#查看块设备
[root@ubuntu2004 ~]# virsh domblklist rocky8-template
Target Source
------------------------------------------------
vda /var/lib/libvirt/images/rocky8-template.qcow2
vdb -

#复制源宿主机上的虚拟机的两个文件到目标宿主机
[root@ubuntu2004 ~]# scp /etc/libvirt/qemu/rocky8-template.xml 10.0.0.101:/etc/libvirt/qemu/
[root@ubuntu2004 ~]# scp /var/lib/libvirt/images/rocky8-template.qcow2 10.0.0.101:/var/lib/libvirt/images

#在目标宿主机不重启服务无法看到新的虚拟机
[root@ubuntu2004 ~]# virsh list --all
[root@ubuntu2004 ~]# systemctl restart libvirtd

#在目标宿主机重启服务后看到新的虚拟机
[root@ubuntu2004 ~]# virsh list --all
Id Name State
----------------------------------
rocky8-template shut off

存储管理

KVM存储模式

基于文件系统的存储

  • dir: Filesystem Directory 需要有挂载点的文件系统
  • fs: Pre-Formatted Block Device 无需挂载的文件系统,如:位于SAN存储的文件系统,可支持多个主机同时访问,而本地文件系统不支持
  • netfs: Network Exported Directory 网络文件系统,比如:NFS,SAMBA等

基于设备的存储

无需文件系统,性能更好,但可管理性差,无法实现快照

  • Disk: Physical Disk Device
  • Iscsi: isCSI Target
  • logical:LVM Volume Group

虚拟磁盘类型

  • 固定Fixed

    在配置时,指定磁盘大小

    不管在虚拟磁盘上实际存储多少数据,都将占用相同大小宿主机的磁盘空间

  • 动态Dynamic

    初始空间占用小

    随着空间的使用逐渐增长到最大容量,但是只根据需求使用更多的空间

  • 差异Differencing

    因为创建是差异磁盘,所以只保存变更的数据

    例如,将操作系统安装在父盘,然后创建差异化磁盘来执行进一步配置

虚拟镜像文件格式

镜像文件储存在主机文件系统中。它可以储存在本地文件系统中,如 ext4 或 xfs;或网络文件系统中,如 NFS 。例如 libguestfs 这样的工具,能管理、备份及监控文件。KVM 上的磁盘镜像格式包括:

  • raw

    此为默认磁盘格式,但并是一种真正的磁盘格式,而是代表虚拟机所使用的原始镜像,它并不存储元数据,因此可作为保证虚拟机兼容性的候选方案。然而,也正因为它不存储元数据,因此不支持某些高级特往,比如快照和压缩等格式简单,容易转换为其他的格式。

    如果主机文件系统允许,raw 文件可以是预分配(pre-allocated)或 稀疏(sparse)。稀疏文件根据需求分配主机磁盘空间,因此它是一种精简配置形式(thin provisioning)。预分配文件的所有空间需要被预先分配,但它比稀疏文件性能好。当对磁盘 I/O 性能要求非常高,而且通常不需要通过网络传输镜像文件时,可以使用 raw文件

    优点 : 性能好

    缺点 : 空间占用大,功能较少,生产不推荐使用

  • cow : copy-on-write格式,昙花一现

  • qcow : QEMU早期的copy-on-write格式,过渡性方案

  • qcow2

    qcow2 镜像文件提供许多高级磁盘镜像特征,如快照、压缩及加密。它们可以用来代表通过模板镜像创建的虚拟机。因为只有虚拟机写入的扇区部分才会分配在镜像中,所以 qcow2 文件的网络传输效率较高。RHEL 7.0 及更新版本支持 qcow2 v3 镜像文件格式

    按需进行分配磁盘空间,不管文件系统是否支持

    支持快照

    支持zlib的磁盘压缩

    支持AES的加密

    优点 : 空间节约,功能丰富

    缺点 : 性能较差,生产推荐使用

  • vmdk( Virtual Machine Disk ): VMware环境当中默认使用的磁盘格式

  • vhd \ vhdx ( Virtual Hard Disk ):微软默认采用的文件格式

  • vdi : VirtualBox 采用的文件格式

查看支持格式

1
qemu-img --help

范例: 查看KVM支持的磁盘格式

1
2
3
4
[root@centos8 ~]# qemu-img --help|grep Support
Supported formats: blkdebug blkreplay blkverify copy-on-read file ftp ftps
gluster host_cdrom host_device http https iscsi iser luks nbd null-aio null-co
nvme qcow2 quorum raw rbd ssh throttle vhdx vmdk vpc

使用qemu-img管理虚拟磁盘文件

qemu-img 概述

qemu-img 是一个功能强大的磁盘镜像管理工具

查看帮助: qemu-img –help

qemu-img 包括以下子命令

1
2
3
4
5
6
7
8
9
10
11
check          #检查完整性
create #创建镜像
commit #提交更改
compare #比较
convert #转换
info #获得信息
map #映射
snapshot #快照管理
rebase #在已有的镜像的基础上创建新的镜像
resize #调整大小
amend #修订镜像格式选项

创建虚拟磁盘文件

1
qemu-img create [-q] [--object objectdef] [-f fmt] [-b backing_file] [-F backing_fmt] [-u] [-o options] filename [size]

创建默认稀疏格式的磁盘

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#默认为raw格式稀疏文件
[root@centos8 ~]# qemu-img create vm1.img 1g
Formatting 'vm1.img', fmt=raw size=1073741824

[root@centos8 ~]# file vm1.img
vm1.img: data

#显示文件大小
[root@centos8 ~]# ll -h vm1.img
-rw-r--r-- 1 root root 1.0G Sep 20 12:17 vm1.img

#实际文件只占4k空间
[root@centos8 ~]# du -h vm1.img
4.0K vm1.img

#显示文件信息
[root@centos8 ~]# qemu-img info vm1.img
image: vm1.img
file format: raw
virtual size: 1.0G (1073741824 bytes)
disk size: 4.0K

查看不同磁盘文件格式支持选项

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
[root@centos8 ~]# qemu-img create -f raw -o ?
Supported options:
size Virtual disk size

[root@centos8 ~]# qemu-img create -f qcow2 -o ?
Supported options:
size Virtual disk size
compat Compatibility level (0.10 or 1.1)
backing_file File name of a base image
backing_fmt Image format of the base image
encryption Encrypt the image with format 'aes'. (Deprecated in favor of encrypt.format=aes)
encrypt.format Encrypt the image, format choices: 'aes', 'luks'
encrypt.key-secret ID of secret providing qcow AES key or LUKS passphrase
encrypt.cipher-alg Name of encryption cipher algorithm
encrypt.cipher-mode Name of encryption cipher mode
encrypt.ivgen-alg Name of IV generator algorithm
encrypt.ivgen-hash-alg Name of IV generator hash algorithm
encrypt.hash-alg Name of encryption hash algorithm
encrypt.iter-time Time to spend in PBKDF in milliseconds
cluster_size qcow2 cluster size
preallocation Preallocation mode (allowed values: off, metadata, falloc, full)
lazy_refcounts Postpone refcount updates
refcount_bits Width of a reference count entry in bits

qcow2 格式选项

1
2
3
4
5
backing_file          #指定后端镜像文件
backing_fmt #设置后端镜像的镜像格式
cluster_size #设置镜像中的簇大小,取值在512到2M之间,默认值为64K
preallocation #设置镜像文件空间的预分配模式
encryption #用于设置加密

创建raw格式非稀疏文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
[root@centos8 ~]# dd if=/dev/zero of=vm2.img bs=1M count=1024
1024+0 records in
1024+0 records out
1073741824 bytes (1.1 GB, 1.0 GiB) copied, 3.20332 s, 335 MB/s

[root@centos8 ~]# qemu-img info vm2.img
image: vm2.img
file format: raw
virtual size: 1.0G (1073741824 bytes)
disk size: 1.0G

[root@centos8 ~]# ls -hl vm2.img
-rw-r--r-- 1 root root 1.0G Sep 20 12:31 vm2.img

[root@centos8 ~]# du -h vm2.img
1.0G vm2.img

创建raw格式稀疏文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
[root@centos8 ~]# dd if=/dev/zero of=vm3.img bs=1M count=0 seek=1024
0+0 records in
0+0 records out
0 bytes copied, 9.2173e-05 s, 0.0 kB/s

[root@centos8 ~]# qemu-img info vm3.img
image: vm3.img
file format: raw
virtual size: 1.0G (1073741824 bytes)
disk size: 0

[root@centos8 ~]# ll -h vm3.img
-rw-r--r-- 1 root root 1.0G Sep 20 12:34 vm3.img

[root@centos8 ~]# du -h vm3.img
0 vm3.img

raw文件复制的格式控制

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#复制非稀疏文件,默认也为非稀疏文件
[root@centos8 ~]# cp vm2.img vm2.img.bak
[root@centos8 ~]# du -h vm2.img.bak
1.0G vm2.img.bak

[root@centos8 ~]# ll -h vm2.img.bak
-rw-r--r-- 1 root root 1.0G Sep 20 12:38 vm2.img.bak

[root@centos8 ~]# qemu-img info vm2.img.bak
image: vm2.img.bak
file format: raw
virtual size: 1.0G (1073741824 bytes)
disk size: 1.0G

#复制稀疏文件,默认仍为稀疏文件
[root@centos8 ~]# cp vm3.img vm3.img.bak
[root@centos8 ~]# ll -h vm3.img.bak
-rw-r--r-- 1 root root 1.0G Sep 20 12:36 vm3.img.bak

[root@centos8 ~]# du -h vm3.img.bak
0 vm3.img.bak

[root@centos8 ~]# qemu-img info vm3.img.bak
image: vm3.img.bak
file format: raw
virtual size: 1.0G (1073741824 bytes)
disk size: 0

#指定将非稀疏文件复制为稀疏格式格式
[root@centos8 ~]# cp --sparse=always vm2.img vm2.img.bak2
[root@centos8 ~]# qemu-img info vm2.img
image: vm2.img
file format: raw
virtual size: 1.0G (1073741824 bytes)
disk size: 1.0G

[root@centos8 ~]# qemu-img info vm2.img.bak2
image: vm2.img.bak2
file format: raw
virtual size: 1.0G (1073741824 bytes)
disk size: 0

#指定将稀疏文件复制为非稀疏格式格式
[root@centos8 ~]# cp --sparse=never vm3.img vm3.img.bak2
[root@centos8 ~]# qemu-img info vm3.img
image: vm3.img
file format: raw
virtual size: 1.0G (1073741824 bytes)
disk size: 0

[root@centos8 ~]# qemu-img info vm3.img.bak2
image: vm3.img.bak2
file format: raw
virtual size: 1.0G (1073741824 bytes)
disk size: 1.0G

检查虚拟磁盘

对于关机状态的虚拟机磁盘,可以检查文件错误

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
[root@centos8 ~]# virsh list
Id Name State
----------------------------------------------------
2 centos8 running

[root@centos8 ~]# qemu-img check /var/lib/libvirt/images/centos8.qcow2
qemu-img: Could not open '/var/lib/libvirt/images/centos8.qcow2': Failed to get shared "write" lock
Is another process using the image [/var/lib/libvirt/images/centos8.qcow2]?

[root@centos8 ~]# virsh suspend centos8
Domain centos8 suspended

[root@centos8 ~]# virsh list
Id Name State
----------------------------------------------------
2 centos8 paused

[root@centos8 ~]# qemu-img check /var/lib/libvirt/images/centos8.qcow2
qemu-img: Could not open '/var/lib/libvirt/images/centos8.qcow2': Failed to get shared "write" lock
Is another process using the image [/var/lib/libvirt/images/centos8.qcow2]?

[root@centos8 ~]# qemu-img check /var/lib/libvirt/images/centos7.qcow2
No errors were found on the image.
25572/327680 = 7.80% allocated, 1.44% fragmented, 0.00% compressed clusters
Image end offset: 1676869632

磁盘预分配策略

raw 文件的预分配策略和文件系统是否支持有关,而qcow2则无关

预分配策略

  • off

    此为缺省策略,即不使用预分配策略,预分配后的虚拟磁盘占用空间很小,不属于稀疏映像类型

    生成的磁盘文件占用空间很小

  • metadata

    只预分配元数据(metadata),预分配后的磁盘文件属于稀疏映像类型,相当于vmware中的磁盘置备

    选项: Thin Provision(精简配置)

    生成的磁盘文件为稀疏格式,实际占用的空间比off策略稍大一些

  • falloc

    分配文件的块并标识它们的状态为未初始化,即只分配空间,但不置零. 预分配后的虚拟磁盘属于非稀疏映像类型,相对full模式来说,创建虚拟磁盘的速度要快很多,相当于vmware中的磁盘置备选项: 厚置备延迟置零

    生成的磁盘文件实际占用的空间和分配的空间相同大小

  • full

    分配所有磁盘空间并置零,预分配后的虚拟磁盘属于非稀疏映像类型,创建最慢,相当于vmware中的磁盘置备选项: 厚置备置零

    生成的磁盘文件实际占用的空间和分配的空间相同大小

范例: 创建预分配置策略

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
[root@centos8 ~]# qemu-img create -f qcow2 test1.qcow2 1g
Formatting 'test1.qcow2', fmt=qcow2 size=1073741824 cluster_size=65536
lazy_refcounts=off refcount_bits=16

[root@centos8 ~]# qemu-img info test1.qcow2
image: test1.qcow2
file format: qcow2
virtual size: 1.0G (1073741824 bytes)
disk size: 196K
cluster_size: 65536
Format specific information:
compat: 1.1
lazy refcounts: false
refcount bits: 16
corrupt: false

#指定关闭预分配
[root@centos8 ~]# qemu-img create -f qcow2 test2.qcow2 1g -o preallocation=off
Formatting 'test2.qcow2', fmt=qcow2 size=1073741824 cluster_size=65536
preallocation=off lazy_refcounts=off refcount_bits=16

[root@centos8 ~]# qemu-img info test2.qcow2
image: test2.qcow2
file format: qcow2
virtual size: 1.0G (1073741824 bytes)
disk size: 196K
cluster_size: 65536
Format specific information:
compat: 1.1
lazy refcounts: false
refcount bits: 16
corrupt: false

#指定预分配metadata
[root@centos8 ~]# qemu-img create -f qcow2 test3.qcow2 1g -o preallocation=metadata
Formatting 'test3.qcow2', fmt=qcow2 size=1073741824 cluster_size=65536
preallocation=metadata lazy_refcounts=off refcount_bits=16

[root@centos8 ~]# qemu-img info test3.qcow2
image: test3.qcow2
file format: qcow2
virtual size: 1.0G (1073741824 bytes)
disk size: 836K
cluster_size: 65536
Format specific information:
compat: 1.1
lazy refcounts: false
refcount bits: 16
corrupt: false

#指定预分配falloc
[root@centos8 ~]# qemu-img create -f qcow2 test4.qcow2 1g -o preallocation=falloc
Formatting 'test4.qcow2', fmt=qcow2 size=1073741824 cluster_size=65536
preallocation=falloc lazy_refcounts=off refcount_bits=16

[root@centos8 ~]# qemu-img info test4.qcow2
image: test4.qcow2
file format: qcow2
virtual size: 1.0G (1073741824 bytes)
disk size: 1.0G
cluster_size: 65536
Format specific information:
compat: 1.1
lazy refcounts: false
refcount bits: 16
corrupt: false

#指定预分配full
[root@centos8 ~]# qemu-img create -f qcow2 test5.qcow2 1g -o preallocation=full
Formatting 'test5.qcow2', fmt=qcow2 size=1073741824 cluster_size=65536
preallocation=full lazy_refcounts=off refcount_bits=16

[root@centos8 ~]# qemu-img info test5.qcow2
image: test5.qcow2
file format: qcow2
virtual size: 1.0G (1073741824 bytes)
disk size: 1.0G
cluster_size: 65536
Format specific information:
compat: 1.1
lazy refcounts: false
refcount bits: 16
corrupt: false

#文件系统显示大小
[root@centos8 ~]# ll -h test*.qcow2
-rw-r--r-- 1 root root 193K Sep 20 13:31 test1.qcow2
-rw-r--r-- 1 root root 193K Sep 20 13:32 test2.qcow2
-rw-r--r-- 1 root root 1.1G Sep 20 13:35 test3.qcow2
-rw-r--r-- 1 root root 1.1G Sep 20 13:36 test4.qcow2
-rw-r--r-- 1 root root 1.1G Sep 20 13:37 test5.qcow2

#查看真实大小
[root@centos8 ~]# du -h test*.qcow2
196K test1.qcow2
196K test2.qcow2
836K test3.qcow2
1.1G test4.qcow2
1.1G test5.qcow2

虚拟磁盘格式转换

qemu-img 可以将不同格式的虚拟磁盘文件进行格式转化

语法格式

1
2
3
4
qemu-img convert [--object objectdef] [--image-opts] [--target-image-opts] [-U] 
[-C] [-c] [-p] [-q] [-n] [-f fmt] [-t cache] [-T src_cache] [-O output_fmt] [-B
backing_file] [-o options] [-s snapshot_id_or_name] [-l snapshot_param] [-S
sparse_size] [-m num_coroutines] [-W] filename [filename2 [...]] output_filename

范例: 将vmdk转化为raw 和qcow2格式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
[root@centos8 ~]# qemu-img info CentOS8.2.vmdk
image: CentOS8.2.vmdk
file format: vmdk
virtual size: 200G (214748364800 bytes)
disk size: 1.6G
cluster_size: 65536
Format specific information:
cid: 2898578192
parent cid: 4294967295
create type: monolithicSparse
extents:
[0]:
virtual size: 214748364800
filename: CentOS8.2.vmdk
cluster size: 65536
format:

#默认转化为raw格式
[root@centos8 ~]# qemu-img convert CentOS8.2.vmdk CentOS8.2.img

#比较大小
[root@centos8 ~]# ll -h CentOS8.2.vmdk CentOS8.2.img
-rw-r--r-- 1 root root 1.6G Sep 20 16:00 CentOS8.2.vmdk
-rw-r--r-- 1 root root 200G Sep 20 16:10 CentOS8.2.img

[root@centos8 ~]# du -h CentOS8.2.vmdk CentOS8.2.img
1.6G CentOS8.2.vmdk
1.5G CentOS8.2.img

[root@centos8 ~]# qemu-img info CentOS8.2.img
image: CentOS8.2.img
file format: raw
virtual size: 200G (214748364800 bytes)
disk size: 1.4G

[root@centos8 ~]# mv CentOS8.2.img /var/lib/libvirt/images/
[root@centos8 ~]# virt-install --import --name=centos8-test2 --vcpus=1 --ram=2048 \
--disk bus=scsi,path=/var/lib/libvirt/images/CentOS8.2.img --network \
network=default --graphics vnc,listen=0.0.0.0 --os-type=Linux --os-variant=centos8 --noautoconsole --boot hd

#转化为qcow2格式
[root@centos8 ~]# qemu-img convert -f vmdk -O qcow2 CentOS8.2.vmdk
CentOS8.2.qcow2

#比较大小
[root@centos8 ~]# ll -h CentOS8.2.vmdk CentOS8.2.qcow2
-rw-r--r-- 1 root root 1.6G Sep 20 16:00 CentOS8.2.vmdk
-rw-r--r-- 1 root root 1.6G Sep 20 16:12 CentOS8.2.qcow2

[root@centos8 ~]# du -h CentOS8.2.vmdk CentOS8.2.qcow2
1.6G CentOS8.2.vmdk
1.6G CentOS8.2.qcow2

[root@centos8 ~]# qemu-img info CentOS8.2.qcow2
image: CentOS8.2.qcow2
file format: qcow2
virtual size: 200G (214748364800 bytes)
disk size: 1.5G
cluster_size: 65536
Format specific information:
compat: 1.1
lazy refcounts: false
refcount bits: 16
corrupt: false

[root@centos8 ~]# mv CentOS8.2.qcow2 /var/lib/libvirt/images/
[root@centos8 ~]# virt-install --import --name=centos8-test3 --vcpus=1 --ram=2048 \
--disk bus=scsi,path=/var/lib/libvirt/images/CentOS8.2.qcow2 --network \
network=default --graphics vnc,listen=0.0.0.0 --os-type=Linux --os-variant=centos8 --noautoconsole --boot hd

调整虚拟磁盘大小

虚拟磁盘文件创建后,还可以调整虚拟磁盘大小

语法格式

1
qemu-img resize [--shrink] filename [+l -]size
  • 操作之前,一定要做好数据备份
  • 增加文件大小后,需要在客户机中使用fdisk、parted等分区工具进行相应的操作才能真正让客户机使用到增加后的镜像空间。
  • 缩小镜像之前,要在客户机中保证里面的文件系统有空余空间,否则会数据丢失。另外xfs文件系统不支持缩减
  • qcow2不支持缩小镜像的操作

范例: 扩展虚拟磁盘

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
[root@centos8 ~]# qemu-img info /var/lib/libvirt/images/centos8.qcow2 
image: /var/lib/libvirt/images/centos8.qcow2
file format: qcow2
virtual size: 20G (21474836480 bytes)
disk size: 20G
cluster_size: 65536
Format specific information:
compat: 1.1
lazy refcounts: true
refcount bits: 16
corrupt: false

#增加10G空间
[root@centos8 ~]# qemu-img resize /var/lib/libvirt/images/centos8.qcow2 +10G
Image resized.
[root@centos8 ~]# qemu-img info /var/lib/libvirt/images/centos8.qcow2
image: /var/lib/libvirt/images/centos8.qcow2
file format: qcow2
virtual size: 30G (32212254720 bytes)
disk size: 20G
cluster_size: 65536
Format specific information:
compat: 1.1
lazy refcounts: true
refcount bits: 16
corrupt: false

#启动虚拟机后,还需要使用fdisk等工具进行空间的继续管理才能使用

110

范例: 缩减虚拟磁盘

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
[root@centos8 images]# qemu-img info centos7.qcow2
image: centos7.qcow2
file format: qcow2
virtual size: 20G (21474836480 bytes)
disk size: 1.6G
cluster_size: 65536
Format specific information:
compat: 1.1
lazy refcounts: false
refcount bits: 16
corrupt: false

[root@centos8 images]# qemu-img resize --shrink
/var/lib/libvirt/images/centos7.qcow2 -2G
Image resized.

[root@centos8 images]# qemu-img info centos7.qcow2
image: centos7.qcow2
file format: qcow2
virtual size: 18G (19327352832 bytes)
disk size: 1.6G
cluster_size: 65536
Format specific information:
compat: 1.1
lazy refcounts: false
refcount bits: 16
corrupt: false

磁盘快照管理

快照Snapshot介绍

磁盘快照,对磁盘数据进行快照,主要用于虚拟机备份等场合

磁盘快照分类

  • 按快照信息保存分为:

    内置快照∶快照数据和base磁盘数据放在同一个qcow2文件中

    外置快照︰快照数据单独的另一个qcow2文件存放

  • 按虚拟机状态可以分为:

    关机态快照︰数据可以保证一致性

    运行态快照∶数据无法保证一致性,类似与系统crash后的磁盘数据。使用是可能需要fsck等操作。

  • 按磁盘数量可以分为:

    单盘:单盘快照不涉及原子性

    多盘:涉及原子性。主要分两个方面:1.是所有盘快照点相同2.所有盘要么都快照成功,要么都快照失败。主要依赖于qemu的transaction实现

qemu-img 管理磁盘快照

命令格式

1
2
3
4
5
6
7
qemu-img snapshot [--object objectdef] [--image-opts] [-U] [-q] [-l | -a snapshot | -c snapshot | -d snapshot] filename

snapshot is the name of the snapshot to create, apply or delete
-a applies a snapshot (revert disk to saved state)
-c creates a snapshot
-d deletes a snapshot
-l lists all snapshots in the given image

范例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#查看块设备
[root@centos8 ~]# virsh domblklist centos7
Target Source
------------------------------------------------
hda /var/lib/libvirt/images/centos7.qcow2
hdb -

#查看快照,如果没有快照,则无显示信息
[root@centos8 ~]# qemu-img snapshot -l /var/lib/libvirt/images/centos7.qcow2

#创建快照
[root@centos8 ~]# qemu-img snapshot -c centos7-s1 /var/lib/libvirt/images/centos7.qcow2

#查看快照
[root@centos8 ~]# qemu-img snapshot -l /var/lib/libvirt/images/centos7.qcow2
Snapshot list:
ID TAG VM SIZE DATE VM CLOCK
1 centos7-s1 0 2020-09-20 17:39:59 00:00:00.000

#查看快照信息
[root@centos8 ~]# qemu-img info /var/lib/libvirt/images/centos7.qcow2
image: /var/lib/libvirt/images/centos7.qcow2
file format: qcow2
virtual size: 20G (21474836480 bytes)
disk size: 1.6G
cluster_size: 65536
Snapshot list:
ID TAG VM SIZE DATE VM CLOCK
1 centos7-s1 0 2020-09-20 17:39:59 00:00:00.000
Format specific information:
compat: 1.1
lazy refcounts: false
refcount bits: 16
corrupt: false

#删除文件,模拟破坏

111

1
2
3
#关机后才能还原快照修复故障
[root@centos8 ~]# qemu-img snapshot -a centos7-s1
/var/lib/libvirt/images/centos7.qcow2

查看文件恢复

112

1
2
3
#关机后才能删除快照
[root@centos8 ~]# qemu-img snapshot -d centos7-s1 /var/lib/libvirt/images/centos7.qcow2
[root@centos8 ~]# qemu-img snapshot -l /var/lib/libvirt/images/centos7.qcow2

virsh 管理虚拟机快照

1
2
3
4
5
6
7
8
9
10
11
12
[root@centos8 ~]# virsh snapshot-list centos8
Name Creation Time State
------------------------------------------------------------

#创建虚拟机快照
[root@centos8 ~]# virsh snapshot-create centos8
Domain snapshot 1600593611 created

[root@centos8 ~]# virsh snapshot-list centos8
Name Creation Time State
------------------------------------------------------------
1600593611 2020-09-20 17:20:11 +0800 shutoff

113

使用virsh 命令还原快照

1
2
3
4
5
6
7
8
9
10
[root@centos8 ~]# virsh list
Id Name State
----------------------------------------------------

#无需关机,即可还原快照
[root@centos8 ~]# virsh snapshot-revert centos8 --snapshotname 1600593611 --running
[root@centos8 ~]# virsh list
Id Name State
----------------------------------------------------
23 centos7 running

114

1
2
3
4
5
6
7
#删除快照
[root@centos8 ~]# virsh snapshot-delete centos8 --snapshotname 1600593611
Domain snapshot 1600593611 deleted

[root@centos8 ~]# virsh snapshot-list centos8
Name Creation Time State
------------------------------------------------------------

网络管理

官方文档:

1
https://wiki.libvirt.org/page/VirtualNetworking

Linux 网桥实现

范例: Ubuntu 配置网桥

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
root@ubuntu1804:~# apt install -y bridge-utils
root@ubuntu1804:~# dpkg -L bridge-utils
/sbin/brctl
......
#三个网卡配置使用一个配置文件
root@ubuntu1804:~# cat /etc/netplan/01-netcfg.yaml
# This file describes the network interfaces available on your system
# For more information, see netplan(5).
network:
version: 2
renderer: networkd
ethernets:
eth0:
dhcp4: yes
eth1:
dhcp4: no
dhcp6: no
eth2:
dhcp4: no
bridges:
br0:
dhcp4: no
dhcp6: no
addresses: [10.0.0.18/16]
gateway4: 10.0.0.2
nameservers:
addresses: [223.6.6.6]
interfaces:
- eth1
- eth2

#桥接配置单独一个文件
[root@ubuntu1804 netplan]#cat br0.yaml
network:
version: 2
renderer: networkd
ethernets:
eth1:
dhcp4: no
dhcp6: no
eth2:
dhcp4: no
bridges:
br0:
dhcp4: no
dhcp6: no
addresses: [10.0.0.10/16]
gateway4: 10.0.0.2
nameservers:
addresses: [223.6.6.6]
interfaces:
- eth1
- eth2

root@ubuntu1804:~# netplan apply
root@ubuntu1804:~# ifconfig br0
br0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500
inet 10.0.0.18 netmask 255.255.0.0 broadcast 10.0.255.255
inet6 fe80::9cbe:1dff:fe85:6601 prefixlen 64 scopeid 0x20<link>
ether 9e:be:1d:85:66:01 txqueuelen 1000 (Ethernet)
RX packets 158 bytes 19534 (19.5 KB)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 10 bytes 796 (796.0 B)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0

root@ubuntu1804:~# brctl show
bridge name bridge id STP enabled interfaces
br0 8000.9ebe1d856601 no eth1
eth2

范例: CentOS 配置网桥

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#创建网桥
nmcli con add type bridge con-name br0 ifname br0
nmcli connection modify br0 ipv4.addresses 10.0.0.100/24 ipv4.method manual
nmcli con up br0

#加入物理网卡
nmcli con add type bridge-slave con-name br0-port0 ifname eth0 master br0
nmcli con add type bridge-slave con-name br0-port1 ifname eth1 master br0
nmcli con up br0-port0
nmcli con up br0-port1

#查看网桥配置文件
cat /etc/sysconfig/network-scripts/ifcfg-br0
DEVICE=br0
NAME=br0
STP=yes
TYPE=Bridge
BOOTPROTO=static
IPADDR=10.0.0.100
PREFIX=24


cat /etc/sysconfig/network-scripts/ifcfg-br0-port0
TYPE=Ethernet
NAME=br0-port0
DEVICE=eth0
ONBOOT=yes
BRIDGE=br0
UUID=23f41d3b-b57c-4e26-9b17-d5f02dafd12d


#安装管理软件包,注意:CentOS8取消了此包
yum install bridge-utils

#查看网桥
brctl show
ip link show master br0
bridge link show

#删除br0
nmcli con down br0
rm /etc/sysconfig/network-scripts/ifcfg-br0*
nmcli con reload

qemu-kvm支持的网络

虚拟机的网络模式:

  • 基于NAT ( Network Addresss Translation)的虚拟网络,此为virt-install的默认模式
  • 基于自定义网桥(Bridge )的虚拟网络
  • 用户自定义的隔离的虚拟网络
  • 直接分配物理网络设备(包括VT-d和SR-IOV),性能最好

虚拟机的网卡设备:

  • RTL8139、e1000、….
  • virtio 生产建议使用

注意: 桥接物理网卡,会自动生成macvtap网卡,并且会导致本宿主机无法访问虚拟机,但其它物理机可以访问当前宿主机上面的虚拟机

范例: 查看qemu-kvm支持的网卡型号

1
2
3
#Ubuntu20.04没有此命令
[root@centos8 ~]# /usr/libexec/qemu-kvm -net nic,model=?
qemu: Supported NIC models: e1000,e1000-82540em,e1000e,rtl8139,virtio-net-pci

默认的网络配置NAT模式

默认网络连接的架构图

默认虚拟机网络配置为NAT模式,相当于vmware的NAT模式的Vmnet8

115

宿主机默认网络相关服务和信息

默认宿主机安装dnsmasq包指供DHCP服务

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#Ubuntu20.04
[root@ubuntu2004 ~]# dpkg -l dnsmasq-base
Desired=Unknown/Install/Remove/Purge/Hold
| Status=Not/Inst/Conf-files/Unpacked/halF-conf/Half-inst/trig-aWait/Trig-pend
|/ Err?=(none)/Reinst-required (Status,Err: uppercase=bad)
||/ Name Version Architecture Description
+++-==============-=================-============-
============================================
ii dnsmasq-base 2.80-1.1ubuntu1.5 amd64 Small caching DNS proxy and DHCP/TFTP server

[root@ubuntu2004 ~]# systemctl status libvirtd
● libvirtd.service - Virtualization daemon
Loaded: loaded (/lib/systemd/system/libvirtd.service; enabled; vendor
preset: enabled)
Active: active (running) since Fri 2022-10-14 08:28:10 CST; 7min ago
TriggeredBy: ● libvirtd-admin.socket
● libvirtd.socket
● libvirtd-ro.socket
Docs: man:libvirtd(8)
https://libvirt.org
Main PID: 909 (libvirtd)
Tasks: 20 (limit: 32768)
Memory: 50.7M
CGroup: /system.slice/libvirtd.service
├─ 909 /usr/sbin/libvirtd
├─1034 /usr/sbin/dnsmasq --conf-file=/var/lib/libvirt/dnsmasq/default.conf --leasefile-ro --dhcp-script=/usr/lib/libvirt/libvirt_leaseshelper
└─1035 /usr/sbin/dnsmasq --conf-file=/var/lib/libvirt/dnsmasq/default.conf --leasefile-ro --dhcp-script=/usr/lib/libvirt/libvirt_leaseshelpe

[root@ubuntu2004 ~]# cat /var/lib/libvirt/dnsmasq/default.conf
##WARNING: THIS IS AN AUTO-GENERATED FILE. CHANGES TO IT ARE LIKELY TO BE
##OVERWRITTEN AND LOST. Changes to this configuration should be made using:
## virsh net-edit default
## or other application using the libvirt API.
##
## dnsmasq conf file created by libvirt
strict-order
user=libvirt-dnsmasq
pid-file=/run/libvirt/network/default.pid
except-interface=lo
bind-dynamic
interface=virbr0
dhcp-range=192.168.122.2,192.168.122.254,255.255.255.0
dhcp-no-override
dhcp-authoritative
dhcp-lease-max=253
dhcp-hostsfile=/var/lib/libvirt/dnsmasq/default.hostsfile
addn-hosts=/var/lib/libvirt/dnsmasq/default.addnhosts

#CentOS
[root@centos8 ~]# rpm -q dnsmasq
dnsmasq-2.79-11.el8.x86_64

[root@centos8 ~]# cat /var/lib/libvirt/dnsmasq/default.conf
##WARNING: THIS IS AN AUTO-GENERATED FILE. CHANGES TO IT ARE LIKELY TO BE
##OVERWRITTEN AND LOST. Changes to this configuration should be made using:
## virsh net-edit default
## or other application using the libvirt API.
##
## dnsmasq conf file created by libvirt
strict-order
pid-file=/var/run/libvirt/network/default.pid
except-interface=lo
bind-dynamic
interface=virbr0
dhcp-range=192.168.122.2,192.168.122.254
dhcp-no-override
dhcp-authoritative
dhcp-lease-max=253
dhcp-hostsfile=/var/lib/libvirt/dnsmasq/default.hostsfile
addn-hosts=/var/lib/libvirt/dnsmasq/default.addnhosts

范例:查看宿主机的网桥信息

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
[root@ubuntu2004 ~]# virsh list
Id Name State
---------------------------
1 centos7.9 running
2 Win2008-2 running

[root@ubuntu2004 ~]# 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: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc fq_codel state UP
group default qlen 1000
link/ether 00:0c:29:90:c0:f3 brd ff:ff:ff:ff:ff:ff
inet 10.0.0.100/24 brd 10.0.0.255 scope global eth0
valid_lft forever preferred_lft forever
inet6 fe80::20c:29ff:fe90:c0f3/64 scope link
valid_lft forever preferred_lft forever
3: virbr0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP
group default qlen 1000
link/ether 52:54:00:b3:39:58 brd ff:ff:ff:ff:ff:ff
inet 192.168.122.1/24 brd 192.168.122.255 scope global virbr0
valid_lft forever preferred_lft forever
4: virbr0-nic: <BROADCAST,MULTICAST> mtu 1500 qdisc fq_codel master virbr0 state
DOWN group default qlen 1000
link/ether 52:54:00:b3:39:58 brd ff:ff:ff:ff:ff:ff
5: vnet0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc fq_codel master
virbr0 state UNKNOWN group default qlen 1000
link/ether fe:54:00:a7:80:b7 brd ff:ff:ff:ff:ff:ff
inet6 fe80::fc54:ff:fea7:80b7/64 scope link
valid_lft forever preferred_lft forever
6: vnet1: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc fq_codel master
virbr0 state UNKNOWN group default qlen 1000
link/ether fe:54:00:64:13:db brd ff:ff:ff:ff:ff:ff
inet6 fe80::fc54:ff:fe64:13db/64 scope link
valid_lft forever preferred_lft forever

[root@ubuntu2004 ~]# apt -y install bridge-utils

#查看桥接信息
[root@ubuntu2004 ~]# brctl show
bridge name bridge id STP enabled interfaces
virbr0 8000.525400b33958 yes virbr0-nic
vnet0
vnet1

#查看virbr0网络的情况
[root@ubuntu2004 ~]# ip link show master virbr0
4: virbr0-nic: <BROADCAST,MULTICAST> mtu 1500 qdisc fq_codel master virbr0 state
DOWN mode DEFAULT group default qlen 1000
link/ether 52:54:00:b3:39:58 brd ff:ff:ff:ff:ff:ff
5: vnet0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc fq_codel master
virbr0 state UNKNOWN mode DEFAULT group default qlen 1000
link/ether fe:54:00:a7:80:b7 brd ff:ff:ff:ff:ff:ff
6: vnet1: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc fq_codel master
virbr0 state UNKNOWN mode DEFAULT group default qlen 1000
link/ether fe:54:00:64:13:db brd ff:ff:ff:ff:ff:ff

#查看所有桥接网卡信息及对应网桥
[root@ubuntu2004 ~]# bridge link show
4: virbr0-nic: <BROADCAST,MULTICAST> mtu 1500 master virbr0 state disabled
priority 32 cost 100
5: vnet0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 master virbr0 state
forwarding priority 32 cost 100
6: vnet1: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 master virbr0 state
forwarding priority 32 cost 100

范例: 查看宿主机的网桥信息

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
[root@centos8 ~]# virsh list --all
Id Name State
----------------------------------------------------
- centos7 shut off
- centos7-2 shut off
- centos8 shut off
- Win_2008_r2-x86_64 shut off

[root@centos8 ~]# 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: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc fq_codel state UP
group default qlen 1000
link/ether 00:0c:29:44:c3:fe brd ff:ff:ff:ff:ff:ff
inet 10.0.0.8/24 brd 10.0.0.255 scope global noprefixroute eth0
valid_lft forever preferred_lft forever
inet6 fe80::20c:29ff:fe44:c3fe/64 scope link
valid_lft forever preferred_lft forever
3: virbr0: <NO-CARRIER,BROADCAST,MULTICAST,UP> mtu 1500 qdisc noqueue state DOWN
group default qlen 1000
link/ether 52:54:00:52:f2:5c brd ff:ff:ff:ff:ff:ff
inet 192.168.122.1/24 brd 192.168.122.255 scope global virbr0
valid_lft forever preferred_lft forever
4: virbr0-nic: <BROADCAST,MULTICAST> mtu 1500 qdisc fq_codel master virbr0 state
DOWN group default qlen 1000
link/ether 52:54:00:52:f2:5c brd ff:ff:ff:ff:ff:ff

[root@centos8 ~]# virsh list
Id Name State
----------------------------------------------------
2 centos7 running
3 centos8 running

[root@centos8 ~]# virsh start centos7
Domain centos7 started

[root@centos8 ~]# virsh start centos8
Domain centos8 started

[root@centos8 ~]# 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: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc fq_codel state UP
group default qlen 1000
link/ether 00:0c:29:44:c3:fe brd ff:ff:ff:ff:ff:ff
inet 10.0.0.8/24 brd 10.0.0.255 scope global noprefixroute eth0
valid_lft forever preferred_lft forever
inet6 fe80::20c:29ff:fe44:c3fe/64 scope link
valid_lft forever preferred_lft forever
3: virbr0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP
group default qlen 1000
link/ether 52:54:00:52:f2:5c brd ff:ff:ff:ff:ff:ff
inet 192.168.122.1/24 brd 192.168.122.255 scope global virbr0
valid_lft forever preferred_lft forever
4: virbr0-nic: <BROADCAST,MULTICAST> mtu 1500 qdisc fq_codel master virbr0 state
DOWN group default qlen 1000
link/ether 52:54:00:52:f2:5c brd ff:ff:ff:ff:ff:ff
6: vnet0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc fq_codel master
virbr0 state UNKNOWN group default qlen 1000
link/ether fe:54:00:95:25:fb brd ff:ff:ff:ff:ff:ff
inet6 fe80::fc54:ff:fe95:25fb/64 scope link
valid_lft forever preferred_lft forever
7: vnet1: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc fq_codel master
virbr0 state UNKNOWN group default qlen 1000
link/ether fe:54:00:83:9d:51 brd ff:ff:ff:ff:ff:ff
inet6 fe80::fc54:ff:fe83:9d51/64 scope link
valid_lft forever preferred_lft forever

#查看virbr0网络的情况
[root@centos8 ~]# ip link show master virbr0
4: virbr0-nic: <BROADCAST,MULTICAST> mtu 1500 qdisc fq_codel master virbr0 state
DOWN mode DEFAULT group default qlen 1000
link/ether 52:54:00:52:f2:5c brd ff:ff:ff:ff:ff:ff
8: vnet0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc fq_codel master
virbr0 state UNKNOWN mode DEFAULT group default qlen 1000
link/ether fe:54:00:95:25:fb brd ff:ff:ff:ff:ff:ff
9: vnet1: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc fq_codel master
virbr0 state UNKNOWN mode DEFAULT group default qlen 1000
link/ether fe:54:00:83:9d:51 brd ff:ff:ff:ff:ff:ff

#查看所有桥接网卡信息及对应网桥
[root@centos8 ~]# bridge link show
4: virbr0-nic: <BROADCAST,MULTICAST> mtu 1500 master virbr0 state disabled
priority 32 cost 100
8: vnet0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 master virbr0 state
forwarding priority 32 cost 100
9: vnet1: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 master virbr0 state
forwarding priority 32 cost 100

[root@centos8 ~]# nmtui

116
117
118
119
120

121

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
[root@centos8 ~]# virsh net-list
Name State Autostart Persistent
----------------------------------------------------------
default active yes yes

[root@centos8 ~]# cat /etc/libvirt/qemu/networks/default.xml
<network>
<name>default</name>
<uuid>5962db15-2851-4825-b516-9bc2eb4d9ee0</uuid>
<forward mode='nat'/>
<bridge name='virbr0' stp='on' delay='0'/>
<mac address='52:54:00:52:f2:5c'/>
<ip address='192.168.122.1' netmask='255.255.255.0'>
<dhcp>
<range start='192.168.122.2' end='192.168.122.254'/>
</dhcp>
</ip>
</network>

[root@centos8 ~]# virsh net-dumpxml default
<network connections='1'>
<name>default</name>
<uuid>5962db15-2851-4825-b516-9bc2eb4d9ee0</uuid>
<forward mode='nat'>
<nat>
<port start='1024' end='65535'/>
</nat>
</forward>
<bridge name='virbr0' stp='on' delay='0'/>
<mac address='52:54:00:52:f2:5c'/>
<ip address='192.168.122.1' netmask='255.255.255.0'>
<dhcp>
<range start='192.168.122.2' end='192.168.122.254'/>
</dhcp>
</ip>
</network>

#查看NAT策略实现从虚拟机可以访问外部网络,反之不通,此策略由libvirtd服务启动时自动加载到NAT表
[root@centos8 ~]# iptables -vnL -t nat
Chain PREROUTING (policy ACCEPT 0 packets, 0 bytes)
pkts bytes target prot opt in out source destination
Chain INPUT (policy ACCEPT 0 packets, 0 bytes)
pkts bytes target prot opt in out source destination
Chain POSTROUTING (policy ACCEPT 0 packets, 0 bytes)
pkts bytes target prot opt in out source destination
0 0 RETURN all -- * * 192.168.122.0/24 224.0.0.0/24
0 0 RETURN all -- * * 192.168.122.0/24 255.255.255.255
0 0 MASQUERADE tcp -- * * 192.168.122.0/24 !192.168.122.0/24 masq ports: 1024-65535
8 608 MASQUERADE udp -- * * 192.168.122.0/24 !192.168.122.0/24 masq ports: 1024-65535
1 84 MASQUERADE all -- * * 192.168.122.0/24 !192.168.122.0/24
Chain OUTPUT (policy ACCEPT 0 packets, 0 bytes)
pkts bytes target prot opt in out source destination

虚拟机网卡默认设置

Ubutun20.04的虚拟机默认网卡设置

122

Rocky8的虚拟机默认网卡设置

123
124
125
126
127

1
2
3
4
5
6
7
8
9
[root@centos8 ~]# virsh dumpxml centos7 |sed -n '/interface/,/interface/p' 
<interface type='network'>
<mac address='52:54:00:95:25:fb'/>
<source network='default' bridge='virbr0'/>
<target dev='vnet0'/>
<model type='virtio'/>
<alias name='net0'/>
<address type='pci' domain='0x0000' bus='0x00' slot='0x03' function='0x0'/>
</interface>

virsh 查看虚拟机网络配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#查看虚拟机的网卡配置
[root@centos8 ~]# virsh domiflist centos8
Interface Type Source Model MAC
-------------------------------------------------------
vnet0 network default virtio 52:54:00:83:9d:51

#查看虚拟机的网卡地址信息
[root@centos8 ~]# virsh domifaddr centos8
Name MAC address Protocol Address
-------------------------------------------------------------------------------
vnet0 52:54:00:83:9d:51 ipv4 192.168.122.94/24

#查看虚拟机的指定网卡的状态
[root@centos8 ~]#virsh domifstat centos8 vnet0
vnet0 rx_bytes 39672
vnet0 rx_packets 739
vnet0 rx_errs 0
vnet0 rx_drop 0
vnet0 tx_bytes 1742
vnet0 tx_packets 19
vnet0 tx_errs 0
vnet0 tx_drop 0

配置虚拟机网卡桥接到宿主机的物理网卡

相当于vmware的桥接模式的Vmnet0

Ubuntu20.04 宿主机的虚拟机界面如下

选择Network source 为 Host deivce eth0: macvtap

128

Rocky8 宿主机的虚拟机界面如下

需要手动输入device name 为 eth0

129

CentOS 7 界面如下

130
131

1
2
3
4
5
6
7
8
[root@centos8 ~]# virsh domiflist centos7
Interface Type Source Model MAC
-------------------------------------------------------
macvtap0 direct eth0 virtio 52:54:00:95:25:fb

[root@centos8 ~]# virsh domifaddr centos7
Name MAC address Protocol Address
-------------------------------------------------------------------------------

132

在宿主机上自动生成虚拟网卡macvtap0@eth0

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
[root@centos8 ~]# 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: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc fq_codel state UP
group default qlen 1000
link/ether 00:0c:29:e1:0e:53 brd ff:ff:ff:ff:ff:ff
inet 10.0.0.8/24 brd 10.0.0.255 scope global noprefixroute eth0
valid_lft forever preferred_lft forever
inet6 fe80::20c:29ff:fee1:e53/64 scope link
valid_lft forever preferred_lft forever
3: virbr0: <NO-CARRIER,BROADCAST,MULTICAST,UP> mtu 1500 qdisc noqueue state DOWN
group default qlen 1000
link/ether 52:54:00:8b:be:ee brd ff:ff:ff:ff:ff:ff
inet 192.168.122.1/24 brd 192.168.122.255 scope global virbr0
valid_lft forever preferred_lft forever
4: virbr0-nic: <BROADCAST,MULTICAST> mtu 1500 qdisc fq_codel master virbr0 state
DOWN group default qlen 1000
link/ether 52:54:00:8b:be:ee brd ff:ff:ff:ff:ff:ff
6: macvtap0@eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc fq_codel
state UP group default qlen 500
link/ether 52:54:00:0d:8a:0e brd ff:ff:ff:ff:ff:ff
inet6 fe80::5054:ff:fe0d:8a0e/64 scope link
valid_lft forever preferred_lft forever

基于自定义网桥的虚拟网络

自定义网桥架构

桥接网络可以让运行在宿主机上的虚拟机使用和宿主机相同网段的IP,并且可以从外部直接访问到虚拟机,目前企业中大部分场景都使用桥接网络。

133

在宿主机创建网桥

CentOS 创建桥接网卡

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
[root@centos8 network-scripts]# pwd
/etc/sysconfig/network-scripts

#创建网桥配置文件
[root@centos8 network-scripts]# cat ifcfg-virbr1
TYPE=Bridge
NAME=virbr1
DEVICE=virbr1
ONBOOT=yes
BOOTPROTO=static
IPADDR=10.0.0.8
NETMASK=255.255.255.0
GATEWAY=10.0.0.2
DNS1=180.76.76.76
DNS2=223.6.6.6

#将物理网卡eth0加入网桥
[root@centos8 network-scripts]# cat ifcfg-eth0
TYPE=Ethernet
NAME=eth0
DEVICE=eth0
ONBOOT=yes
BRIDGE=virbr1

[root@centos8 network-scripts]# nmcli connection reload
[root@centos8 network-scripts]# nmcli connection up eth0 virbr1

[root@centos8 ~]# 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: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc fq_codel master virbr1
state UP group default qlen 1000
link/ether 00:0c:29:44:c3:fe brd ff:ff:ff:ff:ff:ff
4: virbr0: <NO-CARRIER,BROADCAST,MULTICAST,UP> mtu 1500 qdisc noqueue state DOWN
group default qlen 1000
link/ether 52:54:00:52:f2:5c brd ff:ff:ff:ff:ff:ff
inet 192.168.122.1/24 brd 192.168.122.255 scope global virbr0
valid_lft forever preferred_lft forever
5: virbr0-nic: <BROADCAST,MULTICAST> mtu 1500 qdisc fq_codel master virbr0 state
DOWN group default qlen 1000
link/ether 52:54:00:52:f2:5c brd ff:ff:ff:ff:ff:ff
18: virbr1: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP
group default qlen 1000
link/ether 00:0c:29:44:c3:fe brd ff:ff:ff:ff:ff:ff
inet 10.0.0.8/24 brd 10.0.0.255 scope global noprefixroute virbr1
valid_lft forever preferred_lft forever
inet6 fe80::8055:c0ff:fe4e:411e/64 scope link
valid_lft forever preferred_lft forever

[root@centos8 ~]# bridge link show
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 master virbr1 state
forwarding priority 32 cost 100
5: virbr0-nic: <BROADCAST,MULTICAST> mtu 1500 master virbr0 state disabled
priority 32 cost 100

[root@centos8 ~]# ip link show master virbr1
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc fq_codel master virbr1
state UP mode DEFAULT group default qlen 1000
link/ether 00:0c:29:44:c3:fe brd ff:ff:ff:ff:ff:ff

Ubuntu 创建桥接网卡

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
[root@ubuntu2004 ~]# cat /etc/netplan/01-netcfg.yaml
# This file describes the network interfaces available on your system
# For more information, see netplan(5).
network:
version: 2
renderer: networkd
ethernets:
eth0:
dhcp4: no
dhcp6: no
bridges:
br0:
dhcp4: no
dhcp6: no
addresses: [10.0.0.100/16]
gateway4: 10.0.0.2
nameservers:
addresses: [223.6.6.6]
interfaces:
- eth0

基于现有虚拟机镜像批量创建新虚拟机

将前面生成的虚拟机做为模版,生成新的虚拟机

注意:先在前面的模版虚拟机修改配置,如:关闭firewalld和SELinux,禁用NetworkManager(CentOS 7 )等,安装常用包等

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
[root@centos8 images]# pwd
/var/lib/libvirt/images

[root@centos8 images]# cp centos8.qcow2 centos8-2.qcow2
[root@centos8 images]# virt-install --virt-type kvm --name centos8-2 --ram 2048 --vcpus 2 \
--disk bus=virtio,path=/var/lib/libvirt/images/centos8-2.qcow2 --network \
bridge=virbr1,model=virtio --graphics vnc,listen=0.0.0.0 --noautoconsole --autostart --boot hd

WARNING No operating system detected, VM performance may suffer. Specify an OS
with --os-variant for optimal results.
Starting install...
Domain creation completed.

#运行工具,可以看到下面出现新的虚拟机
[root@centos8 images]# virt-manager

#开启的虚拟机磁盘文件所有者为qemu,关闭后为root
[root@centos8 ~]# ll /var/lib/libvirt/images
total 9977352
-rw-r--r-- 1 qemu qemu 2029518848 Sep 21 23:37 centos8-2.qcow2
-rw------- 1 root root 1929183232 Sep 21 23:33 centos8-clone.qcow2
-rw-r--r-- 1 root root 2004221952 Sep 21 23:32 centos8.qcow2

134

查看新虚拟机设置

135
136
137
138

内外网络隔离综合案例

注意:vm2和vm3的虚拟机的IP需要静态配置,用 ip a a 添加的IP不稳定可能会丢失

实现一个外网的web服务和内网的数据库相互隔离的环境

两台宿主机host1和host2

每个宿主机上面各有两个虚拟机,分别连接外网和内网交换机

139

范例: 多网卡绑定

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
root@ubuntu1804:~# vim /etc/netplan/01-netcfg.yaml
# This file describes the network interfaces available on your system
# For more information, see netplan(5).
network:
version: 2
renderer: networkd
ethernets:
eth0:
dhcp4: no
dhcp6: no
eth1:
dhcp4: no
dhcp6: no
bonds:
bond0:
interfaces:
- eth0
- eth1
addresses: [10.0.0.18/16]
gateway4: 10.0.0.1
nameservers:
addresses: [223.6.6.6,223.5.5.5]
parameters:
mode: active-backup
mii-monitor-interval: 100
fail-over-mac-policy: active

root@ubuntu1804:~# netplan apply
root@ubuntu1804:~# ifconfig bond0
bond0: flags=5187<UP,BROADCAST,RUNNING,MASTER,MULTICAST> mtu 1500
inet 10.0.0.18 netmask 255.255.0.0 broadcast 10.0.255.255
inet6 fe80::2820:b7ff:fea8:5837 prefixlen 64 scopeid 0x20<link>
ether 2a:20:b7:a8:58:37 txqueuelen 1000 (Ethernet)
RX packets 296 bytes 25327 (25.3 KB)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 295 bytes 34876 (34.8 KB)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0

root@ubuntu1804:~# ifconfig eth0
eth0: flags=6211<UP,BROADCAST,RUNNING,SLAVE,MULTICAST> mtu 1500
ether 2a:20:b7:a8:58:37 txqueuelen 1000 (Ethernet)
RX packets 3 bytes 180 (180.0 B)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 0 bytes 0 (0.0 B)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0

root@ubuntu1804:~# ifconfig eth1
eth1: flags=6211<UP,BROADCAST,RUNNING,SLAVE,MULTICAST> mtu 1500
ether 2a:20:b7:a8:58:37 txqueuelen 1000 (Ethernet)
RX packets 340 bytes 28893 (28.8 KB)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 336 bytes 39940 (39.9 KB)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0

root@ubuntu1804:~# cat /proc/net/bonding/bond0
Ethernet Channel Bonding Driver: v3.7.1 (April 27, 2011)
Bonding Mode: fault-tolerance (active-backup)
Primary Slave: None
Currently Active Slave: eth1
MII Status: up
MII Polling Interval (ms): 100
Up Delay (ms): 0
Down Delay (ms): 0
Slave Interface: eth1
MII Status: up
Speed: 1000 Mbps
Duplex: full
Link Failure Count: 0
Permanent HW addr: 00:0c:29:34:df:9b
Slave queue ID: 0
Slave Interface: eth0
MII Status: up
Speed: 1000 Mbps
Duplex: full
Link Failure Count: 0
Permanent HW addr: 00:0c:29:34:df:91
Slave queue ID: 0
root@ubuntu1804:~