Is there any way to shrink qcow2 image without converting it raw?

59,664

Solution 1

Noop conversion (qcow2-to-qcow2) removes sparse space:

qemu-img convert -O qcow2 source.qcow2 shrunk.qcow2

You can also try add compression (-c) to the output image:

qemu-img convert -c -O qcow2 source.qcow2 shrunk.qcow2

Before running above command be sure to shutdown the VM. After you are satisfied with the result, you can rename shrunk.qcow2 to original name your VM config wants.

Solution 2

Try virt-sparsify - it will zerofill the unused blocks in the image and then deduplicate the zeroes.

Solution 3

I use virt-sparsify:

virt-sparsify /path/to/source.qcow2 --compress /path/to/output.qcow2

Solution 4

I have been successfully using this procedure many times now. In short, first in the virtual guest fill all free space on all partitions with zeroes:

dd if=/dev/zero of=zerofile bs=1M

When done, empty the disk cache with sync, remove the zerofile(s) and shut down the guest. On the host side convert the image (raw to qcow2 in this example):

qemu-img convert -f raw -O qcow2 guest.img guest-copy.qcow2

This will automatically sparsify the image. Also remember to update the vm definition file if the image file suffix is changed.

A benefit of this method over virt-sparsify is that in this method the guest can be up while the zeros are written, and hence the downtime is shorter. If you can afford a longer downtime, then use virt-sparsify, as it takes care of the whole process with just one command, and also gives useful feedback during the process.

Share:
59,664

Related videos on Youtube

YOU
Author by

YOU

Updated on September 18, 2022

Comments

  • YOU
    YOU almost 2 years

    Is there any way to shrink qcow2 image without converting it raw?

    I cannot convert it to raw because I don't have disk space enough for raw image.

  • YOU
    YOU almost 12 years
    Thanks for you answer, but virt-sparsify said it cannot resize disk images and I found virt-resize from that, but looks like I still need to allocate spaces to expand (that I don't have enough spaces on my harddisk). Anyway, Thank you very much for you info.
  • Michael Hampton
    Michael Hampton over 6 years
    @YOU Current versions of virt-sparsify can work in-place without allocating space for a complete copy of the disk image.
  • Wang
    Wang almost 4 years
    I doubt this is going to shrink much if you do not zero-out the free disk space first. zero-out the free disk space takes very long time and host disk space.
  • Wes
    Wes over 3 years
    @Wang if you enable TRIM support first then it should be able to compress better. pve.proxmox.com/wiki/Shrink_Qcow2_Disk_Files
  • Oleg Neumyvakin
    Oleg Neumyvakin over 2 years
    From man: Since virt-sparsify ≥ 1.26, you can now sparsify a disk image in place by doing: virt-sparsify --in-place disk.img