Complete Guide to KVM Virtualization on Ubuntu 24.04 LTS

admineci

admineci

Auteur

1417 mots
Complete Guide to KVM Virtualization on Ubuntu 24.04 LTS

KVM (Kernel-based Virtual Machine) is a powerful open-source virtualization technology that transforms Linux into a type-1 (bare-metal) hypervisor. With Ubuntu 24.04 LTS, KVM provides enterprise-grade virtualization capabilities that rival proprietary solutions while maintaining the flexibility and cost-effectiveness of open source.

Introduction

KVM (Kernel-based Virtual Machine) is a powerful open-source virtualization technology that transforms Linux into a type-1 (bare-metal) hypervisor. With Ubuntu 24.04 LTS, KVM provides enterprise-grade virtualization capabilities that rival proprietary solutions while maintaining the flexibility and cost-effectiveness of open source.

This comprehensive guide will walk you through setting up KVM on Ubuntu 24.04, creating virtual machines, and mastering essential management techniques. Whether you're building a home lab, deploying production workloads, or migrating from VMware, this tutorial provides everything you need to get started.

Prerequisites

Before installing KVM, ensure your system meets these requirements:

Hardware Requirements

  • CPU: 64-bit processor with hardware virtualization support
    • Intel: VT-x (vmx flag)
    • AMD: AMD-V (svm flag)
  • RAM: Minimum 4GB (8GB+ recommended)
  • Storage: At least 20GB free space for host OS and VMs
  • Network: Ethernet adapter for bridge networking

Verify Hardware Virtualization Support

Check if your CPU supports virtualization:

# Check for Intel VT-x or AMD-V support
egrep -c '(vmx|svm)' /proc/cpuinfo

# If the output is greater than 0, virtualization is supported
# For detailed CPU flags
lscpu | grep Virtualization

1. Installing KVM on Ubuntu 24.04

Step 1: Update System Packages

sudo apt update && sudo apt upgrade -y

Step 2: Install KVM and Related Packages

sudo apt -y install qemu-kvm libvirt-daemon-system libvirt-daemon virtinst bridge-utils libosinfo-bin

Package breakdown:

  • qemu-kvm: The main KVM hypervisor
  • libvirt-daemon-system: System daemon for managing VMs
  • libvirt-daemon: Virtualization management daemon
  • virtinst: Command-line tools for creating VMs
  • bridge-utils: Utilities for configuring network bridges
  • libosinfo-bin: Database of operating systems for optimal configurations

Step 3: Add User to Required Groups

# Add your user to libvirt and kvm groups
sudo usermod -aG libvirt $USER
sudo usermod -aG kvm $USER

# Apply group changes without logging out
newgrp libvirt
newgrp kvm

Step 4: Verify Installation

# Check if KVM modules are loaded
lsmod | grep kvm
# Verify libvirt service is running
sudo systemctl status libvirtd
# Test virsh command
virsh list --all

2. Configuring Bridge Networking

Bridge networking allows VMs to appear as physical hosts on your network, getting IP addresses from your DHCP server.

Step 1: Identify Your Network Interface

ip addr show
# Note your primary interface name (e.g., enp1s0, eth0)

Step 2: Configure Netplan for Bridge Networking

Edit your Netplan configuration:

sudo nano /etc/netplan/01-netcfg.yaml

Replace the content with:

network:
  ethernets:
    enp1s0:  # Replace with your interface name
      dhcp4: false
      dhcp6: false
  
  bridges:
    br0:
      interfaces: [enp1s0]
      dhcp4: false
      addresses: [10.0.0.30/24]  # Your static IP
      routes:
        - to: default
          via: 10.0.0.1  # Your gateway
          metric: 100
      nameservers:
        addresses: [10.0.0.10, 8.8.8.8]  # Your DNS servers
        search: [yourdomain.local]
      parameters:
        stp: false
      dhcp6: false
  version: 2

Step 3: Apply Network Configuration

# Apply the new configuration
sudo netplan apply
# Verify bridge creation
ip addr show br0
brctl show

3. Creating Your First Virtual Machine

Option 1: Command-Line Installation with virt-install

This method provides full control over VM creation:

