Skip to content

Instantly share code, notes, and snippets.

@JohnLBevan
Last active February 9, 2022 14:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JohnLBevan/4cffcdcc92de86d1525469a64c35f769 to your computer and use it in GitHub Desktop.
Save JohnLBevan/4cffcdcc92de86d1525469a64c35f769 to your computer and use it in GitHub Desktop.
Free up disk space caused by Docker files
# :: Prune dangling (untagged) images
docker image prune
# :: Stop Docker Desktop
Stop-Service 'com.docker.service'
# :: Stop the WSL service to ensure that doesn't lock the file
wsl --shutdown
# :: Note: If docker desktop is running you may get a warning at this point... I couldn't find a clean way to stop that via the command line
# :: Now reduce the disk size (pwsh cmdlet needs the hypver v features installed: https://superuser.com/questions/1307441/powershell-resize-vhd-is-not-recognized-as-the-name-of-a-cmdlet/1307442#1307442)
Optimize-VHD -Path (Join-Path -Path $env:LOCALAPPDATA -ChildPath 'Docker\wsl\data\ext4.vhdx') -Mode Full
# now you can right click docker desktop and hit restart docker if you want to use the services again.
# I've not restarted them via this script, as chances are you're not actively using docker if you're working on your disk space.
# Instead of just freeing up space, another option is to move the VHDX file elsewhere
# per https://github.com/docker/for-win/issues/7348
# documentation: https://docs.microsoft.com/en-us/windows/wsl/basic-commands#import-a-new-distribution
# get a list of all wsl distros
wsl -l -v
# Returns something like this:
# NAME STATE VERSION
# * Ubuntu Stopped 2
# Alpine Stopped 2
# docker-desktop Stopped 2
# docker-desktop-data Stopped 2
# stop the running wsl instance
wsl --shutdown
# export the image (the content of the vhdx) to a file by using an distro name from the list above (e.g. `docker-desktop-data`)
wsl --export docker-desktop-data X:\temp\docker-desktop-data-temp.tar
# remove the existing docker data (i.e. vhdx file)
wsl --unregister docker-desktop-data
# re-import that data specifying the new folder for the vhdx file and the tar file we used to temporarily store that data
wsl --import docker-desktop-data Y:\path\to\vhdx\parent\directory\ X:\temp\docker-desktop-data-temp.tar --version 2
# after this, the tar file can be deleted; as it was only required as a staging area for transitioning the data.
# repeat for any other distros to be moved.
# Another option could be to export them files to tar files as above, then compress them / store them on slower storage, then extract and reimport them to your faster drives when you need them
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment