DEV Community

Michael Sanford
Michael Sanford

Posted on • Originally published at Medium on

Clean up and compact your VDI

TL;DR

Guest OS: sudo sfill -llvz /

Host OS: VBoxManage modifyhd --compact \<\_.vdi\>
Enter fullscreen mode Exit fullscreen mode

Details

My VirtualBox thin server had put on a few pounds over the months of guest OS database imports, static resource creation, temp file creation, log rotation, and a bunch of other stuff I don’t need to store indefinitely. Every time more sectors need to be called upon to store something in the guest, VirtualBox will grow the physical VDI image accordingly, up to the maximum size specified. However, when you delete files from the guest system, the VDI doesn’t shrink accordingly (and with good reason).

If you have implemented a backup strategy — as I have with Time Machine — you probably don’t want to back up a 30 GB VDI file every single time a single bit changes (for example, when you boot the virtual machine). This is particularly true when you have deleted old databases, resources and logs, and the guest OS really only represents about 5 GB of data.

VBoxManage modifyhd allows you to compact a physical VDI, but with one important precondition, it only truncates zeros in the guest from the VDI:

With the — compact option, can be used to compact disk images, i.e. remove blocks that only contains zeros. This will shrink a dynamically allocated image again; it will reduce the physical size of the image without affecting the logical size of the virtual disk. Compaction works both for base images and for diff images created as part of a snapshot.

So simply having deleted a file from your guest will not allow you to reclaim space. You have to zerofill the free space on guest OS’s volumes.

In your Guest (in this case, Ubuntu Server 12.04.02 LTS)

sudo apt-get install secure-delete sudo sfill -llvz /
Enter fullscreen mode Exit fullscreen mode

The -ll option writes only one pass (instead of the default 38) and the -z option replaces the single pass of data from /dev/urandom with zeros, which is what VBoxManage is looking for.

In your host:

VBoxManage modifyhd --compact \<virtual\_disk\_file.vdi\>
Enter fullscreen mode Exit fullscreen mode

I shrunk mine from 25 GB to 5 GB in a single step. My SSD allowed me to zerofill about 20 GB in the guest and compact the VDI in less than 90 seconds.

Originally published at michaelsanford.com on August 8, 2013.

Top comments (0)