Using KVM
Introduction
KVM (Kernel-based Virtual Machine) is a virtualization module in the Linux kernel that allows the kernel to function as a hypervisor. KVM requires a processor with hardware virtualization extensions, such as Intel VT or AMD-V.
Prerequisites
Before getting started with KVM, you need to ensure that your system supports hardware virtualization and that you have the necessary packages installed.
grep -E 'vmx|svm' /proc/cpuinfo
If the above command returns output, your CPU supports hardware virtualization.
Installing KVM
Install KVM and related packages using the following commands:
sudo apt update
sudo apt install qemu-kvm libvirt-daemon-system libvirt-clients bridge-utils
After installation, add your user to the libvirt group to manage virtual machines without sudo:
sudo adduser $USER libvirt
sudo adduser $USER kvm
Starting the Libvirt Service
Start and enable the libvirt service to run at boot:
sudo systemctl enable --now libvirtd
Creating a Virtual Machine
You can create a virtual machine using the virt-install
command. For example, to create a virtual machine with 1GB of RAM and a 20GB disk:
sudo virt-install --name ubuntu-vm --ram 1024 --disk path=/var/lib/libvirt/images/ubuntu-vm.img,size=20 --vcpus 1 --os-type linux --os-variant ubuntu20.04 --network network=default --graphics vnc --cdrom /path/to/ubuntu.iso
Managing Virtual Machines
To manage virtual machines, you can use virsh
, the command-line interface for libvirt.
List all virtual machines:
virsh list --all
Start a virtual machine:
virsh start ubuntu-vm
Shutdown a virtual machine:
virsh shutdown ubuntu-vm
Destroy (force stop) a virtual machine:
virsh destroy ubuntu-vm
Accessing Virtual Machine Console
You can access the virtual machine console using VNC or virsh console
:
virsh console ubuntu-vm
Networking
KVM supports various networking options. The default network setup uses NAT, which allows the guest virtual machines to access the external network through the host.
To list available networks:
virsh net-list --all
Storage
KVM supports different storage options. To list storage pools:
virsh pool-list --all
Create a new storage pool:
virsh pool-define-as mypool dir - - - - "/path/to/storage"
virsh pool-start mypool
virsh pool-autostart mypool
Conclusion
KVM provides a powerful and efficient way to run multiple virtual machines on a Linux host. By following the steps in this tutorial, you should be able to set up and manage virtual machines using KVM. For more advanced configurations, refer to the official documentation and resources.