When managing virtual machines (VMs) in a Linux environment, using Logical Volume Manager (LVM) with Kernel-based Virtual Machine (KVM) provides several benefits. LVM offers flexibility and control over storage allocation, while KVM, combined with virsh, offers a robust virtualization solution. This guide will walk you through the process of setting up LVM logical volumes for your KVM guests using virsh.
Prerequisites
Before proceeding, ensure you have the following:
- A host system running a Linux distribution with KVM and libvirt installed.
- Root or sudo access to the host system.
- Basic knowledge of LVM, KVM, and
virsh.
Configure LVM
- Create a Physical Volume (PV): Identify the disk or partition to use for LVM. For example,
/dev/sdb:
sudo pvcreate /dev/sdb
- Create a Volume Group (VG): Create a volume group named
vg_kvm:
sudo vgcreate vg_kvm /dev/sdb
- Create a Logical Volume (LV): Create a logical volume for your VM. For example, a 20GB logical volume named
lv_guest1:
sudo lvcreate -L 20G -n lv_guest1 vg_kvm
Create and configure the KVM guest
- Install Virt-Manager and create a new VM: If you prefer a graphical interface, you can use
virt-managerto create a new VM. However, for this guide, we will focus on usingvirshfor a command-line approach. - Create a disk image using the Logical Volume: Use
virt-installto create a new VM, specifying the logical volume as the disk:
sudo virt-install \
--name guest1 \
--ram 2048 \
--disk path=/dev/vg_kvm/lv_guest1,bus=virtio \
--vcpus 2 \
--os-type linux \
--os-variant ubuntu20.04 \
--network network=default,model=virtio \
--graphics none \
--console pty,target_type=serial \
--location 'http://archive.ubuntu.com/ubuntu/dists/focal/main/installer-amd64/' \
--extra-args 'console=ttyS0,115200n8 serial'
This command creates a VM named guest1 with 2GB of RAM, 2 CPUs, and an Ubuntu 20.04 installation. The disk is specified as the logical volume we created earlier.
Manage the VM with virsh
- Start the VM:
sudo virsh start guest1
- Connect to the VM console:
sudo virsh console guest1
- Shut down the VM:
sudo virsh shutdown guest1
- Destroy the VM (force shutdown):
sudo virsh destroy guest1
- Undefine the VM (remove configuration):
sudo virsh undefine guest1
Extend or shrink Logical Volumes
LVM allows for flexible management of disk space. To extend the logical volume:
- Extend the Logical Volume:
sudo lvextend -L +10G /dev/vg_kvm/lv_guest1
- Resize the filesystem: If the guest is running, use:
sudo virsh domfsresize guest1 /dev/vg_kvm/lv_guest1 --size +10G
Using LVM with KVM guests provides a dynamic and efficient way to manage storage. This method offers flexibility, allowing for easy resizing and management of disk space. By following this guide, you can efficiently utilize LVM logical volumes for your KVM guests using virsh. This setup not only improves performance but also ensures better resource management and scalability for your virtual environments.