Skip to main content

Shrink your WSL2 virtual disk to reclaim disk space

· 2 min read
Stephan Hochdörfer
Head of IT Business Operations

Since migrating to my Windows 10 & WSL2 setup a few years ago, I regularly try to reclaim disk space from my WSL2 setup by following the steps outlined in Scott Hanselman's blog post. However, this time it did not work as expected.

When I realized my free disk space was less than 30 GB, I decided to clean up my WSL and Docker virtual disk to reclaim unused disk space. I was able to shrink the Docker virtual disk by about 30 GB by following the commands outlined in Scott's blog post:

cd C:\Users\YOURNAME\AppData\Local\Docker\wsl\data
optimize-vhd -Path .\ext4.vhdx -Mode full

When trying to shrink the virtual disk of my WSL2 Ubuntu setup, I could only free about 15 GB, which felt a bit disappointing to me. I deleted some more data in the WSL2 instance afterward and tried it again, but things did not improve. And it felt weird to have about 35 GB of data stored in WSL2, but the virtual disk image is 85 GB in size.

While doing some research, I came across this issue on GitHub. One commenter mentioned a Linux tool called fstrim. fstrim helps to discard unused blocks on a mounted filesystem. I gave it a try and ran sudo fstrim /. After that, I shut down WSL2 as usual with the wsl.exe --shutdown command and re-run optimize-vhd:

cd C:\Users\YOURNAME\AppData\Local\Packages\CanonicalGroupLimited.Ubuntu18.04onWindows_79rhkp1fndgsc\LocalState
optimize-vhd -Path .\ext4.vhdx -Mode full

The result looks a lot better. The virtual disk shrank from 85 GB to now 60 GB. So in total, including a few other cleanups, I have about 100 GB of free disk space. That's enough for now ;)

During my research, I came across a tool called wslcompact, which seems to do something similar. I will check it out next time I need to reclaim more disk space.

IMPORTANT: Before running the optimize-vhd and before running fstrim make sure to backup your WSL2 virtual disks. Just in case something does wrong. To backup the virtual disks, shut down Docker Desktop and stop your WSL2 instances first, then copy the virtual disks to your backup storage.