How to free up some Host Disk Space with Virtual Box

Here’s some hints on how to reduce the size of your virtualbox disk image (VDI) files, for linux guests (and host).

First, you’d of course shut down your virtual box guest and then make a backup copy of that vdi file just in case.

Next, boot into your guest and clean it up a bit:

apt-get update
apt-get -y upgrade
apt-get -y dist-upgrade
dpkg -l 'linux-*' | sed '/^ii/!d;/'"$(uname -r | sed "s/\(.*\)-\([^0-9]\+\)/\1/")"'/d;s/^[^ ]* [^ ]* \([^ ]*\).*/\1/;/[0-9]/!d' | xargs sudo apt-get -y purge
apt-get -y autoremove
apt-get -y install zerofree
apt-get clean

Then, reboot and drop into a safe mode. This should give you a root shell, and from there, point zerofree at the relevant partition (check with mount):

zerofree -v /dev/mapper/ubuntu-root

Once that’s done, shut down the virtual machine. On the host, go to the directory where your vdi file is and, if your vdi file is called bla.vdi, do the following:

VBoxManage modifyhd -compact bla.vdi

Once that’s finished, you should have reduced your vdi file quite significantly – I’ve just had one that went down from 40 GB to 14 GB.

Reboot your virtual machine, check that everything is working, and finally delete the backup vdi file.

BTW: If you use Mac OSX as guest, you can utilize the same VBoxManage modifyhd -compact command; before, instead of using zerofree, just use the disk utility to delete free space – and use the fast option, which writes zeros. This allowed me to bring down my Mac OSX image that I use to render videos from 90 GB to 9 GB.