Docker Desktop on WSL2 keeps everything in docker_data.vhdx, and that file only grows. docker system prune frees space inside it, but never gives it back to the Windows drive. Ours had reached 113 GB on a 500 GB partition that kept filling up. This is a follow-up to Docker Desktop WSL2 — VHDX grows by ~1.5GB after every update, no way to reclaim space (closed).
What actually shrinks the file, in this order:
- Prune dangling images and build cache unused for 7 days:
docker builder prune -f --filter until=168h. Never volumes. fstriminside Docker’s VM, so the freed blocks are marked empty. Without this, compaction “succeeds” and the file barely changes:
docker run --rm --privileged --pid=host alpine:3 nsenter -t 1 -m -- fstrim -v /var/lib/dockerdocker desktop stop, thenwsl --shutdown, and wait untilwsl -l --runningis empty and the vhdx can be opened exclusively (proves nothing still holds it).- diskpart:
select vdisk file="...\docker_data.vhdx",attach vdisk readonly,compact vdisk,detach vdisk. (Optimize-VHDneeds Hyper-V tools and failed for us with a permission error even as admin; diskpart works on Home too.) docker desktop start. Containers with a restart policy come back by themselves.
First real run: the vhdx went from 113 GB to 94 GB, and the drive from 20 GB free to 39 GB free. Docker was down for about 20 minutes, and all 38 containers came back.
I wrapped this in a PowerShell script with a Yes/No dialog, a -DryRun mode, a log file, and an always-detach finally. It never formats, resizes or deletes the vhdx. Script below.
Notes:
- Sparse VHD mode (
sparseVhd=true/--set-sparse) looked like the automatic answer, but there are reports of it not reclaiming or corrupting disks (microsoft/WSL#12103, #10703), so we avoided it. - Lowering Docker Desktop’s “Virtual disk limit” did not stop the file growing.
- On Docker 29.8.2,
docker builder prune --max-used-space 20gband--reserved-space 20gbboth reclaimed 0 B from a 30 GB build cache where every record was reclaimable.--filter until=168hdid remove old records. If anyone knows why the size caps do nothing here, I’d like to hear it. - Back up named volumes before compacting.
- Builds after pruning are slower, because the cache is smaller.
<#
Give Docker Desktop's free space back to the Windows drive.
Docker Desktop (WSL2 backend) keeps everything in docker_data.vhdx.
That file only grows: pruning frees space inside it, never on the drive. This script
does the full sequence that actually shrinks the file:
1. optional: run your own volume backup command (-BackupCommand)
2. prune: dangling images, build cache unused for 7 days (never volumes, never
tagged images, never containers)
3. fstrim inside Docker's VM, so the freed blocks are marked empty
(without this, compaction frees almost nothing)
4. stop Docker Desktop and WSL, check nothing still holds the file
5. diskpart: attach read-only, compact, detach
6. start Docker Desktop again; containers with a restart policy come back
Every step that changes something stops the run on failure, and the disk is
always detached at the end. It never formats, resizes or deletes the vhdx.
Run from an admin PowerShell:
powershell -ExecutionPolicy Bypass -File docker-disk-compact.ps1 -DryRun (checks only)
powershell -ExecutionPolicy Bypass -File docker-disk-compact.ps1
Set -Vhdx if you moved the disk image (Settings > Resources > Advanced).
#>
param(
[switch]$DryRun,
[switch]$SkipPrune,
[string]$Vhdx = (Join-Path $env:LOCALAPPDATA 'Docker\wsl\disk\docker_data.vhdx'),
[string]$BackupCommand = '', # your own volume backup, run first; empty = none
[string]$CacheAge = '168h'
)
# Not 'Stop': in PowerShell 5.1 a native command writing to stderr under
# 2>&1 would then abort the script mid-run. Each step checks its exit code.
$ErrorActionPreference = 'Continue'
Add-Type -AssemblyName System.Windows.Forms
$DesktopExe = 'C:\Program Files\Docker\Docker\Docker Desktop.exe'
$LogDir = Join-Path $env:LOCALAPPDATA 'docker-disk-compact'
New-Item -ItemType Directory -Force $LogDir | Out-Null
$Log = Join-Path $LogDir ("{0:yyyy-MM-dd_HHmm}.log" -f (Get-Date))
function Say($msg) {
$line = "{0:HH:mm:ss} {1}" -f (Get-Date), $msg
Write-Host $line
Add-Content -Path $Log -Value $line -Encoding utf8
}
function Box($text, $buttons = 'OK', $icon = 'Information') {
[System.Windows.Forms.MessageBox]::Show($text, 'Docker disk compact', $buttons, $icon)
}
function Fail($msg) {
Say "STOPPED: $msg"
Box "Stopped: $msg`n`nLog: $Log" 'OK' 'Error' | Out-Null
exit 1
}
function SizeGB($path) { [math]::Round((Get-Item $path).Length / 1GB, 1) }
function FreeGB($letter) { [math]::Round((Get-PSDrive $letter).Free / 1GB, 1) }
function DockerUp { docker info *> $null; return ($LASTEXITCODE -eq 0) }
function WslRunning {
# wsl.exe prints UTF-16; read it as such or the names come out garbled.
$old = [Console]::OutputEncoding
[Console]::OutputEncoding = [Text.Encoding]::Unicode
try { $out = (wsl.exe --list --running --quiet 2>$null) -join '' } finally { [Console]::OutputEncoding = $old }
return -not [string]::IsNullOrWhiteSpace($out)
}
function FileFree($path) {
# Opening with no sharing fails if Docker, WSL or anything else holds it.
try { $f = [IO.File]::Open($path, 'Open', 'Read', 'None'); $f.Close(); return $true } catch { return $false }
}
function RunDiskpart($lines) {
$script = Join-Path $LogDir 'diskpart.txt'
Set-Content -Path $script -Value $lines -Encoding ascii
$out = diskpart /s $script 2>&1 | Out-String
Add-Content -Path $Log -Value $out -Encoding utf8
return @{ Code = $LASTEXITCODE; Out = $out }
}
# ---------- checks (no changes) ----------
$isAdmin = ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()
).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
if (-not $DryRun -and -not $isAdmin) { Fail 'needs administrator rights (run from an admin PowerShell)' }
if (-not (Test-Path $Vhdx)) { Fail "no Docker disk at $Vhdx" }
if (-not (DockerUp)) { Fail 'Docker is not running. Start Docker Desktop first, so the cleanup inside it can run.' }
# A power cut during compaction is the one way to damage the disk file.
$onBattery = @(Get-CimInstance Win32_Battery -ErrorAction SilentlyContinue | Where-Object { $_.BatteryStatus -ne 2 }).Count -gt 0
if ($onBattery -and -not $DryRun) { Fail 'the laptop is on battery. Plug it in first.' }
$before = SizeGB $Vhdx
$drive = (Split-Path -Qualifier $Vhdx).TrimEnd(':')
$freeBefore = FreeGB $drive
$running = @(docker ps --format '{{.Names}}')
$needBackup = [bool]$BackupCommand
Say "Docker disk: $before GB. ${drive}: free: $freeBefore GB. Running containers: $($running.Count)."
docker system df | Out-String | ForEach-Object { Say $_ }
if ($DryRun) {
Say "DRY RUN: would back up volumes: $needBackup; prune: $(-not $SkipPrune); then trim, stop Docker+WSL, compact, restart."
Say "Admin rights now: $isAdmin. diskpart present: $([bool](Get-Command diskpart -ErrorAction SilentlyContinue))."
exit 0
}
$list = ($running | Select-Object -First 25) -join "`n"
if ($running.Count -gt 25) { $list += "`n... and $($running.Count - 25) more" }
$answer = Box ("This stops Docker Desktop and all of WSL for about 15-40 minutes.`n" +
"Docker disk now: $before GB. ${drive}: free: $freeBefore GB.`n`n" +
"These $($running.Count) containers will stop and restart afterwards " +
"(scrapers resume from where they were):`n$list`n`n" +
"Back up volumes first: $needBackup`n`nGo ahead?") 'YesNo' 'Warning'
if ($answer -ne 'Yes') { Say 'Cancelled.'; exit 0 }
# ---------- 1. backup ----------
if ($needBackup) {
Say "Running backup: $BackupCommand"
Invoke-Expression $BackupCommand 2>&1 | ForEach-Object { Say " $_" }
if ($LASTEXITCODE -ne 0) { Fail 'volume backup failed, nothing was stopped or compacted' }
}
# ---------- 2. prune ----------
if (-not $SkipPrune) {
Say 'Pruning dangling images and build cache ...'
docker image prune -f 2>&1 | Select-Object -Last 1 | ForEach-Object { Say " $_" }
# Prune by age, not size. On Docker 29.8.2 both size caps,
# --reserved-space and --max-used-space, freed 0 B from a 30 GB cache
# (2026-10-24); --filter until=168h freed 1.8 GB.
docker builder prune -f --filter "until=$CacheAge" 2>&1 | Select-Object -Last 1 | ForEach-Object { Say " $_" }
}
# ---------- 3. trim ----------
Say 'Trimming free blocks inside the Docker VM ...'
$env:MSYS_NO_PATHCONV = '1'
$trim = docker run --rm --privileged --pid=host alpine:3 nsenter -t 1 -m -- fstrim -v /var/lib/docker 2>&1 | Out-String
Say " $($trim.Trim())"
if ($LASTEXITCODE -ne 0) {
$go = Box "The trim step failed:`n$trim`nCompaction is still safe but will free much less. Continue?" 'YesNo' 'Warning'
if ($go -ne 'Yes') { Fail 'trim failed; nothing was stopped' }
}
# ---------- 4. stop Docker and WSL ----------
# Containers get a clean stop (databases flush) before WSL goes down. If Docker
# will not stop cleanly, give up rather than pull the VM out from under them.
Say 'Stopping containers cleanly ...'
docker stop -t 120 $running 2>&1 | Out-Null
$still = @(docker ps --format '{{.Names}}')
if ($still.Count) { Fail ("these containers did not stop, so nothing was compacted: " + ($still -join ', ') + ". Docker is still running.") }
Say 'Stopping Docker Desktop ...'
docker desktop stop --timeout 300 2>&1 | ForEach-Object { Say " $_" }
if ($LASTEXITCODE -ne 0 -or (DockerUp)) {
Fail 'Docker Desktop did not stop cleanly, so nothing was compacted. Start it again from the Start menu; containers were stopped and need `docker start`.'
}
wsl.exe --shutdown
$deadline = (Get-Date).AddMinutes(3)
while ((WslRunning) -or -not (FileFree $Vhdx)) {
if ((Get-Date) -gt $deadline) { Fail 'WSL or another program still holds the Docker disk after 3 minutes. Docker is stopped; start it again from the Start menu.' }
Start-Sleep -Seconds 5
wsl.exe --shutdown
}
Say 'Docker and WSL are stopped and the disk file is free.'
# ---------- 5. compact ----------
$attached = $false
try {
Say 'Compacting with diskpart (10-30 min) ...'
$r = RunDiskpart @("select vdisk file=`"$Vhdx`"", 'attach vdisk readonly')
if ($r.Code -ne 0) { throw "attach failed: $($r.Out)" }
$attached = $true
$r = RunDiskpart @("select vdisk file=`"$Vhdx`"", 'compact vdisk')
if ($r.Code -ne 0) { throw "compact failed: $($r.Out)" }
} catch {
Say " $_"
$compactError = "$_"
} finally {
if ($attached) {
$r = RunDiskpart @("select vdisk file=`"$Vhdx`"", 'detach vdisk')
Say (" detach exit {0}" -f $r.Code)
}
}
# ---------- 6. start Docker ----------
Say 'Starting Docker Desktop ...'
docker desktop start --timeout 600 2>&1 | ForEach-Object { Say " $_" }
if (-not (DockerUp)) { Start-Process $DesktopExe }
$deadline = (Get-Date).AddMinutes(10)
while (-not (DockerUp)) {
if ((Get-Date) -gt $deadline) { break }
Start-Sleep -Seconds 10
}
# `docker stop` above counts as a manual stop, so restart policies such as
# unless-stopped would leave them down. Start exactly the ones that were running.
if (DockerUp) {
Say 'Starting the containers that were running before ...'
docker start $running 2>&1 | Out-Null
Start-Sleep -Seconds 20
}
$after = SizeGB $Vhdx
$freeAfter = FreeGB $drive
$back = @(docker ps --format '{{.Names}}')
$missing = @($running | Where-Object { $back -notcontains $_ })
$msg = "Docker disk: $before GB -> $after GB. ${drive}: free: $freeBefore GB -> $freeAfter GB.`n" +
"Containers running again: $($back.Count) of $($running.Count)."
if ($missing.Count) { $msg += "`nNot back yet (no restart policy, or still starting):`n" + ($missing -join "`n") }
if (-not (DockerUp)) { $msg += "`n`nDocker did not come back within 10 minutes. Start Docker Desktop from the Start menu." }
if ($compactError) { $msg = "Compaction failed: $compactError`nThe disk was detached and Docker restarted.`n`n" + $msg }
Say $msg
Box "$msg`n`nLog: $Log" 'OK' $(if ($compactError) { 'Error' } else { 'Information' }) | Out-Null
Happy to hear if there is a cleaner way that does not need stopping Docker.