How to free up disk space from docker on Windows 10 with WSL 2 installed
Some of you may notice that Docker Desktop for windows is consuming your disk space every day and it’s getting bigger and bigger after loading large images and running containers. Most posts you can find about how to free up your disk space may suggest you to run the following Docker command:
docker system prune
This command deletes unused container, images and docker cache. However, you will get surprised that your disk space is not freed after running this command. This post shows you how to solve this issue.
Install Hyper-V module for Powershell
Before we start optimizing the size of this VHD file, we need to install Hyper-V module in order to enable a Powershell command called optimize-vhd.
Firstly, we need to make sure Hyper-V is enabled on Windows and Hyper-V management tool is installed. You can follow the Microsoft Hyper-V installation guide to enable it.
Secondly, we need to mount the Hyper-V module in Powershell. Here is the command.
Import-Module Hyper-V
NOTE: Please make sure you run Powershell as an administrator.
Locate the VHD file
By default, Docker storage file (ext.4.vhdx) is located in C:\Users\xxx\AppData\Local\Docker\wsl\data. However, Docker Desktop doesn’t really manage the VHD file. Intead, WSL does.
However, you can change the VHD location by reading the following post:
Since the whole docker storage is on this VHD, the next step is to shrink this VHD file.
Shrink the VHD file
Since we have installed Hyper-V module, run the following commands in Powershell
WSL — shutdown
cd C:\Users\xxx\AppData\Local\Docker\wsl\data
optimize-vhd -Path .\ext4.vhdx -Mode full
In a few minutes, you will see the free disk space increases.
Congratulations!
References
https://www.hanselman.com/blog/shrink-your-wsl2-virtual-disks-and-docker-images-and-reclaim-disk-space
https://www.altaro.com/hyper-v/install-hyper-v-powershell-module/