Shrink VirtualBox disk image

1 minute read

Nullify free space

In the Linux Guest system:

  • Log out from the gui
  • Open shell (e.g., Host Key + F2)
  • Nullify free space:
dd if=/dev/zero of=/var/tmp/bigemptyfile bs=4096k ; rm /var/tmp/bigemptyfile

Note that dd will use up all the free space


telinit 1
mount -o remount,ro /dev/sda1
zerofree -v /dev/sda1

If remount read-only fails

Edit fstab to have the mount point in question mounted read-only by default

vi /etc/fstab

Make the appropriate entry ‘ro’

/dev/sda1  /   ext4   ro    0    1

Reboot and run zerofree -v /dev/sda1 now

To “recover” the system:

  • Re-mount read-write: mount -o remount,rw /dev/sda1
  • Edit /etc/fstab again to restore the original content

Shutdown the Guest OS (Linux)

shutdown -h now

Compact VDI with VBoxManage on the host

C:\Program Files\Oracle\VirtualBox>VBoxManage.exe modifyhd --compact "c:\path\to\linux-disk-image.vdi"