Reduce WSL and Docker disks size

I really like WSL/WSL2 in Windows – it provides a lot of features with minimal performance impact (WSL2) and I can still use Windows app. In combination with Docker, it can handle a lot of things and it’s much better for me than for example MacOS. One problem I discovered last time is space consumed by WSL, and also Docker volumes. In both cases, Windows uses Virtual Hard Disk (VHD) format, vhdx files to store all data.

The problem is Windows can extend virtual disks on demand, without asking about that, but doesn’t reclaim free space if we make bigger changes inside WSL filesystem or Docker volumes. I had few IDE versions and different instances, each about 1,5 – 2 GB, and it consumed a lot of space. After deletion them from WSL filesystem, I didn’t get any real free space on my computer disk. We have to manually compact virtual hard disks to do that. How to do this? It’s quite simple. First, we have to enable Hyper-V if it’s not enabled. Just run terminal or PowerShell with admin privileges and execute this command:

Enable-WindowsOptionalFeature -Online -FeatureName Microsoft-Hyper-V -All

System restart may be required after that.

Second step is to compact disks. First, close Docker Desktop if it’s running and also shut down WSL by command:

wsl --shutdown

Right now we can compact disks, command is also very simple:

Optimize-VHD -Path "path_to_disk.vhdx" -Mode Full  

The question is, where can we find these disks?

You can find disks created by Docker in:

SYSTEM_DRIVE\Users\your_username\Local\Docker\wsl // and then directories inside

Second thing is related to your WSL distro – all should be in the same main directory, but with different subdirectory. I use Ubuntu, from Canonical and in that case, data is located on:

SYSTEM_DRIVE\Users\your_username\Local\Packages\CanonicalGroupLimited(...)\LocalState\ext4.vhdx

Of course you can use search or tools like Everything to locale any *.vhdx file easily.

After execute command, file should become smaller and you will have more free space.

Leave a Reply