Programster's Blog

Tutorials focusing on Linux, programming, and open-source

Qcow2 - Recover Disk Space on Linux

Sparse qcow2 images can be convenient for allowing you to over-subscribe your disk for your KVM guests in case they might need that space later. For example, you could provision 3 guests each with 400 GB of storage, on a single 500 GB drive. To begin with, the guests will only use a few GB of space each and use more as and when they need it.

Unfortunately, this can also have the opposite effect, causing the sparse image to use more space than was actually allocated to the guest. This is especially noticeable on smaller guests. I noticed that my 20 GB guest was using over 3 times that. The screenshot below shows the storage required of the image before and after I performed the recovery operation I am about to describe.

In order to perform the steps below it is a good idea to make sure you have enough free space. A good rule of thumb is to have an amount free equal to the size of the image you wish to shrink.


Log into the guest with SSH.

Fill the remaining space in the guest with 0's before be filling the guest with an empty file before deleting it. This will allow an operation we use later to know that this area is free.

# Create a temporary file of empty blocks. Uses 1MB blocks to speed things up.
dd if=/dev/zero of=mytempfile bs=1M

# Ensure file is synced to persistant storage and not in memory cache.

# remove the temporary file
rm mytempfile

You should see output similar to below:

dd: error writing 'mytempfile': No space left on device
14538105+0 records in
14538104+0 records out
7443509248 bytes (7.4 GB) copied, 23.6383 s, 315 MB/s

Now shutdown the guest.

sudo shutdown

Now log into your KVM server and move your file to another location, before converting it back to the original location again.

mv guest-image.qcow2 guest-image.qcow2.bak

qemu-img convert -O qcow2 -p \
  guest-image.qcow2.bak \

The -p flag will result in showing a percentage progress of the conversion. The new file will not contain any of the snapshots. I have seen this come up in multiple places [1] [2] and not found a way to preserve the snapshots.

Now you can boot your guest back up.

sudo virsh start

When you are all happy with everything and there are no issues, you can delete the original image that you had been using.

rm guest-image.qcow2.bak


Last updated: 30th October 2022
First published: 16th August 2018