Faster Trimming & Compacting of Hyper-V Ubuntu VMs

A while ago I described how to compact an Ubuntu VHDX running on Hyper-V using the sfill command. Running sfill, however, can take hours. Luckily, there is a much faster alternative.

ubuntu-vm-after-compacting

Ubuntu Trim and Hyper-V

Ubuntu running in a Hyper-V virtual machine has been supporting the trim command since version 14.04 (details). The OS issues trim commands when files are deleted to tell the disk that the blocks occupied by the files can be used elsewhere.

This mechanism originally developed for SSDs is useful for virtual hard disks, too. The host OS (the hypervisor) cannot know when blocks are ready to be reused unless the VM tells it. That is exactly what the trim command is for!

Trimming from Inside the Ubuntu VM with Fstrim

To tell the hypervisor which blocks can be reused issue the following command:

sudo fstrim -v /

This should not take too long.

Compacting the Ubuntu VM’s Virtual Hard Disk (VHDX)

To actually free the space you got back from the trim command above you need to shut down the Ubuntu VM. Then run the following PowerShell code on the Hyper-V machine hosting the Ubuntu VM:

gci -File -Filter *.vhd* -Path D:\VMs -Recurse | % {Mount-VHD $_.FullName -ReadOnly; Optimize-VHD $_.FullName -Mode full; Dismount-VHD $_.FullName}

This should not take too long, either. It recursively searches a base path (D:\VMs) and optimizes each VHD or VHDX file it finds. Adjust the base path as needed. That’s it - enjoy the freed disk space! In my case, the size of the VHDX was reduced from 103 to 31 GB. Not bad for a few minutes of work (and downtime).

Comments

Related Posts

Windows Server 2019 on Hetzner's EX62 & AX100 Dedicated Servers

Windows Server 2019 on Hetzner's EX62 & AX100 Dedicated Servers
This post is a follow-up to my 2016 article on how to install Windows Server on Hetzner’s EX51 hosted dedicated servers. Hetzner offers many types of dedicated servers at very attractive prices and - astonishingly - good support. This article lists some issues we encountered while installing Windows Server 2019 on the EX62 and AX100 servers and how we worked around them. Reading the earlier article is highly recommended.
Virtualization & Containers

Latest Posts

Scripted WordPress to Hugo Migration

Scripted WordPress to Hugo Migration
After having published in WordPress for almost 20 years, it was time for a change. This site is now rendered by Hugo, a static website generator built for Markdown content hosted in a Git repository. The migration from WordPress (HTML) to Hugo (Markdown) was far from trivial. Since I couldn’t find any tool for the job, I developed my own set of migration scripts that fully automate the migration process. You can find them on GitHub along with extensive documentation.
Website