​​​​​​​# Create a directory for VM images
sudo mkdir -p /var/kvm/images
# Download Ubuntu 24.04 Server ISO
wget https://releases.ubuntu.com/24.04/ubuntu-24.04-live-server-amd64.iso
# Create VM with virt-install
sudo virt-install \
  --name ubuntu-vm1 \
  --ram 4096 \
  --disk path=/var/kvm/images/ubuntu-vm1.img,size=20 \
  --vcpus 2 \
  --os-variant ubuntu24.04 \
  --network bridge=br0 \
  --graphics none \
  --console pty,target_type=serial \
  --location /path/to/ubuntu-24.04-live-server-amd64.iso,kernel=casper/vmlinuz,initrd=casper/initrd \
  --extra-args 'console=ttyS0,115200n8'

Option 2: Using virt-manager GUI

For desktop users, install the graphical interface:

​​​​​​​sudo apt install virt-manager
# Launch virt-manager
virt-manager

Understanding virt-install Parameters


 
Parameter Description
--name VM name (must be unique)
--ram Memory allocation in MB
--disk Disk configuration (path and size)
--vcpus Number of virtual CPUs
--os-variant OS type for optimization
--network Network configuration
--graphics Display type (none for headless)
--console Console connection type

4. Essential VM Management Commands

Starting and Stopping VMs

​​​​​​​# Start a VM
virsh start ubuntu-vm1
# Start and connect to console
virsh start ubuntu-vm1 --console
# Graceful shutdown
virsh shutdown ubuntu-vm1
# Force stop (use cautiously)
virsh destroy ubuntu-vm1
# Reboot VM
virsh reboot ubuntu-vm1

Listing and Monitoring VMs

​​​​​​​# List running VMs
virsh list
# List all VMs (including stopped)
virsh list --all
# Show VM information
virsh dominfo ubuntu-vm1
# Display VM configuration
virsh dumpxml ubuntu-vm1

Console Access

# Connect to VM console
virsh console ubuntu-vm1
# Exit console: Ctrl + ]

Auto-start Configuration

# Enable auto-start
virsh autostart ubuntu-vm1
# Disable auto-start
virsh autostart --disable ubuntu-vm1

5. Storage Management

Creating Storage Pools

​​​​​​​# Create a new storage pool directory
sudo mkdir -p /var/lib/libvirt/images/vmpool
# Define the storage pool
virsh pool-define-as vmpool dir - - - - "/var/lib/libvirt/images/vmpool"
# Start the pool
virsh pool-start vmpool
# Enable auto-start
virsh pool-autostart vmpool
# List storage pools
virsh pool-list --all

Managing Virtual Disks

​​​​​​​# Create a new disk
virsh vol-create-as vmpool ubuntu-vm2.qcow2 30G --format qcow2
# List volumes in a pool
virsh vol-list vmpool
# Delete a volume
virsh vol-delete ubuntu-vm2.qcow2 --pool vmpool

6. Advanced VM Management Tools

Install Management Utilities

​​​​​​​sudo apt -y install libguestfs-tools virt-top

Using libguestfs Tools

​​​​​​​# List files in VM
virt-ls -l -d ubuntu-vm1 /etc
# View file content
virt-cat -d ubuntu-vm1 /etc/hostname
# Edit files in VM (while stopped)
virt-edit -d ubuntu-vm1 /etc/hosts
# Check disk usage
virt-df -d ubuntu-vm1
# Mount VM filesystem
sudo guestmount -d ubuntu-vm1 -i /mnt
sudo umount /mnt

Real-time Monitoring with virt-top

# Monitor VM performance
virt-top
# Sort by CPU usage: shift + P
# Sort by memory: shift + M
# Help: h
# Quit: q

7. VM Cloning and Snapshots

Cloning VMs


 
# Clone a VM
virt-clone --original ubuntu-vm1 --name ubuntu-vm2 --file /var/kvm/images/ubuntu-vm2.img
# Clone with auto-generated storage
virt-clone --original ubuntu-vm1 --name ubuntu-vm3 --auto-clone

Managing Snapshots

# Create snapshot
virsh snapshot-create-as ubuntu-vm1 --name "before-updates" --description "Clean install"
# List snapshots
virsh snapshot-list ubuntu-vm1
# Revert to snapshot
virsh snapshot-revert ubuntu-vm1 "before-updates"
# Delete snapshot
virsh snapshot-delete ubuntu-vm1 "before-updates"

8. Nested Virtualization

Enable nested virtualization to run VMs inside VMs:

