Home > Virtualization > Shrink VirtualBox VDI files with TRIM

Shrink VirtualBox VDI files with TRIM

Historically I have always tried to keep virtual disks small by defragmenting, clearing unused space and compacting. It works, but it is tedious and takes time. Now there is a much better option, as VirtualBox has TRIM support!

Stop the image if it is running, then open the configuration file with a text editor. Locate the virtual disk and add discard and nonrotational:

<AttachedDevice discard="true" nonrotational="true" type="HardDisk" ... >

The nonrotational setting can be edited in the user interface (Solid-state drive), but my version of VirtualBox still doesn’t expose the discard option.

I’m often using Linux Mint as a guest. Start it and verify that TRIM is available for the disk:

sudo hdparm -I /dev/sda | grep TRIM

Provided that TRIM is in fact supported, add discard support to LVM if it is used. Edit /etc/lvm/lvm.conf and make sure that issue_discards is set:

devices {
    issue_discards = 1

Also edit /etc/fstab and add discard to the file systems, for example:

UUID=somevalue / ext4 discard,errors=remount-ro 0 1

Reboot and delete something big. You should see the vdi file shrink in real time. Is that cool or not? You can also discard unused data manually:

sudo fstrim /

With a file system that has been used for a while that can reduce the size of the vdi file a lot.

Categories: Virtualization
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: