Recover VM Disk Space with virt-sparsify in Linux

This article provides a practical overview of the virt-sparsify tool, explaining its primary role in reclaiming unused host storage from virtual machine disk images on Linux systems. You will learn why virtual disks grow over time, how virt-sparsify identifies and unallocates free blocks, and the exact commands required to shrink your virtual machine disks safely and effectively.


Understanding the Problem of Growing VM Disks

When you create a dynamically allocated (thin-provisioned) virtual disk image, such as a QCOW2 or raw sparse file, it starts small and grows as the guest operating system writes new data. However, when files are deleted inside the virtual machine, the hypervisor does not automatically reclaim that physical disk space. The guest filesystem merely marks those sectors as free for reuse, leaving the underlying virtual disk file on the host at its maximum expanded size.

What is virt-sparsify?

virt-sparsify is a command-line utility provided by the libguestfs (or guestfs-tools) suite in Linux. Its purpose is to inspect the filesystem inside a virtual machine disk image, detect unallocated or zeroed-out blocks, and convert them into empty space within the host filesystem. This process turns a bloated virtual disk back into a sparse file, drastically reducing the physical storage consumed on the host.

Key Benefits of virt-sparsify

How to Install virt-sparsify

On Debian/Ubuntu-based systems:

sudo apt update
sudo apt install libguestfs-tools

On RHEL/CentOS/Fedora systems:

sudo dnf install guestfs-tools

Basic Usage

1. Shut Down the Virtual Machine

Never run virt-sparsify on a disk image attached to a running virtual machine, as this can lead to severe disk corruption.

virsh shutdown <vm-name>

2. Run virt-sparsify (Two-Disk Method)

The recommended and safest method creates a new, compacted target image from the original source image:

virt-sparsify --compress original-disk.qcow2 shrunk-disk.qcow2

In this command:

3. In-Place Sparsification (Alternative Method)

If you lack the free disk space required to duplicate the virtual disk image, you can use the --in-place option:

virt-sparsify --in-place disk.qcow2

Note: The --in-place flag discards unused blocks within the existing file rather than rebuilding it. It does not perform full compression or format conversion, but it executes faster and does not require temporary storage.

4. Verify and Replace

After completing the standard two-disk operation, verify the physical size difference on the host using the ls or du command:

du -sh original-disk.qcow2 shrunk-disk.qcow2

Once verified, you can replace the original file with the new disk image and start the virtual machine:

mv shrunk-disk.qcow2 original-disk.qcow2
virsh start <vm-name>