Swap is quite important on a small virtual machine but also on large servers. If you haven’t enabled Swap yet you should check the following guide here. This article should provide you some information about swap and how you can tweak swap on CentOS 7.
We’ll check if swap is enabled using swapon -s which should output something similar to this:
[root@web ~]# swapon -s
Filename Type Size Used Priority
/swap file 1048572 16 -1
This means we currently have a 1GB swap and we can confirm that it’s enabled by running free -m.
We’ll be touching two variables here: Swappiness and Cache Pressure.
Swappiness is a Linux kernel parameter that controls the relative weight given to swapping out runtime memory, as opposed to dropping pages from the system page cache. This parameter can be set to values from 0 to 100 inclusive. A low value instructs the kernel to avoid swapping, a higher value causes the kernel to try to use swap space as much as possible. The default value is 60 which works on most systems.
vm.swappiness = 0 – The kernel will swap only to avoid running out of memory
vm.swappiness = 60 – The default value
vm.swappiness = 100 – The kernel will swap aggressively, consuming a lot of the disk I/O
If we want a fast machine and we don’t want to hammer disk I/O we’ll need to lower this value. You can check the value for the current setting using cat:
[root@web ~]# cat /proc/sys/vm/swappiness
If we want to temporary change this value we can do it using a simple echo:
[root@web ~]# echo 10 > /proc/sys/vm/swappiness
or by using the sysctl tool:
[root@web ~]# sysctl vm.swappiness=10
This setting is not permanent unless we add it to /etc/sysctl.conf. If the value isn’t defined there you can simply add this line at the bottom of the file:
vm.swappiness = 10
After saving the file and exiting the editor the setting is permanent and it should be seen after reboot as well.
Another setting the can help your machine to perform better is vfs_cache_pressure. This setting controls the tendency of the kernel to reclaim the memory which is used for caching of directory and inode objects.
vfs_cache_pressure = 0 – The kernel will never reclaim dentries and inodes due to memory pressure and this can easily lead to out-of-memory situations
vfs_cache_pressure = 100 – The kernel will attempt to reclaim dentries and inodes at a “fair” rate
vfs_cache_pressure > 100 – The kernel will prefer to reclaim dentries and inodes which is not recommended and can have a bad impact on the machine’s perfromance
Default value on CentOS is 100 and it can be adjusted in the same way as vm.swappiness.
[root@web ~]# sysctl vm.vfs_cache_pressure=50
[root@web ~]# cat /proc/sys/vm/vfs_cache_pressure
You can also make it permanent by adding it to /etc/sysctl.conf.