Reducing the size of your VirtualBox virtual disk file

When you've used a virtual machine for a while, adding/removing packages/files/etc your virtual disk may occupy a lot more space then is needed to hold the current contents. In order to reclaim that wasted space, you can shrink/compact your virtual disk so that it takes (a lot) less space on your host. The VirtualBox CLI interface has a command for that:

vboxmanage modifyhd <yourvirtualdiskfile>.vdi --compact

But in order to get some real results you need to prepare your guest first and in this blog I'll show you how.

Preparing a Linux guest

The preparation for a linux guest involves a number of steps which I'll outline below:

  1. Install the zerofree package. If you're on a Debian guest, you can do that with

    aptitude install zerofree

  2. Go into single user mode with

    init 1

  3. Remount all your partitions read only. For the partition containing your root (/) folder, this would be

    mount -no remount,ro /
    (optionally with -t ext2)

    1. The -n parameter is so that mount does not try to update "/etc/mtab" which might be on a readonly device
    2. The -t ext2 parameter can be used, since we don't need journaling for this operation ;-)
  4. Check that the filesystem doesn't contain any errors, by executing

    fsck.ext2 -f /dev/XXX
    Replace XXX with sda1 if that's the partition you want to check. If you didn't use the -t ext2 command, use the fsck command appropriate for your filesystem.

  5. Call zerofree on the partition with

    zerofree /dev/XXX
    Replace XXX with sda1 if that's the partition you want to "zerofree".

  6. Check that the filesystem (still) does not contain any errors, by executing

    fsck.ext2 -f /dev/XXX
    Replace XXX with sda1 if that's the partition you want to check. If you didn't use the -t ext2 command, use the fsck command appropriate for your filesystem.

  7. Repeat step 4-6 for every partition you want to prepare for shrinking/compacting.
  8. Remount all your partitions back to normal with

    mount -t ext4  -o remount,rw /dev/sda1 /
    for the partition containing your root (/) folder. Substitute ext4, sda1 and / with values appropriate for your partition(s) and mount points.

  9. Shutdown the virtual machine with

    shutdown -hP now

Your virtual disk file(s) are now ready to be compacted, so on your host execute the following command:

vboxmanage modifyhd <yourvirtualdiskfile>.vdi --compact

Preparing a Windows guest

To prepare a Windows guest, you need to execute the following steps:

  1. Download and install the sdelete program from http://technet.microsoft.com/en-us/sysinternals/bb897443
  2. Defragment your C:\ drive with the tool of your choice.
  3. Zero the free space of your C:\ drive with

    sdelete -c C:\

  4. Repeat step 2-3 for each partition on your windows guest

Your virtual disk file(s) are now ready to be compacted with the aforementioned command.