Check Current Status

# For Intel
cat /sys/module/kvm_intel/parameters/nested
# For AMD
cat /sys/module/kvm_amd/parameters/nested

Enable Nested Virtualization

​​​​​​​# For Intel CPUs
echo 'options kvm_intel nested=1' | sudo tee /etc/modprobe.d/kvm-intel.conf
# For AMD CPUs
echo 'options kvm_amd nested=1' | sudo tee /etc/modprobe.d/kvm-amd.conf
# Reload module (Intel example)
sudo modprobe -r kvm_intel
sudo modprobe kvm_intel

Configure VM for Nested Virtualization


 
# Edit VM configuration
virsh edit ubuntu-vm1
# Add or modify CPU configuration:
<cpu mode='host-passthrough' check='none' migratable='on'/>

9. Performance Optimization

CPU Pinning

​​​​​​​# Pin vCPUs to physical CPUs
virsh vcpupin ubuntu-vm1 0 0
virsh vcpupin ubuntu-vm1 1 1

Memory Optimization

​​​​​​​# Set memory balloon
virsh setmem ubuntu-vm1 2048M --config
# Enable hugepages
echo 'vm.nr_hugepages = 1024' | sudo tee -a /etc/sysctl.conf
sudo sysctl -p

Disk I/O Optimization

Use VirtIO drivers and cache modes:

​​​​​​​<disk type='file' device='disk'>
  <driver name='qemu' type='qcow2' cache='writeback' io='threads'/>
  <source file='/var/kvm/images/ubuntu-vm1.img'/>
  <target dev='vda' bus='virtio'/>
</disk>

10. Backup and Migration

Backup VMs

​​​​​​​# Backup VM configuration
virsh dumpxml ubuntu-vm1 > ubuntu-vm1.xml
# Backup disk image
sudo cp /var/kvm/images/ubuntu-vm1.img /backup/
# Create compressed backup
sudo qemu-img convert -c -O qcow2 /var/kvm/images/ubuntu-vm1.img /backup/ubuntu-vm1-backup.qcow2

Live Migration (requires shared storage)

# Migrate to another host
virsh migrate --live ubuntu-vm1 qemu+ssh://dest-host/system

Troubleshooting Common Issues

VM Won't Start

# Check logs
journalctl -u libvirtd -f
# Verify VM configuration
virsh domblklist ubuntu-vm1
virsh domiflist ubuntu-vm1
# Check for errors
virsh start ubuntu-vm1 --console

Network Issues


 
# Verify bridge configuration
brctl show
ip addr show br0
# Check VM network
virsh domiflist ubuntu-vm1
virsh domifaddr ubuntu-vm1

Permission Issues

 

# Fix ownership
sudo chown -R libvirt-qemu:kvm /var/lib/libvirt/images/
# Check AppArmor
sudo aa-status

Security Best Practices

  1. Regular Updates
    sudo apt update && sudo apt upgrade
  2. Firewall Configuration
    sudo ufw allow 22/tcp
    sudo ufw enable
  3. SELinux/AppArmor
    • Keep security modules enabled
    • Update policies as needed
  4. Resource Limits
    • Set CPU and memory limits
    • Use cgroups for resource control
  5. Network Isolation
    • Use VLANs for network segmentation
    • Implement firewall rules between VMs

Conclusion

KVM on Ubuntu 24.04 provides a robust, enterprise-ready virtualization platform that's both powerful and free. With features like live migration, snapshots, and nested virtualization, it rivals commercial hypervisors while maintaining the flexibility of open source.

Whether you're running a home lab, development environment, or production infrastructure, KVM offers the tools and performance needed for modern virtualization workloads. The combination of command-line tools and graphical interfaces makes it accessible to both beginners and advanced users.

As you continue your virtualization journey, explore advanced features like:

  • GPU passthrough for graphics-intensive workloads
  • SR-IOV for high-performance networking
  • Integration with cloud platforms like OpenStack
  • Automation with tools like Terraform and Ansible

With Ubuntu 24.04 LTS's five-year support cycle, you have a stable foundation for building and maintaining your virtualized infrastructure.

Partager cet article

Twitter LinkedIn

Vous avez un projet similaire ?

Nos experts sont là pour vous accompagner dans vos projets cloud et infrastructure.

Articles similaires

Nathan

Assistant virtuel ECINTELLIGENCE