Wednesday 17 August 2011

Shrink a KVM disk image

This only applies to images in the qcow2 format and does not apply to raw images.


First, we should clear as many unwanted files as possible from the machine.

Because simply deleting files with rm does not actually remove the bits (it removes entries in the directory table) we therefore need to convert unused space to an easily compressible state.

We can do that by writing a bunch of zero's to the disk using this command;

cat /dev/zero > zero.fill;sync;sleep 1;sync;rm -f zero.fill

Next, we use qemu to shrink the file (compress unused space)

qemu-img convert -c -f qcow2 source.img -O qcow2 dest.img

No comments: