Reduce WSL2 disk size

WSL was good but it was not perfect for a linux dev running Windows 10. One reason was it was not fully compatible with linux. In the upcoming Windows 10 feature update, a new version of WSL is coming and it is called WSL2. It is optional and users can upgrade their exising WSL installations to WSL2.

Behind the scenes, WSL2 actually runs a lightweight VM. It boots up in seconds compared to what it would have taken for a normal VM to start.
Running graphical applications is also simple by using an XServer like MobaXTerm.

Due to it running inside a VM, the file access methods have changed, and the Distro installation/files is actually inside of a virtual hard drive and to access the full benefits and speeds of linux file systems, we need to copy our files inside the virtual hard drive.

Now, this might seem okay, but the problem is that the size of the virtual hard drive keeps on increasing automatically and if you delete a file from the linux file system, the space occupied by the VHD is still the same.

We need a way to manually free up this space from Windows 10.

Windows 10 Pro/Enterprise Method

if you have Pro or enterprise, you can do the following

  • Find the path of the VHD: To do this, enter the following in powershell
wsl --shutdown
Get-AppxPackage -Name "*Distro Name*" | Select PackageFamilyName

---
PackageFamilyName
-----------------
CanonicalGroupLimited.Ubuntu18.04onWindows_79rhkp1fndgsc

  • The VHD path would now be
%USERPROFILE%\AppData\Local\Packages\CanonicalGroupLimited.Ubuntu18.04onWindows_79rhkp1fndgsc\LocalState\ext4.vhdx
  • Now run the powershell command
optimize-vhd -Path <PATH-TO-VHDX> -Mode full

Windows 10 Home

Home version of windows 10 doesn't expose Hyper-V tooling kit. Therefore we need to use the old method of diskpart to reudce the size.

  • Find the .vhdx file path
  • Run diskpart from command line
  • Run the following commands
select vdisk file="<PATH-TO-VHDX>"
attach vdisk readonly
compact vdisk
detach vdisk

NOTE

  • You can run the command sudo fstrim / inside the linux distro before shutting it down to improve the saving
  • If reducing did not help you too much and you would like to move the data to a different drive, please refer the guide here

Thanks for reading

Subscribe to Blog

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe