How to reduce the size of KVM QCOW2 images that grow out of hand

This is a very short and practical article useful to anyone who uses KVM in production and somehow needs to reduce the space used by a QCOW2 disk image. It is not enough to just free up space from the VM itself. Once a QCOW2 grows in size it never goes back down, on its own accord.

To do this quickly and safely I recommend the following steps:

  1. Free up any space in the disk from within the VM
  2. Shutdown the VM
  3. Backup the disk image that you want to reduce(Optional, if have a lot of faith in Unix commands that you never heard about before )
  4. from the directory where your image is stored call:
    virt-sparsify — in-place defenders-disk01.qcow2
  5. Once the command completes successfully, restart the VM
  6. Verify that the disk space usage went down using df -kh. Should work.

Resources

https://maunium.net/blog/resizing-qcow2-images/

https://libguestfs.org/virt-sparsify.1.html