Useful Docker commands

Sort images by size

docker images --format "{{.ID}}\t{{.Size}}\t{{.Repository}}" | sort -k 2 -h

List dangling volumes

docker volume ls -f dangling=true --format '{{.Name}}'

Cleaning up Docker resources: https://www.digitalocean.com/community/tutorials/how-to-remove-docker-images-containers-and-volumes#a-docker-cheat-sheet

Where are the logs?

tail -f ~/Library/Containers/com.docker.docker/Data/log/vm/dockerd.log

Docker on Windows

On Windows all Docker data is stored in C:\Users\siddj\AppData\Local\Docker\wsl\disk\docker_data.vhdx

Also note that .vhdx files (Virtual Hard Disk v2 (VHDX) File Format) don’t reduce in size. Their size only increases. WSL data is also stored in a .vhdx file in windows

Correct — a .vhdx file does not automatically shrink in size even when data is deleted from the virtual disk inside the VM. Here’s why and how to fix it.


🧠 Why .vhdx Doesn’t Shrink Automatically

  • .vhdx is a virtual hard disk format used by Hyper-V.

  • When you delete files inside the guest OS, the space becomes available to the guest, but the host file (.vhdx) doesn’t shrink because:

    • The actual data blocks are still allocated on the host.
    • The guest OS just marks the blocks as “free,” but the .vhdx file still contains them.

✅ How to Shrink a .vhdx File

You need to perform two steps:

  1. Zero out the free space in the guest OS
  2. Compact the .vhdx on the host

🧹 Step 1: Zero Out Free Space (Inside the VM)

In Windows guest:

sdelete64 -z C:
  • Download sdelete from Sysinternals
  • The -z flag writes zeros to free space so Hyper-V can compact it

If you’re on Linux, use:

dd if=/dev/zero of=zero.fill bs=1M
sync
rm zero.fill

🔧 Step 2: Compact the VHDX (on the host)

Use PowerShell on the host:

Optimize-VHD -Path "C:\VMs\MyDisk.vhdx" -Mode Full

> Requires Hyper-V module. If you get an error, run as admin and ensure Hyper-V is installed.


📝 Notes

  • Fixed-size VHDX cannot be compacted — this only works for dynamically expanding disks
  • Back up before compacting in case of errors
  • Compacting may take time depending on disk size

Summary of Steps to clean space taken up by Docker Desktop on Windows

Inside WSL2:

docker system df
docker system prune -af --volumes
sudo apt-get clean
pip cache purge || true
npm cache clean --force || true
sudo fstrim -av

Example output of docker system prune -af –volumes: https://gist.github.com/siddhsql/dd39967fb8d033342f55115c642a8575

After this switch to Windows Command Prompt. Shut down WSL2:

wsl --shutdown   # and quit Docker Desktop if it's open

Then compact Docker VHDX by running:

wsl --manage docker-desktop-data --compact

If this does not work try from PowerShell:

Optimize-VHD -Path "${Env:LocalAppData}\Docker\wsl\data\ext4.vhdx" -Mode Full

or try this: https://stackoverflow.com/a/74870395/147530 replacing paths as necessary.

This entry was posted in Software. Bookmark the permalink.

Leave a comment