Compacting a Linux VM disk

This only works for dynamic disks.

  1. cd to /
  2. dd if=/dev/zero of=ZERO bs=1M
  3. rm ZERO
  4. cd to /boot and repeat

The dd copies blocks of zeros in 1M chunks to a file named ZERO.  The idea is to go to different mount points and zero out unused space.  Only blocks with zero in them are compacted.

As an alternative to using dd, Ben Armstrong suggests:

cat /dev/zero > zero.dat ; sysnc ; sleep 1 ; sync ; rm zero.dat

  1. Shutdown the vm
  2. Vboxmanage modifyhd /fullpath/to/the.vdi –compact

Vboxmanage is in the “\Program Files\Oracle\VirtualBox” directory.

For Hyper-v, you need the PowerShell Hyper-v GUI Management tools installed.  Then run:

Optimize-VHD -Path /fullpath/to/the.vdi -Mode Full

Mounted disks can’t be fully compacted, but mounting the disk as read-only allows a subset of compaction options.

Advertisements
%d bloggers like this: