QEMU+KVM, reclaim disk space
After some time qcow2 images tend -especially after taking snapshots- to grow bigger and bigger, even bigger than the maximum size specified at creation time.
QEMU provides a tool called virt-sparsify (install libguestfs-tools
package in CentOS 7) that can effectively make a virtual machine disk thin provisioned (space is not preallocated, only the actual space needed is used).
virt-sparsify has a nice number of options, the most interesting one is --in-place
, it tells QEMU to shrink the volume in place without requiring any addition space.
BEFORE RUNNING THE COMMAND POWER OFF THE VIRTUAL MACHINE
[root@CentOS vm]# time virt-sparsify --in-place image.qcow2
Trimming /dev/sda1 ...
Trimming /dev/sda2 ...
Clearing Linux swap on /dev/sda3 ...
Sparsify in-place operation completed with no errors.
real 0m5.791s
user 0m0.031s
sys 0m0.050s
In case libguestfs
utilities cannot be installed, QEMU’s own images manipulation tool comes to rescue; it does not shrink the image file in-place
but it is still better than nothing.
Zerofill the all the unused space in the virtual disk drive prior to running qemu-img convert
command to maximize its effectiveness.
[root@CentOS vm]# dd if=/dev/zero of=/mytempfile && rm /mytempfile
[root@CentOS vm]# time qemu-img convert -O qcow2 image.qcow2 image-shrinked.qcow2
Be aware that the command ls
does not understand sparseness, use df -h
or du -sh
to check the actual space used before and after the shrinking operation.