Compacting a VMDK (Virtual Machine Disk Format image)

Compacting a VMDK file (.vmdk) is a good idea if you want to share or reuse it, such as with Vagrant. If you’ve tinkered with your VM a bit, deleting cached files isn’t enough. The space in the filesystem is marked as free, but isn’t erased. It still contains the data, so it doesn’t compress as well. Here, I’ll describe how to zero that free space and shrink that image.

How much it helps depends on your disk content, but for what it’s worth, my VMDK with an Ubuntu Maverick 64 install shrank from 2.0GB to 1.6GB, and gzipped they are now 679MB and 425MB, respectively. That’s a nice savings when you’re talking about shipping the image around between computers and using it as a Vagrant base box multiple times.

Zero Free Space

If you zero the free space, it can be efficiently compressed.

Note: If you can, defrag the volume. You can’t really defrag ext4 (you can, but it’s sketchy), so I’m not going into that.

You want to use the VirtualBox GUI to change the boot media for your VM to a lightweight live Linux like Finnix and boot from it.

Then install zerofree

sudo apt-get update && sudo apt-get install -y zerofree

Then zero the free space on your partition. Mine’s sda1, so it looks like

sudo zerofree -v /dev/sda1

Then shut down the VM

sudo poweroff

Clone the VMDK

VirtualBox only lets you compact VDIs, but if we clone a VMDK we get a compressed copy. So find your disk image

cd $VirtualBox_VMs_dir/$vm_dir

If you don’t have any snapshots, just

VBoxManage clonehd $disk_name.vmdk clone.vmdk

Otherwise, find the snapshot you want. I just want the newest one, so I

ls -lt Snapshots

And I get something like this at the top (newest file is on top):

-rw------- 1 force force 721092608 Jul 12 10:13 {11f18f3d-9a0b-4e98-b680-a108ac31a0aa}.vmdk

The 11f18f3d... is the UUID. So I want to use that to clone the disk.

VBoxManage clonehd 11f18f3d-9a0b-4e98-b680-a108ac31a0aa clone.vmdk

Attach the newly shrunk disk to the VM

Just use the VirtualBox GUI to edit the VM and attach your newly cloned disk instead of the original one. You’re done!

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

2 Responses to Compacting a VMDK (Virtual Machine Disk Format image)

  1. Ryan Finnie says:

    Thanks for the Finnix recommendation! FYI, the next version to be released (107) will include zerofree out of the box:

  2. Pingback: Unix:How can I zero files out inside a VMware image file so that their space can be reclaimed? – Unix Questions

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>