🖥️
Virtualization & Cloud

KVM Virtualization

Kernel-based virtual machine hypervisor for Linux

🐧 Linux🍎 Mac🪟 Windows
Reviewed: Tested on: Kubernetes 1.29 · Terraform 1.8 · Ubuntu 22.04

What is this?

KVM lets you run full virtual machines (like a computer inside your computer) on Linux.

📥

Step 01

Install KVM

(01)Install KVM and tools

Linux
1# Ubuntu / Debian
2sudo apt-get update
3sudo apt-get install -y qemu-kvm libvirt-daemon-system libvirt-clients bridge-utils virt-manager
4
5# RHEL / Fedora
6sudo dnf install -y @virtualization
7sudo systemctl enable --now libvirtd
8
9# Add user to libvirt group
10sudo usermod -aG libvirt $USER
11sudo usermod -aG kvm $USER

(02)Verify CPU virtualization support

Linux
1egrep -c '(vmx|svm)' /proc/cpuinfo # should be > 0
2kvm-ok # Ubuntu
3lsmod | grep kvm
4virsh list --all
⚙️

Step 02

Configure KVM

(01)Create bridge network

Linux
1sudo nano /etc/netplan/01-bridge.yaml
2
3# network:
4# version: 2
5# ethernets:
6# enp0s3:
7# dhcp4: no
8# bridges:
9# br0:
10# interfaces: [enp0s3]
11# dhcp4: yes
12
13sudo netplan apply
14ip addr show br0

(02)Create VM with virt-install

Linux
1# Download ISO first, then:
2sudo virt-install \
3 --name ubuntu-vm \
4 --ram 2048 \
5 --disk path=/var/lib/libvirt/images/ubuntu.qcow2,size=20 \
6 --vcpus 2 \
7 --os-variant ubuntu22.04 \
8 --network bridge=br0 \
9 --graphics vnc,listen=0.0.0.0 \
10 --cdrom /path/to/ubuntu-22.04.iso
11
12# Or use GUI:
13virt-manager

(03)Manage VMs with virsh

Linux
1virsh list --all
2virsh start ubuntu-vm
3virsh shutdown ubuntu-vm
4virsh destroy ubuntu-vm # force stop
5virsh console ubuntu-vm
6virsh dumpxml ubuntu-vm > vm-backup.xml

Step 03

Verify KVM

(01)Check libvirt

Linux
1sudo systemctl status libvirtd
2virsh net-list --all
3virsh pool-list --all

Step 04

Manage KVM

(01)Snapshots and cloning

Linux
1# Snapshot
2virsh snapshot-create-as ubuntu-vm snap1 "before upgrade"
3
4# Clone
5virt-clone --original ubuntu-vm --name ubuntu-vm-clone --auto-clone
6
7# Export/import
8virsh dumpxml ubuntu-vm > ubuntu-vm.xml
9virsh define ubuntu-vm.xml