Minimizing a linux virtual disk image with zerofree

How to make your linux drive image smaller with zerofree and virtualbox-manage

First you need to write zeroes on top of old unallocated data (the files you have deleted) on the virtual drive. This is done with zerofree.

zerofree will only overwrite unallocated data so the Virtualbox drive image file will not get any bigger than it already is.

Then we use vboxmanage to compact the virtual disk image.

Note that this will not work if you are using an encrypted hard disk. This is because the zeroes written by zerofree will be encrypted. In that case, the virtual disk image will grow to it's full size.

1. Install zerofree

First, install zerofree on your virtual machine:
sudo apt install zerofree

2. Log in to recovery mode


Log in to your machine in recovery mode.
At startup, press shift to see GRUB menu.
Select Advanced options and recovery mode for the newest kernel.
Then select Root from the menu.
Press enter when it asks you to "Press enter for maintenance".

3. Remount the drive as read-only


See which drive you have mounted to /
df

Note the device name (/dev/sda1 or such).

Now to remount / as read-only.
mount -o remount,ro /

But this command will probably fail due to running processes.
So first you have to stop these services using the mount point.

To see processes using it:
fuser -v -m / 2>&1 | grep F

Some processes might not show there.

For me I needed to run these commands:
systemctl stop systemd-journald.socket
systemctl stop systemd-journald.service
swapoff -a


Some valuable hints and discussion can be found on stackoverflow.


4. Run zerofree

Then run zerofree on the drive:
zerofree /dev/sda1

This process will take some time depending on how much stuff you have deleted on the drive.

After that, we can shut down the virtual machine.
shutdown 0 -h

5. On host computer, use VBoxManage tool to compact the .vdi disk image file

If you have VBoxManage in path, the command is something like this:
VBoxManage modifymedium disk "c:\Users\USERNAME\VirtualBox VMs\MACHINENAME\DISKNAME.vdi" --compact

Or you can use a full path to vboxmanage like this:
"c:\Program Files\Oracle\VirtualBox\VBoxManage.exe" modifymedium disk "c:\Users\USERNAME\VirtualBox VMs\MACHINENAME\DISKNAME.vdi" --compact

Comments

Popular posts from this blog

How to install and play Curse of Monkey Island on Android

How to fix the weird audio bug in Kingdom Come: Deliverance

How to fix the Anno 1404 out of memory error

Upgrading Ubuntu 10.04 to 11.10.

How to play Anno 1404 multiplayer in local area network