Saturday, October 21, 2017

Compacting Hyper-V VHDX disk image with ext4 file system (Ubuntu)

Compacting Hyper-V VHDX disk image with ext4 file system (Ubuntu)


Go see Henry's blog post for more information about this, he's the expert not me. I mostly copied his stuff and modified it for my personal needs. I'm running Ubuntu 17 Server on a Windows 10.

This is a four part operation.

1. 

First clean and remove any unnecessary files in your guest OS. Don't forget to remove past installations:

sudo apt-get autoremove

Shut down the guest OS.

2. 

The second part is run in any Linux live CD. Google for "System Rescue CD" if you don't have one ready, I had Ubuntu Desktop ISO lying on my host drive, so I used that.

Start your guest machine again, but this time boot it from Live CD. Make your way to the terminal and type this:

sudo -i
apt-get install zerofree
vgchange -a y
zerofree -v /dev/sda1
ls -l /dev/mapper/
zerofree -v /dev/mapper/usvr1--vg-root
swapoff -av
lvm lvresize /dev/mapper/usvr1--vg-swap -L 1G
mkswap /dev/mapper/usvr1--vg-swap
swapon -va
sudo shutdown now

3.

The last part is done from PowerShell on the host machine. Start it as admin and do this: (of course with your path and file names)

cd "C:\Hyper-V\Ubuntu Server\Virtual Hard Disks"
Mount-VHD ".\Ubuntu Server.vhdx" -ReadOnly
Optimize-VHD -Path ".\Ubuntu Server.vhdx" -mode full
Dismount-VHD ".\Ubuntu Server.vhdx" 

4.

Enjoy.


P.S. For some reason, this hasn't quite worked for me, and only shaved a few gigabytes off of my vhdx file; even though that zip-ing the vhdx file reduces it down to 10%, indicating that it is (mostly) zeroed. Others have reported better results.