Tip: compress raw disk images using qcow2

$ qemu-img convert -c -f raw -O qcow2 win.img winq.img
$ ls -lh win*
-rw-r--r--. 1 root   root    10G May 18 14:34 win.img
-rw-r--r--. 1 rjones rjones 6.5G May 18 14:59 winq.img

Of course the degree of compression you get depends on the amount of zeroed free space in the image, and the amount by which qcow2 is able to compress the other blocks containing data.

qcow2 uses zlib for compression, so the compression won’t be that spectacular. It’s better to keep the filesystems “sparse” in the first place, by ensuring unused disk blocks are zeroed.

For ext2/3 filesystems, Fedora ships a utility called zerofree, which you can either run inside the guest, or run offline from guestfish. This turns unused filesystem blocks into zeroes, which will make outside compression eg with qcow2 much more efficient. For other filesystems, the usual trick is to create a large file of all zeroes until you fill up the free space, then delete it.

qcow2 files are completely interchangeable with raw disk images:

$ virt-df -h win.img
Filesystem                                Size       Used  Available  Use%
win.img:/dev/vda1                       100.0M      24.1M      75.9M   25%
win.img:/dev/vda2                         9.9G       7.4G       2.5G   75%
$ virt-df -h winq.img
Filesystem                                Size       Used  Available  Use%
winq.img:/dev/vda1                      100.0M      24.1M      75.9M   25%
winq.img:/dev/vda2                        9.9G       7.4G       2.5G   75%

4 Comments

Filed under Uncategorized

4 responses to “Tip: compress raw disk images using qcow2

  1. Anil

    How to confirm whether a qcow2 img is in compressed or not? qemu-img info was not usable šŸ˜¦

  2. lzap

    Googled this šŸ™‚ I am wondering if I can specify compression level. I mean I would like to distribute an appliance and I care about size – so I would love to compress it with “-9” option for the smallest size. I guess this needs to be hacked somehow šŸ˜¦

  3. Pingback: Zerofree your filesystem | blog.witalis.net

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.