Compacting a VirtualBox VM Centos disk

At work I used Centos 6.4 to convert a large Subversion repo to Git. This required a VM with a 100Gb disk, more than my old iMac could deal with, to the point where I could not update to newer OS version or even run iTunes to update apps.

[dchwalis@imac ~]$ df -h
Filesystem      Size   Used  Avail Capacity   iused   ifree %iused  Mounted on
/dev/disk0s2   931Gi  915Gi   16Gi    99% 239830061 4150681   98%   /

This article “How can I reduce the size of a VM on disk” started me off. Then I found https://forums.virtualbox.org/viewtopic.php?p=34636&sid=5bbe19387a6797d599beb35ec2e8b96c#p34636. Looks like since I used a large portion of the expandable virtual disk, there was data in it, and could not be reclaimed. I needed to zero out the now-deleted files and then pack the virtual disk image.

The tool to zero out the unused storage is zerofree and I needed to build that. Luckily my VM had all the dev tools installed, so it was a simple make. I grabbed the latest version, 1.0.3.

[dchwalis@centos ~]$ df -h
Filesystem            Size  Used Avail Use% Mounted on
/dev/mapper/vg_vmxxfscv62979-lv_home
                      242G   74G  156G  33% /home

First bust the system down to runlevel 1 to prevent other processes from keeping the disk busy.

sudo telinit 1

Now how to run a tool on a mount that was being used. This is why you should ALWAYS create new disks and mount them instead of expanding the system disk.

(Mount command line missing. It disappeared into runlevel 1)
Something like

# mkdir /fred
# mount -o remount,rw /dev/mapper/vg_vmxxfscv62979-lv_home /fred

I ran zerofree on the device. That took a long time and my iMac kept sleeping. Not good.

# /usr/bin/zerofree /dev/mapper/vg_vmxxfscv62979-lv_home

Then to have fsck run when the VM started up, I did per “Force fsck on reboot

# touch /forcefsck
# reboot

Then back to to have

[dchwalis@imac ~]$ VBoxManage modifyhd --compact centos-64-x64.vdi
0%...10%...

This step took a while.

[dchwalis@imac ~]$ df -h
Filesystem Size Used Avail Capacity iused ifree %iused Mounted on
/dev/disk0s2 931Gi 780Gi 151Gi 84% 204440272 39540470 84% /

So 16Gb free to 151Gb free. Looks like it worked. Lets start up the VM… Yay!

[1] http://askubuntu.com/questions/175739/how-do-i-remount-a-filesystem-as-read-write
[2] http://linux.die.net/man/8/mount
[3] http://ianozsvald.com/2012/07/26/using-zerofree-to-shrink-a-virtualbox-linux-image/
[4] http://frippery.org/uml/index.html
[5] “How can I reduce the size of a VM on disk”
[6] http://unix.stackexchange.com/questions/11100/how-to-make-ext4-filesystem-sparse

This entry was posted in Computers, howto and tagged , , , , , . Bookmark the permalink.

Leave a Reply