How To Compact a VirtualBox VDI

I’ve been struggling with this issue for a while, and I’ve uncovered how to do it now.

Many times, I setup a VirtualBox virtual server and do a lot of copying.  So, this will grow the dynamic drive from 4-5 GB up to about 20 GB or more.

Once the copying is done and the files are deleted, I’d like to then reduce the size of the VDI file to get back the hard drive space.

That is what is nice about using dynamic-sized VDI files in VirtualBox – you can specify how large the virtual server can grow to, but it doesn’t use the space on the drive unless the virtual machine actually DOES use that space.

But, compacting a virtual machine in VirtualBox isn’t just a matter of doing a single command – as many believe it to be.  There is another step that you must do first.

The first step is to zero out the space that was previously being used in the virtual machine – that no longer is being used.

You will need to login to the virtual machine itself (in this case, these instructions are for Linux-based virtual machines).  This command will zero out all of the free space on the dynamic drive.  So if you have a dynamic drive of 120 GB, it will zero out all of this free space (even if never used).

cat /dev/zero > zero-file

Alright, that might take a few minutes.  Believe it or not, I was surprised that it didn’t take very long.  You’d think with making a single file that could be 115 GB or so, it would take a very long time to do.  That wasn’t the case.

Now that the entire free space of the drive has been zeroed out, you need to now delete the file:

rm zero-file

Now, it is time to actually compact the virtual machine in VirtualBox.  I ran the command below over and over again, but it never changed the space being used by the VDI file.  That was because the steps above was missed.  VirtualBox will only compact a VDI file IF the space that was previously used – is zeroed out.  That tells VirtualBox that it is indeed free space.

VBoxManage modifyhd “<VDI_FILE_HERE>” –compact

Now be a little patient.  This will take care of compacting your VirtualBox VDI file!  Mine went from 19 GB down to 3.6 GB after about 10 minutes of waiting.