Adding swap space

First switch to root and enter your password:

su

Then check that there is no swap space:

swapon -s

If nothing is returned, there is no swap space in the system.

Create the physical file for swap space:

dd if=/dev/zero of=/swapfile bs=1024 count=512k

This will create a 512MB file called “swapfile” in the root of your drive.

Next, we will create a swap area with this “swapfile”:

mkswap /swapfile

Now we will activate the swap area:

swapon /swapfile 

Check that the swap file is active:

swapon -s

These changes are not permanent, to make them last after a reboot:

nano /etc/fstab

Paste the following line:

/swapfile          swap            swap    defaults        0 0

Finally make sure that only root can read and write to this file:

chown root:root /swapfile
chmod 0600 /swapfile

Result:
SWAP

Setting the level of swappiness in the OS

By default the swappiness setting in CentOS is 60, this is rather high and this might mean that your VPS starts swapping when it doesn’t have to so we’ll change the setting.

First check the level of swappiness:

cat /proc/sys/vm/swappiness

Next, change the setting:

sysctl vm.swappiness=15

Check that the number has changed:

cat /proc/sys/vm/swappiness

To make it survive a reboot we need to add it to the following dile:

nano /etc/sysctl.conf

Search for the swapiness setting and change it or add the following:

vm.swappiness=15