September 2023 update: A new pre-release of WSL (2.0.0) is reported to provide a new "sparse" mode for disk images which will automatically shrink the image when files are removed.
While I have not tested this personally yet, from the DevBlog announcement, you can convert an existing disk image to sparse with the following command from PowerShell:
wsl --manage <distro> --set-sparse true
You can also add the following to your .wslconfig
(located in your Windows profile directory, not inside WSL) to have any newly created distro image be sparse:
[experimental]
sparseVhd=true
Older answer
Still useful for "released" and earlier versions of WSL
Short answer:
diskpart
or the Optimize-VHD
commandlet can be used to shrink the virtual disk. Optimize-VHD
is typically preferred, but is only available under Windows Pro or higher. See below for details.
More Details:
For reference, there's an open Github issue on this topic.
WSL2 virtual disks are "dynamic" .vhdx
's, which means they:
- Are allocated to a maximum size
- Are initialized with just a few kilobytes of structural data
- Grow dynamically as data is added, up to their maximum allocated size
- And here's the kicker -- They do not automatically shrink when data is removed.
However, it's certainly possible to manually optimize them.
Step 0: For others that are reading this, follow the OP's lead by first cleaning up the Docker data using the normal Docker commands.
Next, in all cases:
- Stop Docker Desktop
wsl --shutdown
from PowerShell or CMD
Since you've already removed all data (containers, images, volumes), you could just remove the images entirely:
Uninstall Docker Desktop
From PowerShell:
wsl -l -v
# If they still exist, remove via ...
wsl --unregister docker-desktop
wsl --unregister docker-desktop-data
Important: Note that these are destructive operations, so make sure you really don't need any data from Docker Desktop.
Reinstall Docker Desktop
For those that have data that they need to retain, but still need to reclaim some space:
- Copy the
ext.vhdx
as a backup. Note that there have been reports of corruption when using either of the techniques below.
Then, as noted in the comments in that Github issue:
On Windows Pro, you can enable the Hyper-V feature and then run the Optimize-VHD
cmdlet in PowerShell per the original Github issue:
Optimize-VHD -Path .\ext4.vhdx -Mode full
If using Windows Home, you'll need to use use diskpart
per this comment.
Restart Docker Desktop and confirm that it is functional and that all expected data is intact before removing the backed-up ext4.vhdx
.