Ubuntu 22.04 之 KVM 安装手札
KVM
![](/data/attachment/album/202206/01/171619m6dd7bjb8292bbb9.jpg)


**KVM** 是 <ruby> 基于内核的虚拟机 <rt>  Kernel-based Virtual Machine </rt></ruby> 的首字母缩写，这是一项集成在内核中的开源虚拟化技术。它是一种类型一（裸机）的<ruby> 管理程序 <rt>  hypervisor </rt></ruby>，可以使内核能够作为一个<ruby> 裸机管理程序 <rt>  bare-metal hypervisor </rt></ruby>。


在 KVM 之上可以运行 Windows 和 Liunx 虚拟机。每个虚拟机都独立于其它虚拟机和底层操作系统（宿主机系统），并拥有自己的 CPU、内存、网络接口、存储设备等计算资源。


本文将介绍在 Ubuntu 22.04 LTS（Jammy Jellyfish）中如何安装 KVM 。在文末，我们也将演示如何在安装 KVM 完成之后创建一台虚拟机。


### 1、更新 Ubuntu 22.04


在一切开始前，打开终端并通过如下命令更新本地的软件包索引：



```
$ sudo apt update

```

### 2、检查虚拟化是否开启


在进一步行动之前，首先需要检查你的 CPU 是否支持 KVM 虚拟化，确保你系统中有 VT-x（ vmx）英特尔处理器或 AMD-V（svm）处理器。


你可以通过运行如下命令，如果输出值大于 0，那么虚拟化被启用。否则，虚拟化被禁用，你需要启用它：



```
$ egrep -c '(vmx|svm)' /proc/cpuinfo

```

![SVM-VMX-Flags-Cpuinfo-linux](/data/attachment/album/202206/01/171638lo083lxspwwooykb.png)


根据上方命令输出，你可以推断出虚拟化功能已经启用，因为输出结果大于 0。如果虚拟化功能没有启用，请确保在系统的 BIOS 设置中启用虚拟化功能。


另外，你可以通过如下命令判断 KVM 虚拟化是否已经在运行：



```
$ kvm-ok

```

运行该命令之前，请确保你已经安装了 `cpu-checker` 软件包，否则将提示未找到该命令的报错。


直接就在下面，你会得到如何解决这个问题的指示，那就是安装 `cpu-checker` 包。


![KVM-OK-Command-Not-Found-Ubuntu](/data/attachment/album/202206/01/171639y55r74brr3r3r2w7.png)


随后，通过如下命令安装 `cpu-checker` 软件包：



```
$ sudo apt install -y cpu-checker

```

接着再运行 `kvm-ok` 命令，如果 KVM 已经启动，你将看到如下输出：



```
$ kvm-ok

```

![KVM-OK-Command-Output](/data/attachment/album/202206/01/171639ebbsees9efo6ebpb.png)


### 3、在 Ubuntu 22.04 上安装 KVM


随后，通过如下命令在 Ubuntu 22.04 中安装 KVM 以及其他相关虚拟化软件包：



```
$ sudo apt install -y qemu-kvm virt-manager libvirt-daemon-system virtinst libvirt-clients bridge-utils

```

以下为你解释刚刚安装了哪些软件包：


* `qemu-kvm` – 一个提供硬件仿真的开源仿真器和虚拟化包
* `virt-manager` – 一款通过 libvirt 守护进程，基于 QT 的图形界面的虚拟机管理工具
* `libvirt-daemon-system` – 为运行 libvirt 进程提供必要配置文件的工具
* `virtinst` – 一套为置备和修改虚拟机提供的命令行工具
* `libvirt-clients` – 一组客户端的库和API，用于从命令行管理和控制虚拟机和管理程序
* `bridge-utils` – 一套用于创建和管理桥接设备的工具


### 4、启用虚拟化守护进程（libvirtd）


在所有软件包安装完毕之后，通过如下命令启用并启动 libvirt 守护进程：



```
$ sudo systemctl enable --now libvirtd
$ sudo systemctl start libvirtd

```

你可以通过如下命令验证该虚拟化守护进程是否已经运行：



```
$ sudo systemctl status libvirtd

```

![Libvirtd-Status-Ubuntu-Linux](/data/attachment/album/202206/01/171639dikm3adgamqamjwq.png)


另外，请将当前登录用户加入 `kvm` 和 `libvirt` 用户组，以便能够创建和管理虚拟机。



```
$ sudo usermod -aG kvm $USER
$ sudo usermod -aG libvirt $USER

```

`$USER` 环境变量引用的即为当前登录的用户名。你需要重新登录才能使得配置生效。


### 5、创建网桥（br0）


