Swappiness on WSL2 gets reset to 60
/etc/sysctl.conf
is usually parsed by Systemd in Ubuntu on startup (I believe via systemd-sysctl.service
). Since WSL doesn't use Systemd, it doesn't get "handled" when you shut down and restart the WSL subsystem. This is similar to what I describe in my answer to this Stack Overflow question (no need to read it now, but it has more detail if you need it).
The solution (also as I describe in that particular answer) is to use the kernelCommandLine
setting for WSL2's kernel:
-
In your Windows
%userprofile%
directory (typicallyC:\Users\<username>
) create or edit the file.wslconfig
with the following:[wsl2] kernelCommandLine = "sysctl.vm.swappiness=10"
-
Exit Ubuntu on WSL (and any other WSL instance)
-
Issue a
wsl --shutdown
from PowerShell, CMD, or the Start Menu -
Restart
You should find that vm.swappiness
is now persisted. Note that since all WSL2 sessions share the same kernel, this option will take effect globally. This is the case regardless of how you set the swappiness (or any kernel parameter).
Note also that this has been tested as far back as at least Windows 10 build 18363 by the OP of that Stack Overflow question.
Other alternatives
I believe the .wslconfig
option is probably best for this, but you could also:
- Use
/etc/wsl.conf
with the[boot]
section on Windows 11 to forcesysctl
to run on each startup. - Use your user profile to manually run it. If you go this route, use something like
wsl.exe -u root sysctl --system
to avoid having to type a password or configuresudoers
.