- 1 Introduction
- 2 Comparing KVM with Other Virtualization Technologies
- 3 Building a KVM Environment on Ubuntu [Installation & Initial Setup]
- 4 Creating and Managing Virtual Machines
- 5 Network Configuration and Expansion
- 6 Storage Management and Disk Operations
- 7 Guest OS Installation and Operation
- 8 Practical Use Cases and Automation Tips
- 9 Troubleshooting and Common Error Solutions
- 10 Security and Performance Optimization
- 11 Summary & Further Learning Resources
- 12 Command Quick Reference & Common Settings (Cheat Sheet)
- 13 FAQ (Frequently Asked Questions)
- 13.1 Q1: What are the differences between KVM, VirtualBox, and VMware?
- 13.2 Q2: How do I back up and restore virtual machines?
- 13.3 Q3: How can I use USB devices inside a virtual machine?
- 13.4 Q4: How can I automatically start a VM when the host boots?
- 13.5 Q5: What should I do if VM performance is slow?
- 13.6 Q6: I’m having trouble with network settings. What should I check?
- 13.7 Q7: Is it possible to build clusters or HA setups with KVM?
Introduction
Ubuntu is one of the most widely used Linux distributions around the world. It is popular in a variety of scenarios, from individual users to enterprise environments, and is frequently chosen for server deployment and development setups. If you want to implement advanced virtualization on Ubuntu, one of the most powerful solutions is KVM (Kernel-based Virtual Machine).
KVM is a hypervisor technology that is built directly into the Linux kernel. By leveraging hardware virtualization extensions (such as Intel VT or AMD-V), KVM delivers high performance and stability. Being open-source, KVM enables you to build a full-fledged virtualization infrastructure with minimal cost.
Virtualization technology can sound intimidating at first. However, with Ubuntu and KVM, even beginners can easily create and manage virtual machines. Of course, KVM is also recommended for intermediate users who want to optimize physical server resources, as well as engineers looking to virtualize production systems.
This article provides a comprehensive guide to building a KVM-based virtualization environment on Ubuntu, including installation steps, basic usage, practical tips, and troubleshooting solutions. If you are considering adopting KVM or want to make the most of Ubuntu’s virtualization features, be sure to read until the end.
Comparing KVM with Other Virtualization Technologies
There are various virtualization technologies available, but on Ubuntu, KVM, VirtualBox, and VMware are commonly used. This section explains the features and differences of each, as well as the pros and cons of choosing KVM.
Major Types of Virtualization Technologies
- KVM (Kernel-based Virtual Machine)
KVM is a virtualization feature built into the Linux kernel, and requires Linux as the host OS. By utilizing hardware virtualization extensions (Intel VT or AMD-V), KVM offers high performance virtual machines suitable for production environments. It supports flexible management through command-line tools and GUI managers like virt-manager. - VirtualBox
VirtualBox is a desktop-oriented virtualization software provided by Oracle. It runs on Windows, Mac, and Linux, and features an easy-to-understand interface, making it a popular choice for personal and educational use. However, compared to KVM, it is less suitable for commercial or high-load environments. - VMware (Workstation/ESXi, etc.)
VMware is a widely used commercial virtualization solution, known for its rich feature set and comprehensive support. However, a paid license is required. While it is often chosen for large-scale enterprise deployments, the cost can be a consideration.
Advantages of KVM
- High Performance and Stability
KVM runs as part of the Linux kernel, providing efficient resource management and fine-grained control over CPU and memory allocation for each VM. It is highly stable for running real business systems. - Open Source and No Licensing Fees
KVM is completely open-source and free to use, making it ideal for building low-cost virtualization platforms. - Rich Management Tools and Automation Support
A variety of management options are available, including command-line tools (virsh, virt-install) and GUI tools (virt-manager). KVM is also well-suited for automation and scripting, making it ideal for DevOps and infrastructure management.
Disadvantages of KVM
- Linux-Only Host Requirement
Since KVM requires the Linux kernel, it cannot be used as a host on Windows or Mac environments. - Linux Knowledge Needed for Initial Setup and Troubleshooting
While GUI tools are available, some network settings and advanced tuning may require command-line operations or Linux-specific knowledge.
When Should You Choose KVM?
- When you want to efficiently utilize physical server resources
- When you need virtualization for production systems or server applications
- When you want to build a robust virtualization infrastructure at low cost
- When you want to automate Linux server operations or infrastructure management
KVM is an excellent virtualization technology not only for experienced Linux users and engineers, but also for those who want to try running full-scale servers in the future.
Building a KVM Environment on Ubuntu [Installation & Initial Setup]
To use KVM on Ubuntu, you need to meet certain prerequisites, perform some preparations, and then carry out the installation. This section walks you through the required steps to get started with KVM, with tips to help beginners set up the environment smoothly.
Prerequisites and Pre-Checks
To use KVM, your computer or server’s CPU must support virtualization extensions (Intel VT or AMD-V).
First, check if hardware virtualization is enabled with the following command:
egrep -c '(vmx|svm)' /proc/cpuinfo
If the output is 1 or greater, virtualization support is available.
Additionally, you must be running a 64-bit version of Ubuntu.
Installing KVM and Required Packages
Install the KVM core and related tools (such as libvirt and virt-manager) using the following commands:
sudo apt update
sudo apt install qemu-kvm libvirt-daemon-system libvirt-clients bridge-utils virt-manager
qemu-kvm
: Core KVM virtualization packagelibvirt-daemon-system
,libvirt-clients
: Management services for virtual machinesbridge-utils
: Tools for network bridge setupvirt-manager
: GUI tool for managing virtual machines
Configuring User Groups and Permissions
After installation, add your current user to the kvm
and libvirt
groups. This allows you to manage VMs without root privileges.
sudo usermod -aG libvirt $(whoami)
sudo usermod -aG kvm $(whoami)
Log out and log back in, or reboot, to apply the changes.
Verifying KVM Service Status
Check that KVM is correctly installed and the service is running:
sudo systemctl status libvirtd
If it shows “active (running)”, everything is working.
You can also verify KVM with this command:
virsh list --all
If you see a (currently empty) list of VMs, the KVM environment is set up correctly.
Creating and Managing Virtual Machines
Once your KVM environment is ready, you can start creating and operating virtual machines. With KVM, you can use both graphical tools (virt-manager) and command-line tools (virt-install, virsh), depending on your needs. Here, we introduce both approaches.
Creating a VM Using virt-manager (GUI)
virt-manager is a graphical tool that allows you to easily create and manage virtual machines. If you’re using a Linux desktop environment, virt-manager is very convenient.
- Launch
virt-manager
from your applications menu or the command line. - Click the “New” button in the top left corner.
- Select the location of your installation media (such as an ISO image), and choose the guest OS type (e.g., Ubuntu, Windows).
- Set the number of CPUs, memory size, disk size, etc. for the VM.
- Review the settings and click “Finish” to create the VM. The installation screen will appear.
With virt-manager, you can also start, stop, and reboot VMs, take snapshots, and add networks or disks via an intuitive interface.
Creating a VM Using virt-install (CLI)
For server or remote environments, it’s often easier to create VMs from the command line.
Here’s a basic example using virt-install
:
sudo virt-install \
--name ubuntu-vm \
--memory 2048 \
--vcpus 2 \
--disk size=20 \
--cdrom /path/to/ubuntu.iso \
--os-type linux \
--os-variant ubuntu20.04 \
--network network=default \
--graphics vnc
--name
: Name of the virtual machine--memory
: Memory allocation (in MB)--vcpus
: Number of CPU cores--disk size=20
: Disk size (in GB)--cdrom
: Path to the ISO image for installation--os-type
,--os-variant
: OS type and version--network
: Network to connect to--graphics
: Graphics mode (e.g., VNC)
After running this command, the VM will start and the installation screen will be displayed via VNC or another specified method.
Starting, Stopping, Deleting, and Snapshotting Virtual Machines
Managing your virtual machines with KVM is straightforward. Here are some commonly used commands:
- Start a virtual machine:
virsh start <vm-name>
- Shutdown a virtual machine:
virsh shutdown <vm-name>
- Force stop a virtual machine:
virsh destroy <vm-name>
- Delete a virtual machine (note: also deletes its disk):
virsh undefine <vm-name>
- Create a snapshot:
virsh snapshot-create-as <vm-name> <snapshot-name>
You can also perform these operations from the virt-manager GUI.
Network Configuration and Expansion
Network settings are crucial when running virtual machines with KVM. While default settings work for many cases, business or production environments often require customization. This section explains basic KVM networking and commonly used advanced settings.
Differences Between Default NAT (virbr0) and Bridge Networks
When KVM is installed, it automatically creates a virtual network bridge called “virbr0”. This is a NAT (Network Address Translation) network, which has the following features:
- virbr0 (NAT mode) features:
- VMs can access the external internet
- However, direct access to VMs from the host or other networks requires port forwarding
- Best for home labs, development, or testing
On the other hand, a “bridge network” allows VMs to join the same network segment as the physical host.
- Bridge network features:
- VMs join the same network segment as the host
- Physical PCs or other servers can directly access VMs
- Ideal for internal servers or production services
Creating and Configuring a Custom Bridge (for LAN Access)
If you want VMs to be directly accessible from other PCs or servers, create a bridge network. Below is a typical procedure (assuming the host’s NIC is eth0
):
- Install bridge-utils (skip if already installed)
sudo apt install bridge-utils
- Edit the network configuration file
On Ubuntu 18.04 and later, Netplan is used.
Edit/etc/netplan/01-netcfg.yaml
, for example:
network:
version: 2
renderer: networkd
ethernets:
eth0:
dhcp4: no
bridges:
br0:
interfaces: [eth0]
dhcp4: yes
- Apply the settings
sudo netplan apply
- Add the new bridge (br0) to KVM network
Switch the network adapter of your VM to br0 using virt-manager or virsh.
Assigning Static IPs & Setting Port Forwarding
- Assigning Static IPs
Typically, set a static IP in the VM’s OS, or use the DHCP server to assign a fixed IP by MAC address. - Port Forwarding (when using NAT)
With virsh or libvirt XML, you can forward ports (e.g., SSH or web server) from host to VM. Example for forwarding SSH to port 22:
virsh nat-forward --network default --add-port tcp:2222:22
For more complex setups, you can also edit libvirt’s configuration files or use firewalld.
Storage Management and Disk Operations
Proper storage design and disk management are also essential when operating virtual machines with KVM. This section explains the different types of virtual disks, how to create them, storage pool management, disk expansion, and the use of snapshots.
Types and Uses of Virtual Disks (qcow2, raw)
KVM mainly supports two types of virtual disk formats:
- qcow2 Format
- The standard virtual disk format for KVM
- Supports snapshots, compression, and efficient disk space usage
- Best for flexible operation or testing environments
- raw Format
- A simple format with no compression or conversion
- Ideal when you need maximum disk I/O performance
In most cases, qcow2 is recommended, but you can choose based on your specific needs.
Creating and Managing Storage Pools
KVM uses the concept of “storage pools” to manage the disk space used by virtual machines.
- Default Storage Pool
By default,/var/lib/libvirt/images/
is used as the storage pool, and new virtual disks are created in this directory. - Creating a New Storage Pool (Example)
- Create a directory:
sudo mkdir /data/kvm-images
sudo chown libvirt-qemu:kvm /data/kvm-images - Add a new pool using virt-manager or the virsh command. With virsh:
virsh pool-define-as --name mypool --type dir --target /data/kvm-images
virsh pool-autostart mypool
virsh pool-start mypool
Expanding Virtual Disks and Using Snapshots
- Expanding a Virtual Disk
If you need to increase the disk size, use theqemu-img
command (works for both qcow2 and raw):
sudo qemu-img resize /var/lib/libvirt/images/ubuntu-vm.qcow2 +10G
After this, expand the partition and file system within the guest OS as needed.
- Using Snapshots
With qcow2 disks, you can create snapshots to save the current state of your VM at any time.
virsh snapshot-create-as <vm-name> <snapshot-name>
Snapshots are very useful for backing up before upgrades, rolling back tests, or recovering from configuration errors.
Guest OS Installation and Operation
This section explains how to install and run operating systems on KVM virtual machines. We’ll cover the installation of typical guest OSes, handling ISO images, and tips for improving performance during operation.
Installing Popular Guest OSes
KVM allows you to run a variety of OSes, such as Ubuntu, CentOS, and Windows. Below are sample installation steps for Ubuntu and Windows:
- For Ubuntu
- Download the latest Ubuntu ISO from the official website.
- In virt-manager, choose “Create a new virtual machine”, select “Local install media”, and specify the ISO file.
- Set the VM’s CPU, memory, and disk size, then start the installation.
- Follow the on-screen instructions to complete the standard Ubuntu installation.
- For Windows
- Download a Windows evaluation ISO from the official Microsoft site.
- Create a new VM in virt-manager or using virt-install, and select the ISO as installation media.
- For better disk and network performance, mount the virtio drivers ISO as an additional CD drive and install the drivers during setup.
Obtaining and Mounting ISO Images
- Download ISO images from official sources for the OS you want to install.
- Specify the path to the ISO file when creating a new virtual machine; it will be mounted as a virtual CD/DVD drive.
- If needed, you can mount multiple ISOs at once (e.g., OS and drivers).
Tips for Guest OS Operation and Performance
- Optimize Resource Allocation
Assign appropriate amounts of CPU and memory to each VM. Over-allocating resources can negatively affect the host OS and other VMs. - Install virtio Drivers
For Windows or older Linux guests, installing virtio drivers can significantly boost disk and network performance. - Disable Unused Services
Turn off unnecessary services and background programs in the guest OS to maximize available resources. - Use KVM Guest Tools
Install the QEMU Guest Agent to improve the accuracy of VM management and support features like clean shutdown.
Practical Use Cases and Automation Tips
KVM isn’t just for creating and running VMs — it can be leveraged in various business and development scenarios. Pairing it with scripts or automation tools can also make management much more efficient. This section shares practical KVM use cases and automation ideas.
Server Use Cases
- Isolated Development and Testing Environments
Provision a separate VM for each project, allowing you to freely switch OS versions and software stacks without impacting production. This is a major advantage when testing new OS versions or software updates. - Building Internal Services
Separate critical services (file servers, web servers, databases, etc.) into individual VMs, so failures affect only a limited scope.
Backups and snapshots are easy on a per-VM basis.
Automation Examples Using CLI or Ansible
- Automated VM Creation via CLI
Use scripts to automatically executevirt-install
orvirsh
commands for creating and managing multiple VMs. Example using a shell script:
for i in {1..5}
do
virt-install --name test-vm-$i --memory 1024 --vcpus 1 \
--disk size=10 --cdrom /path/to/ubuntu.iso \
--os-type linux --os-variant ubuntu20.04 --graphics none --network network=default --noautoconsole
done
- Automating with Ansible
With the infrastructure automation tool Ansible, you can describe VM creation, initial setup, and application deployment in playbooks — automating the entire process.
This is especially effective when managing a large number of servers or when consistency is critical.
Tips for Cloud-Like Operations
- VM Templating
Save commonly used initial VM states as templates, allowing you to quickly deploy new servers. - API Integration and Web-Based Management
libvirt provides an API for integration with custom tools or other management systems. For large environments, use web-based management tools (like Cockpit) to manage VMs visually.
Troubleshooting and Common Error Solutions
While running KVM, you may encounter issues such as failed VM startup or network connectivity problems. This section covers common problems, how to resolve them, and how to check logs and use support resources.
Common Issues with KVM
- VM Fails to Start or Create
- Hardware virtualization (Intel VT, AMD-V) is disabled
- Insufficient memory or disk space allocated
- Incorrect storage pool or ISO path
- Network Connectivity Issues
- VM network adapter not configured correctly
- Errors in bridge or NAT settings, or DHCP assignment failures
- Firewall or security restrictions
- Poor Performance
- Resource overallocation or underallocation
- Missing virtio drivers (especially for Windows guests)
- Disk I/O bottlenecks
How to Check Logs and Basic Troubleshooting Flow
When issues occur, checking logs is critical.
- Check System Logs
sudo journalctl -xe
Look for error messages related to KVM or libvirt.
- Check libvirt Logs
Review log files under/var/log/libvirt/
(e.g., libvirtd.log). - Check VM-Specific Logs
In virt-manager or virsh, review the “Details” or “Logs” tab for each VM. - Check Network Status
ip a
brctl show
virsh net-list --all
Check the current network connections and bridge setup.
Basic Troubleshooting Steps
- Identify when the issue started and clarify the symptoms
- Check the above logs and configuration files
- If needed, edit configuration files, restart services, or recreate the VM
Leveraging Official Documentation and Community Resources
If you get stuck, these resources can be invaluable:
- Official Documentation
Ubuntu Official KVM Guide
libvirt Official Documentation - Community Forums & Q&A Sites
- Ubuntu Forums
- Ask Ubuntu
- Stack Overflow
- Search for Error Messages
Try searching for error messages in both English and your native language — you’ll often find plenty of solutions.
Security and Performance Optimization
To operate your KVM environment safely and efficiently, security measures and performance optimization are essential. This section covers key points for protecting your virtualization infrastructure and practical tips for maximizing resource efficiency.
Strengthening Security in Virtualized Environments
- Disable Unnecessary Services and Use Minimal Setups
Disable unused services inside your VMs to reduce the attack surface. Likewise, stop unnecessary services on the host OS. - Firewall and Access Controls
Set up firewalls (such as ufw or firewalld) properly on both host and guest systems to block unauthorized external access.
For SSH, consider changing the port number, using key-based authentication, and implementing fail2ban for added protection. - VM Isolation (Network Segmentation)
Separate critical servers onto different virtual networks or physical segments to minimize the impact if a breach occurs. - Regular Updates
Keep both your host and guest OS up to date with the latest security patches and software updates.
Optimizing Resource Allocation (CPU/Memory/Disk I/O)
- Basic Resource Management
Allocate CPU and memory appropriately to each VM and leave headroom on the host for overall system stability.
Over-allocation can cause performance degradation for both the host and other VMs. - Disk I/O Optimization
Disk performance often becomes a bottleneck. Assign fast SSD storage to important VMs for best results.
Also, using too many snapshots with qcow2 disks can reduce performance, so balance usage accordingly. - Leverage virtio Drivers
Install virtio drivers in guest OSes to greatly improve disk and network performance.
Automating Backups and Snapshots
- Schedule Regular Snapshots
Take regular snapshots of production VMs so you can quickly recover in case of failure. - Back Up Disk Images and Config Files
Back up your virtual disk images (qcow2/raw files) and libvirt XML configuration files regularly to another storage device or external server. - Integrate with Automation Tools
Use cron jobs or automation tools like Ansible to schedule backups and snapshot creation automatically.
Summary & Further Learning Resources
This article has covered building and operating a KVM virtualization environment on Ubuntu—from installation to advanced usage, troubleshooting, security, and performance tuning. Let’s review the key points and introduce resources to help you continue learning.
Summary of Key Points
- KVM Overview and Benefits
KVM is an open-source, high-performance virtualization solution widely used with Ubuntu servers. - Step-by-Step from Installation to Operation
We walked through checking virtualization support, installing packages, setting user permissions, creating VMs, and performing basic operations. - Practical Tips on Networking, Storage, and Operations
You learned how to configure NAT or bridge networks, manage storage pools, expand disks, and utilize snapshots. - Troubleshooting and Security
We covered common error handling, how to check logs, and points for secure and efficient operation.
Next Steps & Recommended Learning Resources
- Official Documentation
- Ubuntu Official KVM Guide
- libvirt Official Documentation
- Ask Ubuntu
- Stack Overflow (English)
Once you’ve mastered the basics, KVM can be used for everything from personal projects to enterprise infrastructure. Use this guide as a foundation and keep exploring based on your goals and environment.
Command Quick Reference & Common Settings (Cheat Sheet)
Having a quick reference of useful commands and configuration examples for KVM and libvirt is very handy for daily VM management. This section lists common commands and compact settings examples for networks and disks.
Main KVM/virsh/virt-manager Commands
- List all virtual machines
virsh list --all
- Start a virtual machine
virsh start <vm-name>
- Shutdown a virtual machine
virsh shutdown <vm-name>
- Force stop a virtual machine
virsh destroy <vm-name>
- Create a new virtual machine (virt-install)
virt-install --name <name> --memory <MB> --vcpus <cores> \
--disk size=<GB> --cdrom <ISO path> \
--os-type linux --os-variant ubuntu20.04
- Delete a virtual machine (settings only)
virsh undefine <vm-name>
Network & Bridge Configuration Examples
- List current networks
virsh net-list --all
- Create a new network (XML example)
Place an XML file under/etc/libvirt/qemu/networks/
,
then activate it withvirsh net-define <filename>
andvirsh net-start <network-name>
Storage Management & Disk Operations Examples
- List storage pools
virsh pool-list --all
- Expand a virtual disk
sudo qemu-img resize /path/to/disk.qcow2 +10G
- Create a snapshot
virsh snapshot-create-as <vm-name> <snapshot-name>
Other Useful Tips
- Set VM to start automatically on host boot
virsh autostart <vm-name>
- Get detailed information about a VM
virsh dominfo <vm-name>
- Start virt-manager (GUI)
virt-manager
FAQ (Frequently Asked Questions)
Here are answers to common questions from readers about KVM and Ubuntu virtualization environments. Use these for troubleshooting and daily operations.
Q1: What are the differences between KVM, VirtualBox, and VMware?
A1: KVM is a high-performance virtualization platform integrated into the Linux kernel and is best suited for servers and production use. VirtualBox is aimed at desktop use, while VMware is rich in features and support for large-scale commercial environments. KVM is recommended when you want high performance at low cost.
Q2: How do I back up and restore virtual machines?
A2: You can easily back up by copying the virtual disk images (qcow2 or raw files). It’s also recommended to save virsh snapshots and the VM’s XML config files for smooth restoration.
Q3: How can I use USB devices inside a virtual machine?
A3: Use the “Add Hardware” feature in virt-manager or set up USB passthrough with virsh. This allows you to use USB drives, external HDDs, printers, etc. inside your VMs.
Q4: How can I automatically start a VM when the host boots?
A4: Run virsh autostart <vm-name>
to configure that VM to start automatically when the host OS boots.
Q5: What should I do if VM performance is slow?
A5: Review and adjust CPU/memory allocation, optimize disk I/O (use faster storage or switch from qcow2 to raw), and install virtio drivers in the guest OS.
Q6: I’m having trouble with network settings. What should I check?
A6: Use virsh or brctl to check the network status. Review and, if needed, recreate virtual networks or edit bridge settings with Netplan or NetworkManager.
Q7: Is it possible to build clusters or HA setups with KVM?
A7: Yes. You can combine KVM with tools like Pacemaker, Corosync, and shared storage (NFS, iSCSI, etc.) to enable high availability (HA) clusters and live migration of VMs. Advanced knowledge is required.