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.

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

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!