Free up not used space on a qcow2-image-file on kvm/qemu

disk-imagekvm-virtualizationqcow2qemu

we are using kvm/qemu with qcow2-images for our virtual machines.

qcow2 has this nice feature where the image file only allocates the actually needed space by the virtual-machine. but how do i shrink back the image file, if the virtual machine's allocated space gets smaller?

example:

1.) i create a new image with qcow2 format, size 100GB

2.) i use this image to install ubuntu. installation needs about 10 gb, the image-file grows up to about 10GB. nothing unexpected so far.

3.) i fill up the image with about 40 GB of additional data. the image-file grows up to 50GB. i am ok with that 🙂

4.) this is where it gets strange: i delete all of the 40GB data on the image, but the image-size still eats up 50GB.

question: how do i free up that 40GB of data and shrink the image to the only needed 10 GB?

thanks in advance,
berni

Best Answer

virt-sparsify can do all this with less hassle on your part: http://libguestfs.org/virt-sparsify.1.html