Linux – Minimize VirtualBox Hard Drive disk

hard drivelinuxUbuntuvirtual machinevirtualbox

I have Ubuntu Server 10.04 TLS installed on a Virtual Machine in a VirtualBox.
The size of the Hard Drive is dynamic growing hard drive and the maximum is 32GB.
At the beginning i had 4GB on the Hard Drive and the size of the .vdi was 4GB.
Lately the size of data on the disk is 15GB but the size of the .vdi is almost 32GB.

Why is that?

How can i pack / optimize / defrag the HD so it will be the same size of the data on the disk?


Best Answer

The reason is that the dynamic disk stores all data, even data that was just temporary and now unlinked. The VBoxManage executable has a command, modifyvhd, which can perform compaction of hard disk images:

VBoxManage modifyhd Ubuntu.vhd --compact

This should get you back down close to the 15GB file size, and might even give you a small performance boost (less data to read / search through). If you really want to optimize the disk you can start by writing zero to the free space, then compacting. This will force the filesystem to free up any blocks that might still be held.

cat /dev/zero > zero ; sync ; rm zero

Additional reference: - see the modifyvhd section, specifically the --compact option.

Related Question