Compacting a Linux VM disk
This only works for dynamic disks.
- cd to /
- dd if=/dev/zero of=ZERO bs=1M
- rm ZERO
- 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
- Shutdown the vm
- 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.