Back Up Your WSL

While I work on Windows for my Office-related work, all of my coding is done on a WSL instance. Periodically, I export an image of each instance using the export feature.

Cleanup Disk Usage

The first step is to clean up disk usage. This will make the export take less time and will result in a smaller tar file. While you can us du, the ncdu utility adds some nice bells and whistles, namely the ability to drill down and find out what's using up the most space.

To install ncdu on Ubuntu, run:

sudo apt update
sudo apt install ncdu  

To install ncdu on Alpine, run:

su
apk update
apk add ncdu

When running ncdu, exclude the Windows file system root so that you scan only the data used by WSL:

ncdu --exclude /mnt

The usual suspects in terms of using up disk space are node_modules and compiled versions, plus cache files. You can safely remove these to keep your backup from being too large. You can also safely remove the .vscode-server folder (it will automatically reinstall next time you open code).

Export

Before backing up your WSL instances, it's best to shut them down. You can use the --terminate option of wsl to stop individual distributions, or the --shutdown to stop all distributions. Once you have stopped a distro, you can back it up by running:

wsl --export myDistro myDistro.tar

Then go get some coffee, because it'll take a few minutes, depending on how effective your disk cleanup was.