WSL2
Set up Windows subsystem for Linux 2 (WSL2) for Linux development experience in Windows 10 and 11.
Instal WSL2¶
Open powershell with administrator privilege, run the following command in the host.
wsl --install
WSL2 post-install (optional) setup¶
Move the virtual disk¶
If you want to move the WSL virtual disk file to another disk (in this example, D:\
), run the following commands in Windows12:
Tip
The following example will move the current WSL virtual disk to D:\Ubuntu\ext4.vhdx
. You can change the distribution name (Ubuntu) and filesystem paths if necessary.
cd D:\
mkdir WSL
cd WSL
mkdir Ubuntu
wsl --export Ubuntu .\Ubuntu\ext4.tar
wsl --unregister Ubuntu
wsl --import Ubuntu .\Ubuntu\ .\Ubuntu\ext4.tar
Default login user¶
Edit /etc/wsl.conf
in the WSL. You may need to set the default user if you have moved the virtual disk file of the WSL distribution.
[user]
default=username
Host settings¶
Edit .wslconfig
3 in your Windows home directory (Enter %USERPROFILE%
in file explorer's location bar).
For example,
[wsl2]
memory=20GB # How much memory to assign to the WSL2 VM.
processors=4 # How many processors to assign to the WSL2 VM.
swap=8GB # How much swap space to add to the WSL2 VM. 0 for no swap file.
swapfile=C:\\temp\\wsl-swap.vhdx # Sets swap file path location, default is %USERPROFILE%\AppData\Local\Temp\swap.vhdx. Useful if your C drive has limited disk space.
Auto reclaim RAM and disk space¶
Edit .wslconfig
3 in your Windows home directory (Enter %USERPROFILE%
in file explorer's location bar). 4
[experimental]
autoMemoryReclaim=dropcache
sparseVhd-true
Maintenance¶
Update kernel¶
To (manually) update the WSL kernel, run the following commands with administrator privileges:
wsl --shutdown
wsl --update
Reclaim virtual disk space¶
To reclaim disk space from virtual hard disks (VHDs), run the following commands with administrator privileges 5:
wsl --shutdown
Optimize-VHD -Path %path-to.vhdx% -Mode Full
Alternatively, use diskpart
(if Optimize-VHD
is not found) 6
wsl --shutdown
diskpart
# open window Diskpart
select vdisk file="E:\ubuntu\ext4.vhdx"
attach vdisk readonly
compact vdisk
detach vdisk
exit
Alternatively, export the VHD as a tar file and reimport it again.
Caveats about WSL2¶
Poor filesystem performance across OSes¶
Cross-OS file access (e.g., accessing /mnt/c
in WSL) is at least one order of magnitude slower than accessing the native (/home/user/file
) files.7
-
https://learn.microsoft.com/zh-tw/windows/wsl/basic-commands#import-and-export-a-distribution ↩
-
https://devblogs.microsoft.com/commandline/windows-subsystem-for-linux-september-2023-update/ ↩
-
https://blog.miniasp.com/post/2023/05/14/Shrink-your-WSL2-Virtual-Disks-and-Docker-Images-and-Reclaim-Disk-Space ↩
-
https://answers.microsoft.com/en-us/windows/forum/all/optimize-vhd-not-found-in-windows-10-home/a727b760-0f82-4d0f-8480-d49eeaeb11a2 ↩