VirtualBox: Shrink dynamically extended image

VirtualBox Logo

A VirtualBox image needs to be shrinked again from time to time. Due to usage, updates, testing the size of the VDI files grows. The following post shows how to shrinken the VDI files again.

The instruction is based on a Linux guest system. For Windows based guests you will find more information at the end.

Cleaning a VirtualBox Disk Image (VDI)

Beside removing undeeded data from the disk the disk needs to be prepared before compacting it. Using zerofree the free diskspace will be filled with 0 which improves the compact afterwards.

sudo apt-get install zerofree

Once installed, the disk must not be writeable before zerofree can be started. For all disk or partitions which are not mounted to root ( / ). Easieast way is to unmount it. E.g. if /dev/sda2 is mounted to /home, the clean up can be started with

umount /dev/sda2
zerofree -v /dev/sda2

Cleaning a VirtualBox root disk

The root disk mounted at / cannot be unmounted this way. If possible it can be mounted read only using the following command:

mount -n -o remount,ro -t ext4 /dev/sda1 /

The above command asumes root installed on /dev/sda1 as ext4. You need to adjust this matching your VM.

On many systems this command will fail with

cannot unmount /dev/sda1 - device busy

As even stopping services often does not help, the easier way for Debian and Ubuntu based installations is to reboot the VM and select the recovery mode while booting. If the grub menu is not visible by default, you may have to press left shift key while powering the VM to make it visible. When prompted, enter the root password. Then stop some of the running services and remount the disk:

service rsyslog stop
service network-manager stop
killall dhclient
mount -n -o remount,ro -t ext4 /dev/sda1 /

If the command still fails, you can check which services are still running and may block the remount using the following command

fuser -v -m /

Once the remount command is executed sucessfully, execute zerofree

zerofree -v /dev/sda1

When all disks are prepared, shutdown the machine

shutdown -h now

Cleaning  a Windows disk

In case the guest is a Windows guest, you can download sdelete from Microsoft and install it. Open a command prompt and exeucte

sdelete -z c:/

Shutdown the Windows VM afterwards.

Shrink the disk image

Once the VM is stopped, open a command window in the folder where the VDI files are stored, and execute the following command:

VBoxManage modifyhd root.vdi compact
VBoxManage modifyhd home.vdi compact

The above command asumes the /dev/sda1 (root) is stored in root.vdi and /dev/sda2 (home) is stored in home.vdi. You need to adjust the above command to your VM.  The command works on both Linux and Windows hosts.