Reclaim disk space used by Docker Desktop (WSL2)
Table of contents
Problem
I was always out of disk space in my C drive, and even though I clear my stuff often, I notice that my space is never reclaimed, instead, it kept going down.
I used WizTree to view which file is taking up my disk space, and I noticed this
Notice that in %LOCALAPPDATA%\Docker\wsl\data
, there is a file ext4.vhdx
that is taking up 64.6gb
of space, around 14%
of my total disk space.
Docker Desktop for Windows uses WSL2 to manage all images and keep them in
ext4.vhdx
So to reclaim the space, I tried to delete the docker images via Docker Desktop
manually, but the space was not reclaimed even though I deleted most of the unused images.
Based on portainer
, I am currently only using 4.1gb
of space where before the clean-up, I am using around 20+gb
.
Solution - Optimize-VHD
Hyper-V has a command Optimize-VHD
that optimizes the allocation of space used by virtual hard disk files. In short, it helps to shrink the space used by Docker Desktop
.
To do so, exit Docker Desktop
, and shutdown WSL by running
wsl --shutdown
Give it a minute, and run wsl -l -v
and the distro should be in stopped
state.
wsl -l -v
NAME STATE VERSION
* Ubuntu Stopped 2
docker-desktop Stopped 2
docker-desktop-data Stopped 2
rancher-desktop Stopped 2
rancher-desktop-data Stopped 2
Navigate to the directory that stores ext4.vhdx
, and run the following command
optimize-vhd -Path .\ext4.vhdx -Mode full
Give it some time to complete, it took around 5 min for me.
Viola! It reclaims nearly 40gb
of disk space for me.
It's a chore to keep reclaiming manually, but I've learned that WSL has a new update recently where it comes with Sparse VHD
, a feature that automatically shrinks the WSL virtual hard disk (VHD) as you use it. If you are already using the latest version of WSL (currently in pre-release as of writing), then you can run the following command to enable it.
# wsl --manage <distro> --set-sparse <true/false>
wsl --manage Ubuntu --set-sparse true
References
Subscribe to my newsletter
Read articles from Joseph Gan directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Joseph Gan
Joseph Gan
Advocate for better developer's productivity and experience Documenting my learnings and sharing it