How to add swap partition on Centos 6 On KVM

Before we proceed to setup a swap file we need to check  if any swap files have been enabled by looking at the summary of swap usage.

swapon -s

If nothing returned that menas swap file is empty.

Now we have confirmed that we do not have any swap file enabled next we will check available disk space on server with df command

df

Filesystem     1K-blocks Used Available Use% Mounted on

/dev/vda1       20125372 813952 18289172   5% /

Create and Enable the Swap File

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

“of=/swapfile” designates the file’s name. In this case the name is swapfile.

Subsequently we are going to prepare the swap file by creating a linux swap area:

mkswap /swapfile

The results display:

Setting up swapspace version 1, size = 536866 kB

Finish up by activating the swap file:

swapon /swapfile

You will then be able to see the new swap file when you view the swap summary.

swapon -s
Filename Type Size Used Priority
/swapfile                               file 524280 0 -1

This file will last on the server until the machine reboots. You can ensure that the swap is permanent by adding it to the fstab file.

vi /etc/fstab

/swapfile          swap swap    defaults 0 0

To prevent the file from being world-readable, you should set up the correct permissions on the swap file:

chown root:root /swapfile
chmod 0600 /swapfile

How To Configure Swappiness

The operating system kernel can adjust how often it relies on swap through a configuration parameter known as swappiness.

To find the current swappiness settings, type:

cat /proc/sys/vm/swappiness

60

Swapiness can be a value from 0 to 100. Swappiness near 100 means that the operating system will swap often and usually, too soon. Although swap provides extra resources, RAM is much faster than swap space. Any time something is moved from RAM to swap, it slows down.

A swappiness value of 0 means that the operating will only rely on swap when it absolutely needs to. We can adjust the swappiness with the sysctl command:

sysctl vm.swappiness=10

vm.swappiness=10

If we check the system swappiness again, we can confirm that the setting was applied:

cat /proc/sys/vm/swappiness

10

To make your VPS automatically apply this setting every time it boots up, you can add the setting to the/etc/sysctl.conf file:

sudo nano /etc/sysctl.conf

# Search for the vm.swappiness setting.  Uncomment and change it as necessary.
   vm.swappiness=10

Leave a Reply

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