如果你打算从本机（Ubuntu 22.04）之外访问 KVM 虚拟机，你必须将虚拟机的网卡映射至网桥。`virbr0` 网桥是 KVM 安装完成后自动创建的，仅做测试用途。


你可以通过如下内容在 `/etc/netplan` 目录下创建文件 `01-netcfg.yaml` 来新建网桥：



```
$ sudo vi /etc/netplan/01-netcfg.yaml
network:
  ethernets:
    enp0s3:
      dhcp4: false
      dhcp6: false
  # add configuration for bridge interface
  bridges:
    br0:
      interfaces: [enp0s3]
      dhcp4: false
      addresses: [192.168.1.162/24]
      macaddress: 08:00:27:4b:1d:45
      routes:
        - to: default
          via: 192.168.1.1
          metric: 100
      nameservers:
        addresses: [4.2.2.2]
      parameters:
        stp: false
      dhcp6: false
  version: 2

```

保存并退出文件。


注：上述文件的配置是我环境中的，请根据你实际环境替换 IP 地址、网口名称以及 MAC 地址。


你可以通过运行 `netplan apply` 命令应用上述变更。



```
$ sudo netplan apply

```

你可以通过如下 `ip` 命令，验证网桥 `br0`：



```
$ ip add show

```

![Network-Bridge-br0-ubuntu-linux](/data/attachment/album/202206/01/171640d4gj7ogvtgztvgcq.png)


### 6、启动 KVM 虚拟机管理器


当 KVM 安装完成后，你可以使用图形管理工具 `virt-manager` 创建虚拟机。你可以在 GNOME 搜索工具中搜索 `Virtual Machine Manager` 以启动。


点击搜索出来的图标即可：


![Access-Virtual-Machine-Manager-Ubuntu-Linux](/data/attachment/album/202206/01/171640l3zschiibzr9hi1m.png)


虚拟机管理器界面如下所示：


![Virtual-Machine-Manager-Interface-Ubuntu-Linux](/data/attachment/album/202206/01/171640mzy5b7mz44lzrnko.png)


你可以点击 “<ruby> 文件 <rt>  File </rt></ruby>” 并选择 “<ruby> 新建虚拟机 <rt>  New Virtual Machine </rt></ruby>”。你也可以点击下图所示的图标：


![New-Virtual-Machine-Icon-Virt-Manager](/data/attachment/album/202206/01/171640ecehilwhisiwgoql.png)


在弹出的虚拟机安装向导将看到如下四个选项：


* 本地安装介质（ISO 镜像或 CDROM）
* 网络安装（HTTP、HTTPS 和 FTP）
* 导入现有磁盘镜像
* 手动安装


本文使用已下载的 ISO 镜像，你可以选择自己的 ISO 镜像，选择第一个选项，并点击 “<ruby> 向前 <rt>  Forward </rt></ruby>”。


![Local-Install-Media-ISO-Virt-Manager](/data/attachment/album/202206/01/171641pe25eotwx21wwwzo.png)


下一步中，点击 “<ruby> 浏览 <rt>  Browse </rt></ruby>” 选择 ISO 镜像位置。


![Browse-ISO-File-Virt-Manager-Ubuntu-Linux](/data/attachment/album/202206/01/171641ix5fr0lf815vtnx8.png)


在下一个窗口中点击 “<ruby> 浏览本地 <rt>  Browse local </rt></ruby>” 选取本机中 ISO 镜像。


![Browse-Local-ISO-Virt-Manager](/data/attachment/album/202206/01/171641ygkguukdm6kmwg11.png)


如下所示，我们选择了 Debian 11 ISO 镜像，随后点击 “<ruby> 打开 <rt>  Open </rt></ruby>”。


![Choose-ISO-File-Virt-Manager](/data/attachment/album/202206/01/171641taa2k7yy1yj7fzkt.png)


当 ISO 镜像选择后，点击 “<ruby> 向前 <rt>  Forward </rt></ruby>” 进入下一步。


![Forward-after-browsing-iso-file-virt-manager](/data/attachment/album/202206/01/171642y4rmr9rxgxodsoxr.png)


接着定义虚拟机所用内存大小以及 CPU 核心数，并点击 “<ruby> 向前 <rt>  Forward </rt></ruby>” 。


![Virtual-Machine-RAM-CPU-Virt-Manager](/data/attachment/album/202206/01/171642nwrttbb1jbl1w2ee.png)


下一步中，输入虚拟机磁盘空间，并点击 “<ruby> 向前 <rt>  Forward </rt></ruby>” 继续。


![Storage-for-Virtual-Machine-KVM-Virt-Manager](/data/attachment/album/202206/01/171642ndoj9dyk56xemc69.png)


