How To: Add swap to a KVM VPS or Dedicated Server CentOS 6

0
928

Swap is beneficial, because it allows inactive memory blocks to be written to disk, freeing up real memory for stuff like file system caching. Swap also (to some extent) protects you against short bursts of memory demand. Linux (by default) over commits real memory, relying on the fact that most applications ask for more than they need, but if they suddenly all need that memory swap can buffer you against applications crashing.

The first thing we need to do is check to see if any swap files have already been enabled. So login to shell as the root user and run:

swapon -s

If it comes back blank, then you do not have a swap file enabled and can proceed. But first, we want to check to see how much total space we have. In this example, we’re going to use 7% of the primary partition and create a swap file of 1024MB. So check your total HD:

df -h

Now, create the swap file using the dd command :
dd if=/dev/zero of=/swapfile bs=1024 count=1024k
“of=/swapfile” designates the file’s name. In this case the name is swapfile.

Now, prepare the swap file by creating a linux swap area:
mkswap /swapfile
The results display:
Setting up swapspace version 1, size = 536866 kB

Then finally, the last step would be to activate the swap file:
swapon /swapfile

Now when you check your memory, you will now see the swap memory available. You will also see the swap file when checking the summary:
swapon -s
and
free -m

To make sure these new settings stick after a machine reboot, we modify the fstab file.
Open up the file:
nano /etc/fstab

Paste in the following line:
/swapfile swap swap defaults 0 0

Save the file. And now, set up the correct permissions for the file

chown root:root /swapfile
chmod 0600 /swapfile

All done! Now your new swap file is ready.

Originally posted 2016-01-11 05:53:31.

LEAVE A REPLY

Please enter your comment!
Please enter your name here