Thursday, July 12, 2012

Compacting VirtualBox Linux partitions

After re-installing Debian in a VirtualBox VM guest, the dynamically-allocated VDI obviously still contained the old data. Google didn't find a quick recipe on how to fix this - so here it is:

  1. Mount the VDI using:
    vdfuse -f volume.vdi /mnt
  2. zerofree the ext partition (look at the partition table and the file sizes in /mnt if unsure):
    zerofree /mnt/Partition1
  3. Compact the VDI:
    VBoxManage modifyhd volume.vdi --compact
This approach works from a Linux host for ext2/ext3 partitions within the VDI. It should also be possible to run zerofree from within the guest system, after changing to runlevel 1 and re-mounting the system partition read-only.

Update: The first two steps also work with VMDKs. Before Step 3, the VMDK has to be converted to VDI though:
VBoxManage clonehd volume.vmdk volume.vdi --format VDI