Reduce Size of Docker Data Volume in Docker Desktop for Windows

Submitted on Dec 30, 2021, 2:36 a.m.
docker-desktop.png

Here's a helper script that will allow you to reduce the size of the Docker Desktop for Windows virtual hard drive. Docker uses this volume to store docker images and other docker data.

If (!([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) {
# Substitute powershell PowerShell with pwsh for ps7
Start-Process pwsh -Verb RunAs "-NoProfile -ExecutionPolicy Bypass -Command `"cd '$pwd'; & '$PSCommandPath';`"";
exit;
}
$title = 'Docker Optimize-VHD'
$question = 'Docker and WSL will be shutdown, and the docker VHD optimized. Are you sure you want to proceed?'
$choices = '&Yes', '&No'
$decision = $Host.UI.PromptForChoice($title, $question, $choices, 1)
if ($decision -eq 0) {
if (Test-Path -Path $Env:LOCALAPPDATA\Docker\wsl\data\ext4.vhdx ) {
docker system prune
net stop com.docker.service
taskkill /IM "docker.exe" /F
taskkill /IM "Docker Desktop.exe" /F
wsl --shutdown
Optimize-VHD -Path $Env:LOCALAPPDATA\Docker\wsl\data\ext4.vhdx -Mode Full
Write-Host 'Optimization complete.'
Pause
} else {
Write-Host 'Warning: Docker VHD not found.'
Pause
}
} else {
Write-Host 'Operation canceled.'
}

The script will check for, and elevate privileges to Admin if required. It will stop both the Docker and WSL processes, and then run Optimize-VHD -Path $Env:LOCALAPPDATA\Docker\wsl\data\ext4.vhdx -Mode Full

You should almost certainly run docker system prune before running this script.

The script currently requires PowerShell v7 - which you can download here from the Installing PowerShell for Windows page.

Thanks to Marc Ziel with his post here for pointing me in the right direction.

Enjoy!