How To Add Swap on Linux







You have root privileges ( otherwise use the command sudo before every command listed below or use command su to gain root )
You want to create 4GB swap size


prompt> dd if=/dev/zero of=/swapspace bs=1M count=4000


prompt> fallocate -l 4000M /swapspace


prompt> dd if=/dev/zero of=/swapspace bs=1G count=4

last command may result in an error : dd: memory exhausted by input buffer of size 1073741824 bytes (1.0 GiB)

prompt> mkswap /swapspace
prompt> chmod 600 /swapspace
prompt> swapon /swapspace

if you get an error messages like:
swapon: /swapspace: swapon failed: Operation not permitted
then you have cheap vps, ask your provider to let you make swap files or move on

Make the Swap File Permanent

prompt> nano /etc/fstab


prompt> vi /etc/fstab

add the following line

/swapspace none swap defaults 0 0

Tweak your Swap Settings

prompt> nano /etc/sysctl.conf


prompt> vi /etc/sysctl.conf

add the following lines

vm.swappiness = 10
vm.vfs_cache_pressure = 50
prompt> sysctl -p

The swappiness parameter configures how often your system swaps data out of RAM to the swap space. This is a value between 0 and 100 that represents a percentage. see swappiness wiki
The vfs_cache_pressure parameter configures how much the system will choose to cache inode and entry information over other data. see kernel vm documentation

You can test values by issuing the following commands

prompt> sysctl vm.vfs_cache_pressure=20
prompt> sysctl vm.swappiness=100

You can check the current settings with the following commands

prompt> cat /proc/sys/vm/vfs_cache_pressure
prompt> cat /proc/sys/vm/swappiness

Leave a Reply

Your email address will not be published. Required fields are marked *