如你需要将虚拟机网卡连接至网桥，点击 “<ruby> 选择网络 <rt>  Network selection </rt></ruby>” 并选择 `br0` 网桥。


![Network-Selection-KVM-Virtual-Machine-Virt-Manager](/data/attachment/album/202206/01/171642oapqqog83z18qorw.png)


最后，点击 “<ruby> 完成 <rt>  Finish </rt></ruby>” 按钮结束设置虚拟机。


![Choose-Finish-to-OS-Installation-KVM-VM](/data/attachment/album/202206/01/171643sfnf31nxh9fdzyn1.png)


稍等片刻，虚拟机的创建过程将开始。


![Creating-Domain-Virtual-Machine-Virt-Manager](/data/attachment/album/202206/01/171643az00v3hpn3f30hmz.png)


当创建结束时，虚拟机将开机并进入系统安装界面。如下是 Debian 11 的安装选项。在这里你可以根据需要进行系统安装。


![Virtual-Machine-Console-Virt-Manager](/data/attachment/album/202206/01/171643f5et37740h9lu0u9.png)


### 小结


至此，本文向你演示了如何在 Ubuntu 22.04 上 安装 KVM 虚拟化引擎。你的反馈对我们至关重要。




---


via: <https://www.linuxtechi.com/how-to-install-kvm-on-ubuntu-22-04/>


