VirtualBox - Shrink VDI

Had I known that a product from Oracle would be so inefficient, I would probably have not used it (what tempted me to use the product was really the graphical user interface).

With that being said, these VDIs seem to grow incredibly large even though the data inside of it can be only 25% of what is reported on the host node. We need to try to shrink it so the host node keeps some space.

Two things must be done and most people who have posted about this aren't intelligent. They suggest that you unmounth the drive before zerofilling it - this is a terrible suggestion if you do this to an OS partition! So here's what you can do. Boot your VM up and then zerofill it (but alter this command to suit your needs). What I did was df -h and looked at how much remaining space was in the partition, I then subtracted 10G to ensure zerofill would not take up all the space.

dd if=/dev/zero of=zerofillfile bs=1G count=10

Change the above count=10 to whatever is the remaining size of the partition and make sure to run this on the correct partition. This will create a zerofillfile and it takes a while to do.

Once completed, delete this file and then shutdown the VM.

Next, go to your host machine that is running Oracle VirtualBox, then go to the directory that contains the VDI file and then run the following. Note, this can take hours (in my case since I had a 270GB vdi file). YOU MUST SHUTDOWN THE VM BEFORE DOING THIS! SO BASICALLY DOWNTIME (THIS IS WHY I HATE VIRTUALBOX)!

vboxmanage modifymedium --compact file.vdi

Replace the file.vdi above with the correct vdi file name.

Once this has completed, check to see if your VDI has shrinked and you can restart the VM.