How to make a virtual machine disk sparse

When someone had deleted files to reduce the virtual machine img size, you need to do some actions in the server to return this free space to the server.

Steps

  1. Install libguestfs-tools
apt install libguestfs-tools
  1. Check the real size of the virtual machine size
qemu-img info file.qcow2

The output will be something that contains this information:

disk size: 10G
  1. Make a backup copy of the img file
cp -p file.qcow2 /another/directory/file.backup.qcow2
  1. Now use virt-sparsify
virt-sparsify --in-place file.qcow2
  1. Check if the virtual img size has been reduced
qemu-img info file.qcow2

The output now shows that the size has decreased:

disk size: 5G
  1. Check if the virtual machine works.
  2. If the virtual machine works, then remove the img file backup.

Extended information about to reduce image size.