作者：[James Kiarie](https://www.linuxtechi.com/author/james/) 选题：[lkxed](https://github.com/lkxed) 译者：[turbokernel](https://github.com/turbokernel) 校对：[wxy](https://github.com/wxy)


本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译，[Linux中国](https://linux.cn/) 荣誉推出


OK
This blog post will show you how to install KVM on Ubuntu 22.04 step-by-step. At the tail end of this post, we will demonstrate how you can create a virtual machine once the installation of KVM is complete.

[KVM](https://www.redhat.com/en/topics/virtualization/what-is-KVM), an acronym for Kernel-based Virtual Machine is an opensource virtualization technology integrated into the Linux kernel. It’s a type 1 (bare metal ) hypervisor that enables the kernel to act as a bare-metal hypervisor.

KVM allows users to create and run multiple guest machines which can be either Windows or Linux. Each guest machine runs independently of other virtual machines and the underlying OS ( host system ) and has its own computing resources such as CPU, RAM, network interfaces, and storage to mention a few.

#### Prerequisites

- Pre Installed Ubuntu 22.04
- 2 vCPUs & 4 GB RAM
- Stable Internet Connectivity

## 1) Update Ubuntu 22.04

To get off the ground, launch the terminal and update your local package index as follows.

$ sudo apt update

## 2) Check if Virtualization is enabled

Before you proceed any further, you need to check if your CPU supports KVM virtualization. For this to be possible, your system needs to either have a VT-x( vmx ) Intel processor or an AMD-V (svm) processor.

This is achieved by running the following command. if the output is greater than 0, then virtualization is enabled. Otherwise, virtualization is disabled and you need to enable it.

$ egrep -c '(vmx|svm)' /proc/cpuinfo

From the above output, you can deduce that virtualization is enabled since the result printed is greater than 0. If Virtualization is not enabled, be sure to enable the virtualization feature in your system’s BIOS settings.

In addition, you can verify if KVM virtualization is enabled by running the following command:

$ kvm-ok

For this to work, you need to have installed the cpu-checker package, otherwise, you will bump into the error ‘Command ‘kvm-ok’ not found’.

Directly below, you will get instructions on how to resolve this issue, and that is to install the cpu-checker package.

Therefore, install the cpu-checker package as follows.

$ sudo apt install -y cpu-checker

Then run the kvm-ok command, and if KVM virtualization is enabled, you should get the following output.

$ kvm-ok

## 3) Install KVM on Ubuntu 22.04

Next, run the command below to install KVM and additional virtualization packages on Ubuntu 22.04.

$ sudo apt install -y qemu-kvm virt-manager libvirt-daemon-system virtinst libvirt-clients bridge-utils

Let us break down the packages that we are installing:

- qemu-kvm – An opensource emulator and virtualization package that provides hardware emulation.
- virt-manager – A Qt-based graphical interface for managing virtual machines via the libvirt daemon.
- libvirt-daemon-system – A package that provides configuration files required to run the libvirt daemon.
- virtinst – A set of command-line utilities for provisioning and modifying virtual machines.
- libvirt-clients – A set of client-side libraries and APIs for managing and controlling virtual machines & hypervisors from the command line.
- bridge-utils – A set of tools for creating and managing bridge devices.

## 4) Start & Enable Virtualization Daemon


With all the packages installed, enable and start the Libvirt daemon.

$ sudo systemctl enable --now libvirtd $ sudo systemctl start libvirtd

Confirm that the virtualization daemon is running as shown.

$ sudo systemctl status libvirtd

In addition, you need to add the currently logged-in user to the kvm and libvirt groups so that they can create and manage virtual machines.

$ sudo usermod -aG kvm $USER $ sudo usermod -aG libvirt $USER

The $USER environment variable points to the name of the currently logged-in user. To apply this change, you need to log out and log back again.

## 5) Create Network Bridge (br0)

If you are planning to access KVM virtual machines outside from your Ubuntu 22.04 system, then you must map VM’s interface to a network bridge. Though a virtual bridge named virbr0, created automatically when KVM is installed but it is used for testing purposes.

To create a network bridge, create the file ‘01-netcfg.yaml’ with following content under the folder /etc/netplan.

$ sudo vi /etc/netplan/01-netcfg.yaml network: ethernets: enp0s3: dhcp4: false dhcp6: false # add configuration for bridge interface bridges: br0: interfaces: [enp0s3] dhcp4: false addresses: [192.168.1.162/24] macaddress: 08:00:27:4b:1d:45 routes: - to: default via: 192.168.1.1 metric: 100 nameservers: addresses: [4.2.2.2] parameters: stp: false dhcp6: false version: 2

save and exit the file.

Note: These details as per my setup, so replace the IP address entries, interface name and mac address as per your setup.

To apply above change, run ‘netplan apply’

$ sudo netplan apply

Verify the network bridge ‘br0’, run below [ip command](https://www.linuxtechi.com/ip-command-examples-for-linux-users/)

$ ip add show

## 6) Launch KVM Virtual Machines Manager

With KVM installed, you can begin creating your virtual machines using the virt-manager GUI tool. To get started, use the GNOME search utility and search for ‘Virtual machine Manager’.

Click on the icon that pops up.

This launches the Virtual Machine Manager Interface.

Click on “File” then select “New Virtual Machine”. Alternatively, you can click on the button shown.

This pops open the virtual machine installation wizard which presents you with the following four options:

- Local install Media ( ISO image or CDROM )
- Network Install ( HTTP, HTTPS, and FTP )
- Import existing disk image
- Manual Install

In this guide, we have downloaded a Debian 11 ISO image, and therefore, if you have an ISO image, select the first option and click ‘Forward’.

In the next step, click ‘Browse’ to navigate to the location of the ISO image,

In the next window, click ‘Browse local’ in order to select the ISO image from the local directories on your Linux PC.

As demonstrated below, we have selected the Debian 11 ISO image. Then click ‘Open’

Once the ISO image is selected, click ‘Forward’ to proceed to the next step.

Next, define the RAM and the number of CPU cores for your virtual machine and click ‘Forward’.

In the next step, define the disk space for your virtual machine and click ‘Forward’.

To associate virtual machine’s nic to network bridge, click on ‘Network selection’ and choose br0 bridge.

Finally, click ‘Finish’ to wind up setting the virtual machine.

Shortly afterward, the virtual machine creation will get underway.

Once completed, the virtual machine will start with the OS installer displayed. Below is the Debian 11 installer listing the options for installation. From here, you can proceed to install your preferred system.

#### Conclusion

And that’s it. In this guide, we have demonstrated how you can install the KVM hypervisor on Ubuntu 22.04. Your feedback on this guide is much welcome.

Read Also: [How to Create KVM Virtual Machine Snapshot with Virsh Command](https://www.linuxtechi.com/create-revert-delete-kvm-virtual-machine-snapshot-virsh-command/)

KamusHi James, thanks for this great article, I would like to add a little comment.

If you want to let host machine to access the vm machine by SSH, and let the vm machine to access internet by the host machine ethernet, there is a additional package should be installed.

sudo apt install libnss-libvirt

Pål BjartanThanks for a detailed tutorial. However, I am facing an issue with creating a network bridge. I created the `/etc/netplan/01-netcfg.yaml` file as described in step 5, but this resulted in Ubuntu no longer connecting to the WiFi. It now shows a LAN icon in the top right corner. Deleting the file and running `sudo netplan apply` again solved the issue. I presume Ubuntu instead attempts to use the bridge to connect to the Internet.

Is there a way this can be avoided?

JohnSo I upgraded my Ubuntu 20.04 LTS hypervisor to 22..04 LTS.

systemctl status libvirtd says:

VMM is missing/removed and Storage Pool no longer showing up.

tried to re-install via APT, APT-GET ‘virt-manager’ and ‘virtinst’ packages, neither one is found.

Anyone else encountering this issue after Ubuntu 22.04 LTS ‘jammy jellyfish’ upgrade from 20.04 LTS?