shrink VirtualBox disk image

For a recent hackathon at InMobi, I brought up a VirtualBox VM using vagrant. It had couple of java applications, nginx and ab hitting the nginx to generate traffic. I left the vm running even after the event and in a couple of day’s time I started getting disk space notifications on my laptop (host machine). The VM disk image (box-disk1.vmdk) file was around 17GB by that time. When I login to the vm and check disk space, it was only around 2.5GB. Obviously, something was wrong. Eventhough log rotation and cleanup was configured on the VM, space once used was not getting cleared on the disk image file even when the files inside the VM were deleted. Though I didn’t want the vm to be running, I didn’t want the vm disk image taking up this much space on my laptop as well.

Steps to Shrink the vmdk disk image

A lot of the posts on internet explains how to extend the image. What I wanted to do was to shrink or compact it without losing the data. As the disk image on host was showing much bigger size than the actual usage on VM, first step is to zero fill all the empty space on the vm. One way to do this is using zerofill command.

zerofill works on the file system and therefore requires the vm to be booted up using a different boot image. Once inside the vm, install zerofill package and run:

$ sudo zerofill /dev/sda1

Assuming /dev/sda1 is your vm root disk.

When you do not have a live image to boot up the vm, this is what you can do. Boot up the vm and inside that, run the following

# dd if=/dev/zero of=file; sync; rm -f file

This would essentially fill up the entire disk image with one file full of zeros and then remove the file.  Shutdown the vm and clone the disk image using VBoxManage command. It will skip all the zeros and what you get is a disk image with actual disk usage of the VM!

$ sudo VBoxManage clonehd box-disk1.vmdk box-disk2.vmdk

Most of the steps mentioned here are from this website. The only difference would be that you don’t really have to convert the vmdk to vdi format and back to achieve this.

As a final step, go to the VirtualBox settings for the VM and change the hard disk to point to the new file and you are good to go.

This entry was posted in linux, tech and tagged , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *