Compacting VirtualBox Disks

Virtual machines (VMs) long have been a useful tool in the house network. At any moment there usually are a dozen or more VMs on the office desktop. Although the office desktop has ample disk space, old school computer habits mean keeping the VM virtual disks as small as practical.

VirtualBox supports this by compacting the virtual disk. The basic command:

vboxmanage modifyvdi /full/path/to/disk.vdi compact

VirtualBox defaults to using “dynamic” disks. This means much of the disk is “sparse,” or unused. Yet virtual disks are prone to the same fragmentation as physical disks. File systems typically do not delete files and only delete the pointers to find the file, leaving the contents of the file on the disk. While not as readily noticed in physical disks, with dynamic or sparse virtual disks this means the disk size tends to grow.

Before compacting a virtual disk this unused and remnant disk space in all partitions needs to be wiped.

With Linux systems this can be done by creating and deleting a dummy file of all zeroes:

dd if=/dev/zero of=/bigfile bs=4M status=progress; rm -f /bigfile

If the virtual disk has multiple partitions then modify the file path as needed to wipe unused disk space in each partition.

The same command can be used with Windows virtual disks if the disk partitions are mounted from a Linux system. If not there is a handy Windows utility called sdelete that will wipe unused disk space.

After wiping unused disk space the virtual disk can be compacted. Compacting cannot be performed on a virtual disk that is in use or is encrypted. For the former that means the VM must be powered off.

The vboxmanage command can be used to find and list all virtual disks. The respective VM configuration file can be queried with grep -i "CRYPT/Keystore" $VM_CONFIG to determine whether a disk is encrypted.

A shell script will help coordinate all of this into a more manageable one-shot task.

Posted: Category: Tutorial Tagged: Virtual Machines

Next: Updating a Testing Partition Without Rebooting

Previous: Booting a 486 from a CD