How to Optimize Disk Space Usage of Docker in WSL2
If you're running Docker inside WSL2 (Windows Subsystem for Linux) and noticing that your disk space is quickly being consumed, this guide will walk you through the best ways to clean up space and reduce the size of your ext4.vhdx virtual disk.
✨ Step 1: Clean Docker Resources Inside WSL
Open your WSL2 terminal (e.g., Ubuntu) and run the following commands to remove unused Docker resources:
docker system prune -a --volumes
sudo apt-get autoremove -y
sudo apt-get clean
Then, zero out free space to help with disk compaction:
dd if=/dev/zero of=wipefile bs=1M status=progress; sync; /bin/rm wipefile
🔌 Step 2: Shut Down WSL
In PowerShell (as Administrator), shut down WSL completely:
wsl --shutdown
⚙️ Step 3: Compact the ext4.vhdx File Using diskpart
select vdisk file="D:\Docker\wsl\UbuntuWSL\ext4.vhdx"
attach vdisk readonly
compact vdisk
detach vdisk
exit
This will shrink the .vhdx file by removing unused zeroed space.
🔧 Step 4: Toggle Sparse Mode (Optional for Windows 11+)
wsl.exe --manage Ubuntu --set-sparse false
wsl.exe --manage Ubuntu --set-sparse true
🏁 Conclusion
Managing disk usage effectively within WSL2 is crucial for performance and long-term maintainability—especially when working with Docker. By following the cleaning and compaction steps, along with considering alternative storage paths, you ensure your development environment remains fast, clean, and efficient. Regular maintenance using these techniques will help you avoid bloated virtual disks and unexpected storage issues.