How to Install and configure KVM on Ubuntu

Installation and configuration of KVM on Ubuntu 18.04 / 20.04 / 22.04

KVM (Kernel-based Virtual Machine) is an open source virtualization technology that allows you to create and run virtual machines on Linux. KVM requires hardware virtualization support, which is available on most modern CPUs.

In this comprehensive guide, we will cover how to install and configure KVM on Ubuntu 20.04/22.04. We will go through the following steps:

  • Install required packages
  • Verify hardware support for virtualization
  • Load KVM kernel modules
  • Set up a KVM user group
  • Create a KVM virtual machine using CLI
  • Create a KVM virtual machine using Virt Manager (GUI)
  • Manage KVM virtual machines
  • Optimizations and best practices

By the end of this guide, you will have KVM installed and configured, and you will have created virtual machines using both CLI and GUI methods. Let’s get started!

Prerequisites

Before we install KVM, let’s go over the prerequisites:

  • Ubuntu 20.04/22.04 operating system
  • Administrator (root) access to the system
  • Intel VT-x or AMD-V CPU virtualization support enabled in BIOS
  • At least 2 GB RAM (4 GB recommended)

To verify that your CPU supports hardware virtualization, run this command:

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

If the output is 1 or greater, your CPU supports hardware virtualization.

You also need to ensure virtualization is enabled in BIOS. Reboot your system, enter BIOS setup, and enable Intel VT-x/AMD-V.

Now let’s move on to installing KVM.

Install KVM and Other Required Packages

We need to install a few packages to use KVM. Run these commands to install KVM and other required utilities:

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

This installs the main packages:

  • qemu-kvm – KVM hypervisor and processor emulator
  • libvirt-daemon-system – Main daemon managing VMs and hypervisor
  • libvirt-clients – Client tools for interacting with libvirt
  • bridge-utils – Required for creating a network bridge
  • virt-manager – GUI for managing virtual machines (optional)

Verify the installation by checking the version of KVM:

$ kvm --version

The output should display the installed KVM version:

QEMU emulator version 4.2.1 (Debian 1:4.2-3ubuntu6.28)
Copyright (c) 2003-2019 Fabrice Bellard and the QEMU Project developers

Now KVM and related utilities are installed. Next we’ll load the required kernel modules.

Load KVM Kernel Modules

KVM requires the kvm and kvm_intel/kvm_amd kernel modules to be loaded.

Check if they are loaded:

$ lsmod | grep kvm

If they are not loaded, run:

$ sudo modprobe kvm
$ sudo modprobe kvm_intel

This loads kvm and kvm_intel modules. Verify they are now loaded:

$ lsmod | grep kvm

The output should show the modules:

kvm_intel             204800  0
kvm                   593920  1 kvm_intel

KVM modules are now loaded and ready to use.

Set Up KVM User Group

For better security and access control, we will create a dedicated KVM group and add users to it.

Create a kvm group:

$ sudo groupadd kvm 

Add your user to kvm group:

$ sudo usermod -aG kvm $USER

Add any other users who need KVM access to the kvm group as well.

Now we can continue with creating virtual machines.

Create a KVM Virtual Machine (CLI)

Let’s create a KVM virtual machine using command line tools.

We will perform the following steps:

  • Create storage for the VM
  • Create a virtual network bridge
  • Define the VM resources – CPU cores, memory etc
  • Launch the VM installation

First, create a disk image that will be used for VM storage:

$ sudo qemu-img create -f qcow2 /var/lib/libvirt/images/ubuntu-20.qcow2 10G

This creates a qcow2 format disk image at /var/lib/libvirt/images/ubuntu-20.qcow2 with 10GB capacity.

Next, we need to create a network bridge so the VM can connect to the network.

Edit /etc/netplan/00-installer-config.yaml and add a network bridge:

network:
  version: 2
  renderer: networkd
  ethernets:
    enp0s3:
      dhcp4: no
    enp0s8:
      dhcp4: yes
  bridges:
    br0:
      interfaces: [enp0s3]
      dhcp4: no
      addresses: [192.168.122.1/24]
      gateway4: 192.168.122.1
      nameservers:
         addresses: [8.8.8.8,1.1.1.1]

This bridges the enp0s3 interface and assigns it an IP address of 192.168.122.1.

Apply the configuration:

$ sudo netplan apply

Now we have storage and networking ready. Let’s define the VM resources using a CLI definition file called ubuntu-vm.xml:

$ sudo nano ubuntu-vm.xml

Add this content:

