Optimizing WSL2 Docker Desktop v4.37.x VHDX File Size on Windows 10
By default, WSL2 VHDX files tend to grow beyond their utilized space, causing unnecessary consumption of disk space. However, by following a series of commands, you can solve this issue and optimize the VHDX file size.
Understanding the Issue
The WSL2 architecture relies on a virtual machine (VM) powered by Hyper-V to run its linux distributions. Each WSL2 distribution uses a VHDX file to store its file system. Over time, as you install more packages and utilities, the VHDX file grows in size, even if it is not being fully utilized.
Solving the Issue
To address the problem of growing VHDX files, follow these steps:
-
Open PowerShell as an administrator and run the following set of commands:
wsl --shutdown
wsl --managed docker-desktop-data
set-vhd -Path .\ext4.vhdx -Type Dynamic
Resize-VHD -Path .\ext4.vhdx -SizeBytes
optimize-vhd -Path .\ext4.vhdx -Mode Full
Replace
desired_size = 50 # In GB
size_in_bytes = desired_size * (1024 * 1024 * 1024)
print(size_in_bytes)
After running the commands, the VHDX file will be resized to your desired size and optimized, reducing disk usage.
Why Perform These Steps
By default, the WSL2 VHDX file is set to dynamic growth, meaning it grows as new data is added. However, it rarely shrinks and optimizes its size. This can lead to a significant waste of disk space.
Preventing Future Issues
While the above steps will help optimize your current WSL2 VHDX file, it's important to remember that the file could continue to grow beyond optimal size. Periodically monitor the disk usage in Windows and perform the above steps to ensure optimal VHDX file size.
-
Understand the issue of growing VHDX files in WSL2.
-
Learn the solution to optimize VHDX file size by following a series of commands in PowerShell.
-
Ensure that no packages or utilities are being actively installed or used during the optimization process.
-
Monitor disk usage periodically and perform the optimization steps as needed.