Skip to content

WSL 2 should automatically release disk space back to the host OS #4699

Open

Description

@dsmaher

Is your feature request related to a problem? Please describe.
I occasionally have workloads that consume large amounts of disk space for temporary use in /tmp. For example, transcoding large video files or processing large datasets exported from a database. Since WSL2 stores its filesystem on a .vhdx, that file grows when the dataset is processed and never releases that space. Also, it doesn't appear to re-use released disk space in the .vhdx when files are deleted... it seems to prefer to grow the file rather than re-use existing empty space. (I haven't explicitly tested that theory, but my workload deletes temporary files as they are used and I never had enough of them existing simultaneously to reach 250GB, but the size of the .vhdx eventually expanded to that size.

When I'm done with that workload, I have to:

wsl --shutdown
optimize-vhd -Path .\ext4.vhdx -Mode full

This is annoying since it basically means that my system backups include a huge .vhdx file that is mostly empty. Also, until about 2 weeks ago, it was consuming the entire remainder of my system disk. I had only 50GB free, which was enough to handle the workload, but since it continued to grow even after files were removed, that didn't matter. (I figured it was time to upgrade the disk size anyway)

Describe the solution you'd like
Automatic compaction of the .vhdx, or a way to do so while WSL2 is still running so that I can schedule it for frequent cleanups.

Describe alternatives you've considered

  • Going back to WSL1 since it uses the host filesystem and is faster accessing that than WSL2. However, this alternative makes docker less useful. Docker on WSL2 is actually almost perfect; not so much on WSL1.
  • Exporting/Importing WSL 2 to move it to another disk. Not even sure if this is possible, but if it is,
    it would probably be fine for my desktop, but not really an option for my laptop. Not really worth the time either since that entire process would probably take about 30 minutes, but compacting is usually under 3.

