Shrink Docker WSL2 vhdx Disk Size
Can also be used to clean up files for regular WSL distributions
When running Docker Desktop with the WSL2 backend on Windows, due to the nature of dynamic VHD disks (docker_data.vhdx), the host machine’s disk space is not automatically released even if we delete a large number of useless images and containers in Docker. Often, the actual container usage is only around 20 GB, but the host’s .vhdx file can swell to 130 GB, or even fill up the C drive.
Core Solution: Directly Compress the VHDX
The most fundamental way to solve this problem is to shut down first, and then use Windows’ diskpart tool to manually compress the bloated virtual disk file. Simply running docker system prune is not enough; you must actually compress the VHD file back.
1. Clean Up Internal Docker Junk (Optional)
Before compressing the disk, it’s best to completely discard unnecessary images and zombie containers to free up space inside the container:
| |
2. Shut Down WSL
After cleaning up, exit Docker Desktop completely. To detach the WSL VHDX from its mounted state, run the following in an Administrator PowerShell:
| |
3. Compress the Disk
Continue by typing diskpart in the Administrator PowerShell to enter the interactive interface, then execute the following commands in order (replace with the actual path of your local .vhdx):
| |
After execution, you will find that the size of the .vhdx file has significantly decreased, close to the actual upper-layer read/write usage of your current Docker system. You can then reopen Docker Desktop and use it normally.
Appendix: One-Click Cleanup Script
Usage: .\Compact-Vhdx.ps1 C:\Users\mioyi\AppData\Local\Docker\wsl\disk\docker_data.vhdx
| |