<domain type='kvm'>
  <name>ubuntu-vm</name>
  <memory unit='GiB'>2</memory>
  <vcpu>2</vcpu>
  <os>
    <type arch='x86_64'>hvm</type>
  </os>
  <devices>
    <disk type='file' device='disk'>
      <source file='/var/lib/libvirt/images/ubuntu-20.qcow2'/>
      <target dev='vda'/>
    </disk>
    <interface type='bridge'>
      <source bridge='br0'/>
    </interface>
    <graphics type='vnc' listen='0.0.0.0' port='-1'/>
  </devices>
</domain>

This defines a KVM domain with:

  • 2GB RAM
  • 2 vCPUs
  • Disk pointing to the ubuntu-20.qcow2 image
  • Network interface attached to br0 bridge
  • VNC graphics for remote access

Now let’s launch the VM installation:

$ sudo virt-install --import --name ubuntu-vm --ram 2048 --disk /var/lib/libvirt/images/ubuntu-20.qcow2,size=10 --vcpus 2 --os-type linux --os-variant ubuntu20.04 --network bridge=br0 --graphics vnc --noautoconsole --print-xml > ubuntu-vm.xml
$ sudo virsh define ubuntu-vm.xml
$ sudo virsh start ubuntu-vm

This will start the Ubuntu 20.04 installation from the ISO image. You can connect to the VNC console to complete the installation.

After installation completes and the VM boots up, verify it is running:

$ sudo virsh list

The output will show the running VM:

 Id    Name                           State
----------------------------------------------------
 2     ubuntu-vm                      running

We have successfully created a KVM virtual machine using CLI tools!

Create a KVM Virtual Machine (GUI)

We can also use a GUI like Virt Manager to manage KVM VMs.

Install Virt Manager if you haven’t already:

$ sudo apt install virt-manager

Launch Virt Manager either from the command line or desktop environment.

Click on Create a new virtual machine to begin the New VM wizard.

Step through the wizard to define the VM resources, storage, network, etc.

For example, select import existing disk image, enter the path to the qcow2 image created earlier e.g. /var/lib/libvirt/images/ubuntu-20.qcow2.

Complete the remaining steps, review the summary, and click Finish to create the VM.

The VM should now be created and powered off. Right click on it and select Run to start it.

Connect to the VNC console to complete OS installation.

We have now created a KVM virtual machine using the graphical virt-manager tool. Using the GUI can help simplify managing multiple VMs.

Manage KVM Virtual Machines

Now we have KVM installed and VMs created, let’s go over managing the VMs.

List all VMs:

$ sudo virsh list --all

This will list all active and inactive VMs.

Start a VM:

$ sudo virsh start ubuntu-vm

Shutdown a VM:

$ sudo virsh shutdown ubuntu-vm

Force power off a VM:

$ sudo virsh destroy ubuntu-vm

Delete a VM:

$ sudo virsh undefine ubuntu-vm

This will delete the VM configuration, but won’t delete the disk image.

Suspend/resume a VM:

$ sudo virsh suspend ubuntu-vm
$ sudo virsh resume ubuntu-vm

Reboot a VM:

$ sudo virsh reboot ubuntu-vm

Connect to VNC console:

$ sudo virt-viewer ubuntu-vm

This will open a VNC window to interact with the VM’s graphical console.

VM status:

$ sudo virsh domstate ubuntu-vm

VM statistics:

$ sudo virsh domstats ubuntu-vm

This covers the basic VM management tasks with KVM. You can refer to the virsh man pages for more advanced management operations.

Optimizations and Best Practices

Here are some tips for optimizing KVM performance and efficiency:

  • Use paravirtualized drivers (virtio) for disk and network. This improves I/O throughput.
  • Use LVM based storage. Create a volume group for VM images to allow flexible allocation.
  • Use network bridges instead of NAT for better network performance.
  • Enable nested virtualization if you want to run VMs inside guest VMs.
  • Allocate CPU cores/memory appropriately based on workload. Do not over provision.
  • Take regular VM snapshots before major configuration changes.
  • Monitor VM resource usage to identify bottlenecks.
  • Host critical VMs on machines with redundant storage/network (High-availability).
  • Isolate VM types by using different bridge networks and VLANs.

Following best practices helps ensure your KVM infrastructure remains secure, stable and scalable.

Conclusion

We have installed KVM on Ubuntu 20.04/22.04, created VMs using CLI and Virt Manager, and covered managing and optimizing KVM.

KVM provides an open source and cost-effective virtualization solution on Linux. With its excellent performance and wide adoption, it is a great hypervisor for running Linux guest VMs.

We encourage you to further explore KVM capabilities and build robust virtualized environments. This will allow you to consolidate servers, isolate services, and take advantage of powerful VM management features.

LEAVE A COMMENT