Activity

  1. adrianciacob commented on Nov 27, 2019

    @adrianciacob

    +1 for being able to move the .vhdx to a different partition, either via config file or the "Move" feature in the Control Panel of Windows (currently getting a message that it's disabled)

  2. dvescovi1 commented on Dec 8, 2019

    @dvescovi1

    +1 here too

  3. wizhippo commented on Dec 11, 2019

    @wizhippo

    +1 also add the ability to specify the initial size limit.

  4. dvescovi1 commented on Dec 12, 2019

    @dvescovi1

    I also would like to see a setting for initial partition size limit. It looks like all distros are installed with a 250GB partition size. I see no (easy) way to extend this. My yocto builds require slightly more space than this and they have to be on an ext3/4 partition so I can not use the /mnt/c or other NTFS partitions.

  5. davidwin commented on Dec 14, 2019

    @davidwin

    In Home you don't even have the Optimize-VHD cmdlet, but thankfully (the slightly clumsier) diskpart command which can also be used to compact the .vhdx file. When I did this, it seemed like I first had to run sudo fstrim / in WSL to get a significant saving (14GB reclaimed with 8GB in use). A periodic background task that did this is really needed (and even better if it could be done online, of course).

    The default partition size should have some connection to the size of the Windows host partition. What is the use of a limit that exceeds that of the host (unless actual magic is involved)? Also, artificially limiting the maximum size to a fraction of that of the host seems a bit unnecessary.

    I think you really want an experience that is as close to that of WSL1 as possible, but with the incredible perf and compat gains, of course. That is, the WSL2 file system shouldn't feel like it was a static volume bound to a file on the host (although it is). Ideally, even the WSL partition/volume size should shrink and grow with available space on the host in a somewhat timely fashion. Now there is a stretch goal for you!

  6. taylankasap commented on Jan 15, 2020

    @taylankasap

    FWIW, since these commands looked benign I ran them to reclaim some disk space:

    wsl --shutdown
    optimize-vhd -Path .\ext4.vhdx -Mode full
    

    This broke my docker. I had to reset to factory defaults & reinstall docker and restart the pc a few times along the way to fix. All docker data is gone (doesn't matter in my case because it's just dev environment). YMMV.

    Microsoft Windows 19041.1 with WSL2
    Docker Desktop Edge 2.1.7.0 (41536) | Engine: 19.03.5

  7. StefanScherer commented on Jan 17, 2020

    @StefanScherer

    I've tried the commands as well. I could find an issue that docker engine (docker.sock) is not available after starting. But after restarting Docker Desktop and changing the settings / resources / wsl integration to off + apply, then to on again + apply did the trick. Looks like the sock

    I ran the test a second time, but now my whole Ubuntu 18.04 distro is broken, the terminal closes either immediately or after some seconds without any text in it.

  8. taylankasap commented on Jan 17, 2020

    @taylankasap

    Maybe disabling wsl integration first, then quitting docker and then using the optimize-vhd command can make it work. But I'm not going to take that risk now.

  9. StefanScherer commented on Jan 17, 2020

    @StefanScherer

    It's back alive, got the Ubuntu distro working again. Seem like I just have to wait a little bit. Terminal opens and I have the bash prompt. The WSL integration was disabled, after enabling again docker also works again in Ubuntu.

  10. MatyRi commented on Apr 25, 2020

    @MatyRi

    If you are looking for a way how to reclaim your disk space from Docker using WSL2, then there is a button for this if you are using Docker for Desktop (Edge 2.3.0.0). In the Dashboard / Troubleshoot - there is a Clean / Purge Data option which will let you select what do you want to remove. It safely shrank the Docker vhdx disk file to a few kilobytes. Just a warning that this obviously removes everything and not just unused space.

    image

    It does not solve the original issue but it's a quick way to a fresh start.

  11. merkuriy commented on May 12, 2020

    @merkuriy

    For Windows 10 Home (alternative Optimize-VHD cmdlet):

    wsl --shutdown
    diskpart
    # open window Diskpart
    select vdisk file="C:\WSL-Distros\…\ext4.vhdx"
    attach vdisk readonly
    compact vdisk
    detach vdisk
    exit

    Thanks to David Windehem (@davidwin) for the tip #4699 (comment).

  12. sorenwacker commented on May 14, 2020

    @sorenwacker

    I just got no disc space, I have not even installed much. I added a symbolic link that was no problem on my old system.

  13. nickjj commented on May 28, 2020

    @nickjj

    I'm on Windows 10 Pro build 2004 here (stable 2020 spring edition) and I just noticed I lost 60GB on my primary SSD from this because I started moving my source code into WSL 2's file system and forgot one of my podcast sites has a bunch of wave files in a private directory.

    When I run optimize-vhd -Path .\ext4.vhdx -Mode full as admin from PowerShell it throws an error with:

    optimize-vhd : '.\ext4.vhdx' is not an existing virtual hard disk file. 
    At line:1 char:1                                                                                                        
    + optimize-vhd -Path .\ext4.vhdx -Mode full
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [Optimize-VHD], VirtualizationException
    + FullyQualifiedErrorId : InvalidParameter,Microsoft.Vhd.PowerShell.Cmdlets.OptimizeVhd                                                                    
    

    How can I get around this error? This put my SSD at a dangerously low level of space and I'd rather not have to reinstall the entire WSL 2 instance from scratch and reconfigure Docker every time I accidentally copy an unused file into WSL 2's file system.

  14. 353 remaining items

  15. Guayamose commented on May 9, 2026

    @Guayamose
    Contributor

    I opened a more concrete proposal for this here: #40243.

    The proposal is focused specifically on optional VHDX compaction after WSL shutdown, rather than live compaction while WSL is still running.

    I also did some external validation outside the WSL repo using a disposable WSL2 Ubuntu distro and the native Windows Virtual Disk API:

    • OpenVirtualDisk with VIRTUAL_DISK_ACCESS_METAOPS | VIRTUAL_DISK_ACCESS_GET_INFO
    • CompactVirtualDisk with COMPACT_VIRTUAL_DISK_FLAG_NONE
    • no AttachVirtualDisk
    • no DetachVirtualDisk
    • WSL explicitly stopped before compaction

    In the test, I created a 4 GiB non-zero file inside WSL, deleted it, ran wsl --shutdown, and then compacted the offline ext4.vhdx.

    Result:

    Step VHDX size
    Before creating data 4,997,513,216 bytes
    After creating 4 GiB non-zero file 9,292,480,512 bytes
    After deleting the file 9,294,577,664 bytes
    After CompactVirtualDisk 4,997,513,216 bytes

    CompactVirtualDisk returned Win32 0 and recovered roughly 4 GiB.

    This does not solve all design questions, but it suggests that the shutdown/offline API path is technically viable and may be a practical implementation direction for this issue.

    I’m continuing the more focused technical discussion in #40243.

  16. Guayamose commented on May 9, 2026

    @Guayamose
    Contributor

    I posted more detailed validation results in #40243.

    Short version: I tested an external prototype using the native Windows Virtual Disk API against a disposable WSL2 Ubuntu distro.

    Findings:

    • offline OpenVirtualDisk + CompactVirtualDisk works after WSL is stopped
    • a 4 GiB non-zero file caused the VHDX to grow materially, and compaction recovered roughly 4 GiB after deletion
    • when the target distro is running, OpenVirtualDisk fails with ERROR_SHARING_VIOLATION
    • Docker Desktop WSL integration can restart/keep the target user distro running after wsl --shutdown

    So the implementation shape should probably not be “blindly compact immediately after shutdown”, but something closer to:

    • opt-in
    • shutdown-triggered
    • final target-distro/VHD in-use check
    • skip/defer/retry on sharing violation or if the target distro is running

    Continuing the focused technical discussion in #40243.

  17. Guayamose commented on May 10, 2026

    @Guayamose
    Contributor

    I opened an exploratory draft PR for a smaller manual-command-first step: #40481

    It adds wsl --manage <Distro> --compact for stopped WSL 2 distros only. No automatic compaction or shutdown hook yet.

    The idea is to validate the offline Virtual Disk API path before discussing any automatic shutdown-triggered policy.

  18. hyperphantasia commented on May 16, 2026

    @hyperphantasia

    +1
    Things are moving after all :)
    In the meanwhile I packed WSL-vhdx-Compact as a windows executable and also pushed the script to the PowerShell gallery.

  19. igortas commented on Jun 3, 2026

    @igortas

    Yesterday installed fresh Windows 11 25H2.... Restored my arch disto setup, everything I had, projects around 1gb, plus some tools installed with pacman..... Played around with playwright and docker configuring some images..... NOW THIS CRAP TAKES F************** 50GB!!!!!! IS THERE A PILOT IN THE AIRPLANE??????????????????????????????????????????

  20. craigforr commented on Jun 12, 2026

    @craigforr

    Yesterday installed fresh Windows 11 25H2.... Restored my arch disto setup, everything I had, projects around 1gb, plus some tools installed with pacman..... Played around with playwright and docker configuring some images..... NOW THIS CRAP TAKES F************** 50GB!!!!!! IS THERE A PILOT IN THE AIRPLANE??????????????????????????????????????????

    Image
  21. Rokurolize commented on Jul 2, 2026

    @Rokurolize

    After Optimize-VHD successfully ran, the vhdx file was marked as corrupted. When I searched for this thread and tried using the DMDE software, I was told I needed a paid license to restore subdirectories as well. This makes it completely unsuitable as an option.

    I can't help but think it would have been better if we had known in the past that vhdx corruption reports existed before executing this command.

  22. igortas commented on Sep 1, 2026

    @igortas

    This is working for me on WSL2 kernel 6.18.40.1-microsoft-standard-WSL2, Arch guest, Win11 Pro. Backup first, if u give a try!!!!

    Optimize-VHD -Mode Full compressing from 231 GB to around ~36 GB). But it only works if the guest has actually released the freed blocks first.

    1. One-time, admin PowerShell, then reboot:
      Enable-WindowsOptionalFeature -Online -FeatureName Microsoft-Hyper-V-Management-PowerShell -All
      (Requires Windows Pro/Enterprise. Home doesn't have the Hyper-V feature.)

    2. Trim inside the distro so the freed space is marked free at the vhdx level.
      sudo fstrim -v / sudo systemctl enable --now fstrim.timer
      $ findmnt -no OPTIONS rw,relatime,discard,errors=remount-ro,data=ordered

    3. Shut WSL down so the vhdx is detached:
      wsl --shutdown

    4. Compact (admin PowerShell):
      Optimize-VHD -Path "C:\Users\<you>\AppData\Local\wsl\{GUID}\ext4.vhdx" -Mode Full

    Find the path with:
    Get-ChildItem "$env:LOCALAPPDATA\wsl" -Recurse -Filter ext4.vhdx

    What did NOT reclaim anything for me (leaving this here since it's the usual advice in this thread):
    sparseVhd=true in .wslconfig,
    wsl --manage <distro> --set-sparse true --allow-unsafe
    diskpart -> compact vdisk.

  23. philippe-granet commented on Sep 1, 2026

    @philippe-granet

    workarounds suggested in this thread rely on the assumption that the user has local administrator privileges on Windows.

    In many corporate environments with strict security policies, developers simply do not have the authorization to run elevated/admin commands. Has anyone found a reliable solution or workaround for this issue that doesn't require admin rights?

  24. KnorpelSenf commented on Sep 1, 2026

    @KnorpelSenf

    I've tried that for a while with no solution in sight. I ended up getting admin access by the IT department.

    This is not to say that no workaround can exist, but I just wouldn't be too hopeful.

  25. onomatopellan commented on Sep 1, 2026

    @onomatopellan

    Reminder: The latest WSL 2.9.9 pre-release (install with wsl.exe --update --pre-release) already features the new compact capability for individual distros.

    wsl --manage <Distro> --compact

  26. Proman4713 commented on Sep 2, 2026

    @Proman4713

    For me, using diskpart to compact the VHDX has been reliable for me and I do it often.

    I've been following this thread for years, I believe...

  27. RandomDSdevel commented on Sep 2, 2026

    @RandomDSdevel

    Igor Tashevski (@igortas):

    1. Trim inside the distro so the freed space is marked free at the vhdx level.
      sudo fstrim -v / sudo systemctl enable --now fstrim.timer
      $ findmnt -no OPTIONS rw,relatime,discard,errors=remount-ro,data=ordered

    sudo fstrim -v

         This may have come up/been mentioned in this thread already, but, if you just do this and not any of the other in-distribution/-VM/-instance commands, you can combine this step with the next PowerShell invocations:

    wsl -d "$DISTRIBUTION" -u root fstrim -v && wsl --shutdown && Optimize-VHD -Path "$VHD_PATH" -Mode Full
    

    sudo systemctl enable --now fstrim.timer

         …Hmm, I wonder what the equivalent of this is for users on OpenRC instead of systemd. Looks it up… Ah, you'd just add '-a' to your 'fstrim' invocation. You can have a timed trigger for 'fstrim,' but it'll repeat; you have to add it as a periodic job using the system job scheduler, like the traditional 'cron.' 'fstrim' was just run, though, so that's kind of redundant.

  28. ChGen commented on Sep 17, 2026

    @ChGen

    Typically Windows OS and Linux distro does quick fsck check on boot drive to avoid corruption. WSL2 still skips fsck on boot, as I understand it. So, perfect sequence is: fsck + fstrim + vhdx compact.

  29. neversamiever-art commented on Oct 7, 2026

    @neversamiever-art

    Deleting files inside the distro does not shrink ext4.vhdx on Windows. wsl --manage <name> --set-sparse true also does not shrink a disk that is already large, and on some versions that switch is marked unsafe.

    This does shrink it:

    1. Inside the running distro: sudo fstrim -a
    2. In PowerShell: wsl --shutdown
    3. Compact the file while WSL and Docker are stopped.
      Windows Pro: Optimize-VHD -Path "C:\path\to\ext4.vhdx" -Mode Full
      Windows Home has no Optimize-VHD. In diskpart: select vdisk file="C:\path\to\ext4.vhdx", then attach vdisk readonly, compact vdisk, detach vdisk.

    Copy the vhdx somewhere else first.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    featurewsl2Issue/feature applies to WSL 2

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions