Kvm/Qemu
Chapter 59: KVM/QEMU Virtualization - Deep Dive
Section titled “Chapter 59: KVM/QEMU Virtualization - Deep Dive”Mastering Kernel-Based Virtual Machine Technology
Section titled “Mastering Kernel-Based Virtual Machine Technology”Why This Matters in DevOps/SRE
Section titled “Why This Matters in DevOps/SRE”KVM (Kernel-based Virtual Machine) is enterprise-grade virtualization - essential for running VMs on Linux servers, private cloud environments, and infrastructure-as-a-service. Unlike containers, VMs provide full OS isolation.
┌─────────────────────────────────────────────────────────────────────────────┐│ KVM IN DEVOPS │├─────────────────────────────────────────────────────────────────────────────┤│ ││ ┌─────────────────────────────────────────────────────────────────────┐ ││ │ USE CASES │ ││ │ │ ││ │ • Private cloud - Self-hosted IaaS │ ││ │ • Legacy apps - Run older OS versions │ ││ │ • Windows workloads - Windows VMs on Linux │ ││ │ • Development - Isolated testing environments │ ││ │ • Security - Complete OS isolation from host │ ││ │ │ ││ └─────────────────────────────────────────────────────────────────────┘ ││ ││ ┌─────────────────────────────────────────────────────────────────────┐ ││ │ KEY CONCEPTS │ ││ │ │ ││ │ • KVM: Linux kernel module for hardware virtualization │ ││ │ • QEMU: Emulator for disk/memory management │ ││ │ • libvirt: Management API (virsh, virt-manager) │ ││ │ • virt-install: CLI for creating VMs │ ││ │ │ ││ └─────────────────────────────────────────────────────────────────────┘ ││ ││ ┌─────────────────────────────────────────────────────────────────────┐ ││ │ PRODUCTION TASKS │ ││ │ │ ││ │ • Live migration: Move VMs between hosts without downtime │ ││ │ • Snapshots: Point-in-time backups │ ││ │ • Resource limits: CPU/memory/IO limits │ ││ │ • Storage pools: Centralized storage management │ ││ │ │ ││ └─────────────────────────────────────────────────────────────────────┘ ││ │└─────────────────────────────────────────────────────────────────────────────┘59.1 Understanding Virtualization
Section titled “59.1 Understanding Virtualization”What is Virtualization?
Section titled “What is Virtualization?”Virtualization is a technology that allows multiple isolated virtual machines to run on a single physical server. KVM (Kernel-based Virtual Machine) turns the Linux kernel into a hypervisor.
Virtualization Types+------------------------------------------------------------------+| || Full Virtualization || +----------------------------------------------------------+ || | - Complete emulation of hardware | || | - Guest OS doesn't know it's virtualized | || | - Uses: Legacy OS, OS testing | || | - Examples: VMware, QEMU (no KVM) | || +----------------------------------------------------------+ || || Paravirtualization || +----------------------------------------------------------+ || | - Guest OS is aware of virtualization | || | - Uses hypervisor APIs for I/O | || | - Better performance than full virtualization | || | - Examples: Xen, early KVM | || +----------------------------------------------------------+ || || Hardware-Assisted Virtualization (HVM) || +----------------------------------------------------------+ || | - CPU provides hardware support (Intel VT-x, AMD-V) | || | - Nearly native performance | || | - Can run unmodified OS | || | - Examples: KVM, VMware, Hyper-V | || +----------------------------------------------------------+ || || Container Virtualization || +----------------------------------------------------------+ || | - OS-level virtualization | || | - Containers share host kernel | || | - Lightweight, fast to start | || | - Examples: Docker, LXC, Podman | || +----------------------------------------------------------+ || |+------------------------------------------------------------------+KVM Architecture
Section titled “KVM Architecture” KVM Architecture+------------------------------------------------------------------+| || QEMU/KVM Stack || || +-------------------------------------------------------------+ || | libvirt (Management API) | || | (virsh, virt-manager, OpenStack, etc.) | || +-----------------------------+-------------------------------+ || | || v || +-----------------------------+-------------------------------+ || | libvirt daemon (libvirtd) | || +-----------------------------+-------------------------------+ || | || v || +-------------------------------------------------------------+ || | QEMU Emulator | || | - Emulates hardware devices | || | - Handles I/O operations | || | - Process: qemu-system-x86_64 | || +-----------------------------+-------------------------------+ || | || v || +-----------------------------+-------------------------------+ || | KVM Kernel Module (kvm.ko, kvm-intel.ko) | || +-----------------------------+-------------------------------+ || | || v || +-----------------------------+-------------------------------+ || | Linux Kernel | || | - CPU scheduling | || | - Memory management | || | - Device drivers | || +-----------------------------+-------------------------------+ || || | || v || Physical Hardware || |+------------------------------------------------------------------+59.2 KVM Installation and Setup
Section titled “59.2 KVM Installation and Setup”Installing KVM
Section titled “Installing KVM”# =============================================================================# ARCH LINUX# =============================================================================
# Install packagessudo pacman -S \ qemu \ libvirt \ virt-manager \ bridge-utils \ dnsmasq \ iptables \ ovmf \ edk2-ovmf
# Enable nested virtualization (if needed)sudo modprobe kvm_intel nested=1
# Verify KVMkvm-ok
# =============================================================================# UBUNTU/DEBIAN# =============================================================================
# Install packagessudo apt updatesudo apt install \ qemu-kvm \ libvirt-daemon-system \ libvirt-clients \ bridge-utils \ virt-manager
# Add user to groupssudo usermod -aG libvirt $USERsudo usermod -aG kvm $USER
# Start libvirtdsudo systemctl enable --now libvirtd
# =============================================================================# VERIFY INSTALLATION# =============================================================================
# Check moduleslsmod | grep kvm
# Check KVM devicesls -la /dev/kvm
# Verify libvirtdsudo systemctl status libvirtdvirsh list --all
# Test with guestvirt-install --name test --os-variant detect --ram 1024 --disk path=/var/lib/libvirt/images/test.qcow2 --pxe --dry-runKVM Network Setup
Section titled “KVM Network Setup”# =============================================================================# BRIDGE NETWORK# =============================================================================
# Create bridge (using nmcli)nmcli con add type bridge ifname br0nmcli con add type ethernet ifname eth0 master br0nmcli con down eth0nmcli con up br0
# Using brctl (deprecated but still works)sudo brctl addbr br0sudo brctl addif br0 eth0sudo brctl show
# =============================================================================# LIBVIRT NETWORK# =============================================================================
# Create network XML /tmp/bridge-network.xml<network> <name>bridge-network</name> <forward mode='bridge'/> <bridge name='br0'/></network>
# Define and start networkvirsh net-define /tmp/bridge-network.xmlvirsh net-start bridge-networkvirsh net-autostart bridge-network
# =============================================================================# NAT NETWORK (DEFAULT)# =============================================================================
# Default NAT network comes with libvirtvirsh net-listvirsh net-start default59.3 Virtual Machine Management
Section titled “59.3 Virtual Machine Management”Creating VMs with virt-install
Section titled “Creating VMs with virt-install”# =============================================================================# BASIC VM CREATION# =============================================================================
# Create VM with ISOvirt-install \ --name=webserver \ --vcpu=2 \ --memory=2048 \ --disk path=/var/lib/libvirt/images/webserver.qcow2,size=20 \ --os-variant=ubuntu22.04 \ --cdrom=/path/to/ubuntu.iso \ --network network=default \ --graphics=vnc
# Create VM with PXE bootvirt-install \ --name=pxe-server \ --vcpu=2 \ --memory=2048 \ --disk path=/var/lib/libvirt/images/pxe.qcow2,size=10 \ --os-variant=ubuntu22.04 \ --pxe \ --network network=default
# Create VM with cloud-initvirt-install \ --name=cloud-vm \ --vcpu=2 \ --memory=4096 \ --disk path=/var/lib/libvirt/images/cloud.qcow2,size=20 \ --os-variant=ubuntu22.04 \ --cloud-init root-password-generate=on \ --network network=default
# Create from existing imagevirt-install \ --name=imported \ --vcpu=2 \ --memory=2048 \ --disk path=/var/lib/libvirt/images/existing.qcow2 \ --import \ --os-variant=auto
# =============================================================================# CONSOLE ACCESS# =============================================================================
# Connect to VM consolevirt-viewer webserver
# Connect via serial consolevirsh console webserver
# Exit serial console: Ctrl+]
# =============================================================================# VM CLONING# =============================================================================
# Clone VMvirt-clone --original=webserver --name=webserver-clone --auto-clone
# Clone to new storagevirt-clone --original=webserver \ --name=webserver-clone \ --file=/var/lib/libvirt/images/clone.qcow2Managing VMs with virsh
Section titled “Managing VMs with virsh”# =============================================================================# VM LIFECYCLE# =============================================================================
# List running VMsvirsh list
# List all VMsvirsh list --all
# Start VMvirsh start webserver
# Stop VM (graceful)virsh shutdown webserver
# Force stop VMvirsh destroy webserver
# Reboot VMvirsh reboot webserver
# Pause/Resumevirsh suspend webservervirsh resume webserver
# Autostart VMvirsh autostart webservervirsh autostart --disable webserver
# =============================================================================# VM INFORMATION# =============================================================================
# VM detailsvirsh dominfo webserver
# VM statevirsh domstate webserver
# List VCPUsvirsh vcpucount webserver
# Get VNC portvirsh vncdisplay webserver
# =============================================================================# VM MODIFICATION# =============================================================================
# Resize memory (online)virsh setmem webserver 4096 --currentvirsh setmem webserver 4096 --config # persistent
# Resize VCPUs (online)virsh setvcpus webserver 4 --currentvirsh setvcpus webserver 4 --config # persistent
# Attach diskvirsh attach-disk webserver /var/lib/libvirt/images/newdisk.qcow2 vdb --persistent
# Detach diskvirsh detach-disk webserver vdb --persistent
# Attach networkvirsh attach-interface webserver --type network --source default --persistent
# =============================================================================# VM DELETION# =============================================================================
# Undefine VM (remove definition)virsh undefine webserver
# Undefine with storagevirsh undefine webserver --remove-all-storage
# Delete snapshots before undefinevirsh undefine webserver --snapshots-metadata59.4 Storage Management
Section titled “59.4 Storage Management”KVM Storage Pools
Section titled “KVM Storage Pools” KVM Storage Types+------------------------------------------------------------------+| || Directory (dir) || +----------------------------------------------------------+ || | - File-based storage (qcow2, raw) | || | - Default for most setups | || | - Easiest to manage | || +----------------------------------------------------------+ || || LVM || +----------------------------------------------------------+ || | - LVM volumes as VM disks | || | - Better performance | || | - Requires LVM setup | || +----------------------------------------------------------+ || || iSCSI || +----------------------------------------------------------+ || | - Network storage | || | - For shared storage | || | - Requires iSCSI target | || +----------------------------------------------------------+ || || NFS || +----------------------------------------------------------+ || | - Network file system | || | - For live migration | || | - Requires NFS server | || +----------------------------------------------------------+ || || Ceph/RBD || +----------------------------------------------------------+ || | - Distributed storage | || | - Highly available | || | - For production clusters | || +----------------------------------------------------------+ || |+------------------------------------------------------------------+Storage Commands
Section titled “Storage Commands”# =============================================================================# STORAGE POOLS# =============================================================================
# List poolsvirsh pool-listvirsh pool-list --all
# Create directory poolvirsh pool-define-as default dir - - - - /var/lib/libvirt/imagesvirsh pool-start default
# Create LVM poolvirsh pool-define-as vgpool logical - /dev/vg_kvm /dev/emptyvirsh pool-start vgpool
# Pool infovirsh pool-info default
# Build poolvirsh pool-build default
# Refresh poolvirsh pool-refresh default
# Delete poolvirsh pool-destroy defaultvirsh pool-undefine default
# =============================================================================# STORAGE VOLUMES# =============================================================================
# List volumesvirsh vol-list default
# Create volumevirsh vol-create-as default vmdisk.qcow2 20G
# Create volume with specific formatvirsh vol-create-as default vmdisk.raw 10G --format raw
# Clone volumevirsh vol-clone --pool default vmdisk.qcow2 vmdisk-clone.qcow2
# Resize volumevirsh vol-resize default/vmdisk.qcow2 40G
# Delete volumevirsh vol-delete default/vmdisk.qcow2
# =============================================================================# DISK FORMATS# =============================================================================
# qcow2 (Copy on Write) - Recommended# - Snapshot support# - Compression# - Encryption# - Thin provisioning
# raw - Fastest# - No features# - Full allocation
# qcow2 creationqemu-img create -f qcow2 /var/lib/libvirt/images/vm.qcow2 20G
# Convert raw to qcow2qemu-img convert -f raw -O qcow2 input.raw output.qcow2
# Convert to rawqemu-img convert -f qcow2 -O raw input.qcow2 output.raw
# Resize diskqemu-img resize vm.qcow2 +10G
# Check diskqemu-img check vm.qcow259.5 Snapshots
Section titled “59.5 Snapshots”Snapshot Management
Section titled “Snapshot Management”# =============================================================================# SNAPSHOT TYPES# =============================================================================
# Internal snapshots# - Stored within qcow2 file# - Cannot live merge# - Limited performance
# External snapshots# - Backing chain# - Can live merge# - Better performance
# =============================================================================# CREATE SNAPSHOT# =============================================================================
# Create internal snapshotvirsh snapshot-create webservervirsh snapshot-create-as webserver --name "before-update"
# Create external snapshotvirsh snapshot-create-as webserver \ --name "backup-snapshot" \ --disk-only \ --diskspec vda,file=/var/lib/libvirt/images/webserver-backup.qcow2
# =============================================================================# LIST SNAPSHOTS# =============================================================================
# List all snapshotsvirsh snapshot-list webserver
# Current snapshotvirsh snapshot-current webserver
# =============================================================================# REVERT TO SNAPSHOT# =============================================================================
# Revert to snapshotvirsh snapshot-revert webserver before-update
# =============================================================================# DELETE SNAPSHOT# =============================================================================
# Delete snapshotvirsh snapshot-delete webserver before-update
# =============================================================================# MERGE SNAPSHOT# =============================================================================
# Block commit (merge to base)virsh blockcommit webserver vda --active --verbose --pivot
# Block pull (merge to top)virsh blockpull webserver vda --verbose59.6 Live Migration
Section titled “59.6 Live Migration”VM Migration
Section titled “VM Migration” Live Migration Types+------------------------------------------------------------------+| || Pre-copy Migration || +----------------------------------------------------------+ || | 1. Initial transfer (memory pages) | || | 2.迭代 memory transfer (dirty pages) | || | 3. Stop source VM | || | 4. Transfer remaining pages | || | 5. Start destination VM | || | | || | - Minimal downtime | || | - Requires shared storage | || +----------------------------------------------------------+ || || Post-copy Migration || +----------------------------------------------------------+ || | 1. Stop source VM | || | 2. Transfer memory | || | 3. Start destination VM | || | | || | - Faster transfer | || | - Risk of source failure | || +----------------------------------------------------------+ || |+------------------------------------------------------------------+Migration Commands
Section titled “Migration Commands”# =============================================================================# LIVE MIGRATION# =============================================================================
# Basic live migrationvirsh migrate --live webserver qemu+ssh://dest-host/system
# With compressionvirsh migrate --live --compress webserver qemu+ssh://dest-host/system
# With tunneled migrationvirsh migrate --live --tunnelled webserver qemu+ssh://dest-host/system
# =============================================================================# MIGRATION WITH STORAGE# =============================================================================
# Migrate with non-shared storagevirsh migrate --live \ --copy-storage-all \ webserver \ qemu+ssh://dest-host/system
# Migrate with incremental storagevirsh migrate --live \ --copy-storage-incremental \ webserver \ qemu+ssh://dest-host/system
# =============================================================================# MIGRATION OPTIONS# =============================================================================
# Set maximum downtimevirsh migrate-setmaxdowntime webserver 1000
# Auto-converge (reduce memory during migration)virsh migrate --live --auto-converge webserver qemu+ssh://dest-host/system
# Bandwidth limit (Mbps)virsh migrate --live --bandwidth 100 webserver qemu+ssh://dest-host/system
# =============================================================================# VERIFY MIGRATION# =============================================================================
# Check migration statusvirsh migrate-getspeed webserver
# List completed migrationsvirsh migrate-compeleted webserver59.7 Exam Tips
Section titled “59.7 Exam Tips”- KVM vs QEMU: KVM = kernel module, QEMU = emulator
- virt-install: Create VMs from command line
- virsh: Main CLI for VM management
- Storage: qcow2 supports snapshots, raw is faster
- Networks: Bridge for external access, NAT for isolated
- Live migration: Requires shared storage or —copy-storage-all
- libvirt: API/daemon that powers KVM management
- snapshots: Internal vs external, understand tradeoffs
- Nested virtualization: Enable kvm_intel nested=1
- Performance: Use virtio drivers for disk/network
Common Mistakes & Anti-Patterns
Section titled “Common Mistakes & Anti-Patterns”1. Not Using Virtio Drivers
Section titled “1. Not Using Virtio Drivers”WRONG:
# Using default IDE/SCSI drivers# Poor disk/network performanceCORRECT:
# Use virtio for better performancevirt-install \ --disk path=vm.qcow2,bus=virtio \ --network bridge=br0,model=virtioWhy: Virtio provides ~3x better I/O performance than emulated drivers.
2. Not Setting Up Proper Networking
Section titled “2. Not Setting Up Proper Networking”WRONG:
# Default NAT - VM not accessible from network# Can't connect to services running in VMCORRECT:
# Create bridge for external accessvirsh net-edit default# Or use host bridgebrctl addif br0 eth0Why: NAT isolates VMs; bridge makes them first-class network citizens.
3. Using Raw Image Withoutthin Provisioning
Section titled “3. Using Raw Image Withoutthin Provisioning”WRONG:
# Pre-allocated raw - takes full disk space immediatelyqemu-img create -f raw vm.img 100GCORRECT:
# qcow2 with thin provisioningqemu-img create -f qcow2 vm.qcow2 100G# Only uses actual disk spaceWhy: qcow2 saves space and supports snapshots.
4. No Resource Limits
Section titled “4. No Resource Limits”WRONG:
# VM can consume all host resources# Host becomes unresponsiveCORRECT:
# Set CPU/memory limitsvirsh setvcpus vm1 4 --maximumvirsh setmem vm1 8G --maximum
# Or in XML:# <cpu mode='host-passthrough'># <topology sockets='1' cores='4' threads='1'/># </cpu>Why: Prevents VM from affecting other VMs or host.
5. Not Using Snapshots for Backups
Section titled “5. Not Using Snapshots for Backups”WRONG:
# No snapshots - risky updates# Can't rollback if something goes wrongCORRECT:
# Create snapshot before risky changesvirsh snapshot-create-as vm1 --name "before-update"
# Revert if neededvirsh snapshot-revert vm1 before-update
# Delete after successvirsh snapshot-delete vm1 before-updateWhy: Snapshots provide quick rollback capability.
Summary
Section titled “Summary”In this chapter, you learned:
- ✅ Virtualization types and concepts
- ✅ KVM architecture
- ✅ KVM installation
- ✅ VM creation with virt-install
- ✅ VM management with virsh
- ✅ Storage pools and volumes
- ✅ Snapshots
- ✅ Live migration
- ✅ Performance tuning
Next Chapter
Section titled “Next Chapter”Chapter 57: Docker Fundamentals
Last Updated: February 2026