Monday, July 11, 2011

How to shrink qcow2 file

While working with kvm/qemu virtual environment you might encounter need to shrink image file after a removal of unnecessary files, etc. You will be surprised that the space you freed in guest virtual machine is not actually released in host file. It's size remain the same. Here you will know how to shrink it to minimum.

Windows Guest

The idea here is simple, there are few things you have to do:
  1. Delete all unnecessary files, empty recycle bin
  2. Defragment drive (you might need to do this several times, until you see it "compacted" well)
  3. Use sdelete to zero free disk space. Please note that this operation will cause that all drive free space will be filled by zero, so the virtual machine image will grow to the maximum size.
    sdelete -c c:
    

Linux/FreeBSD Guest

dd if=/dev/zero of=./zero bs=1M
sync
rm -f ./zero
Note, the bs parameter is important, since it greatly reduce time necessary to complete this task.

Host

Convert image to the same format that is currently is (e.g. qcow2 => qcow2)... during this procedure it will release unused space.
qemu-img convert -O qcow2 w2k3.qcow2 \
 w2k3-shrinked.qcow2
The process is time consuming and each phase greatly depends on physical disk IO performance and available free space.

5 comments:

  1. thanx,
    what about qemu-img resize?

    ReplyDelete
  2. qemu-img resize doesn't release unused space while keeping the virtual size the same. So take that as we are okay with 20G virtual drive, but while finished with drive clean up (inside virtual machine) we would like release virtual space to host as well.

    ReplyDelete
    Replies
    1. "qemu-img resize doesn't release unused space while keeping the virtual size the same."

      Yes, you are right. I think "qemu-img resize" is better for disk creation with "preallocation=metadata".

      Delete
  3. reading the link for zeroe the disk space must be.

    -z parameter

    "usage: sdelete [-p passes] [-s] [-q] ...
    sdelete [-p passes] [-z|-c] [drive letter] ...
    -a Remove Read-Only attribute
    -c Clean free space
    -p passes Specifies number of overwrite passes (default is 1)
    -q Don't print errors (Quiet)
    -s or -r Recurse subdirectories
    -z Zero free space (good for virtual disk optimization)"

    ReplyDelete
  4. there was a buq in sdelete, parameters '-c' and '-z' were switched in old version.

    ReplyDelete