Shrink a dynamically-expanding guest VirtualBox image ¶
For Windows Guest
- defrag C: on guest O.S.
- run "sdelete.exe c -z" on guest O.S.
- run "VBoxManage modifyhd /path/to/thedisk.vdi --compact" on guest O.S.
P.S. download "sdelete" from sysinternals.
For Linux Guest
(1) Zero out the free space on VM
Install zerofree and restart:
sudo apt-get install zerofree sudo shutdown -r now
During reboot, press Left Shift Key, the select:
- recovery mode
- drop to root shell prompt
- run df to identify the biggest mount point; let's assume it's "/dev/sda1"
Stop background services:
service rsyslog stop service network-manager stop killall dhclient
Remount partition as readonly (zerofree needs this):
mount -n -o remount,ro -t ext4 /dev/sda1 /
Finally:
zerofree -v /dev/sda1 shutdown -h now
Alternative approach: fill HD with a single file, then remove it
dd if=/dev/zero of=file rm file
See: http://www.willdurness.com/post/101278039635/compacting-shrinking-a-virtualbox-image-when-using
(2) Detach virtual HD from VM and remove it from HDs listed in Virtual Media
From VirtualBox GUI, use VM settings / Storage first, then Virtual Media Manager
(3) Shrink the HD image
On host:
If image is in vmdk format, we need to convert it to a .vdi file first since VirtualBox’s utilities can’t compact vmdk format images.
VBoxManage clonehd Ubuntu.vmdk Ubuntu.vdi --format vdi VBoxManage modifyhd --compact Ubuntu.vdi VBoxManage clonehd Ubuntu.vdi Ubuntu.vmdk --format vmdk
(4) Finally reattach image to VM
From VirtualBox GUI, use VM settings / Storage again