Now and then, heavily used systems may need to have their swap usage cycled (reset) to increase performance. There are many occasions where even though a system has enough RAM, there may still be a growing swap usage. The steps I outline here are safe to run on a production host to reduce swap usage and return swap contents to RAM.
Check current swap use:
[email protected]:~# free -m
total used free shared buff/cache available
Mem: 7800 4822 383 1 2594 2668
Swap: 4095 429 3666
[email protected]:~#
We can see here that about 430MB of swap is used even though there is plenty of RAM available. In this case, the system gets average consistent use and has been up for 206 days. We want to also see what the swappiness setting is currently set at and maybe reduce it:
[email protected]:~# cat /proc/sys/vm/swappiness
60
[email protected]:~#
[email protected]:~# sysctl vm.swappiness=20
vm.swappiness = 20
[email protected]:~# cat /proc/sys/vm/swappiness
20
[email protected]:~#
This new setting of 20 should help the system swap less often. We now want to force the system to move swap contents back to RAM where it belongs. To do that, we’ll turn swap off, and WAIT approx. 30 seconds, then turn swap back on:
[email protected]:~# swapoff -a
[email protected]:~# swapon -a
[email protected]:~# free -m
total used free shared buff/cache available
Mem: 7800 5295 143 2 2360 2194
Swap: 4095 0 4095
[email protected]:~#
We can now see that swap contents has been moved to RAM and that swap has reclaimed space. It should be easy to write a cron job to check swap usage and periodically do this when swap usage goes above an acceptable threshold.