How to Set Memory and CPU Limits in WSL 2
Follow these steps :
1. Create or Edit the .wslconfig
File
- Create or update the file :
C:\Users\MyUsername\.wslconfig
- Add the following configuration :
[wsl2] memory=4GB # Set the maximum memory to 4 GB processors=2 # Limit the number of processors to 2 swap=1GB # Optional: Set the swap file size to 1 GB localhostForwarding=true # Optional: Enable localhost forwarding
2. Restart WSL
To apply the changes, restart WSL:
- Open PowerShell or Command Prompt.
- Run the following command to shut down WSL:
wsl --shutdown
- Start WSL again by launching your distribution (e.g., Ubuntu).
3. Verify the Changes
After restarting, verify the new settings:
- Check Memory: Run the following command in your WSL terminal:
free -h
This shows the total, used, and available memory. - Check CPU: Run the following command:
nproc
This displays the number of processors available to WSL.
Enable systemd and prevent any modification on the /etc/resolv.conf to prevent any internet problem access:
2 steps:
– Edit /etc/wsl.conf with:
[boot] systemd=true [network] generateResolvConf = false |
– hardcode the content of /etc/resolv.conf:
sudo rm /etc/resolv.conf
sudo bash -c 'echo "nameserver 1.1.1.1" > /etc/resolv.conf'
You can restart WSL now:
wsl --shutdown