Reclaim empty space from, Shrink disk of qcow2 disk file

To reclaim disk space (in other words to shrink disk space) of qcow2 disk file you need to run following steps.

1. Fill guest disk with empty file

This is required since disk does not really hold its configured size, instead it has a sparse file format in creation time. After a while disk gets writes, temporary file creations/deletions that result non zero blocks in qcow2 file which are useless in reality (i.e. temporarily created file and deleted later). So to gain this space we’ll create a file that takes all space available in backing store (here qcow2 file). This file will only contain zeros. That way qemu-img will skip copying zeros and it will only mark the meta-data of zero sequence (for example length of it).

To do this, turn on virtual machine and in virtual machine’s terminal (you can use ssh to connect):

dd if=/dev/zero of=/tempzerofile
 dd will read from /dev/zero and write to /tempzerofile until all disk space is full. Now remove the file:
 rm /tempzerofile

2. Reclaim unused disk space from qcow2 file

Now turn virtual machine off, and run below command in your host machine to reclaim unused space back. Remember this space is marked with zeros and these type of files are called “sparse file”.

qemu-img convert -O qcow2 image.qcow2 shrinked_image.qcow2

where image is the original image whose size is big and we want to shrink it. shrinked_image is the destination image we want to create.

Leave a Reply

Your email address will not be published. Required fields are marked *