Recommended VPS Complete list of best VPS hosting providers.

How to Create SWAP File On CentOS Server

How To

This is a very basic guide: creating a Swap file on your CentOS server to act as a backup RAM space. Well, this task is optional but you better create one (if your VPS doesn’t come with Swap yet) to avoid OOM (Out of Memory) error. For your information -in case you didn’t know it yet- a Swap file can be described as a small amount of space created on a servers hard drive (or SSD) to simulate and act as backup RAM.

Using a HDD as RAM is probably not very good idea but it is a good practice especially in the event when your server is out of memory and you couldn’t effort to add more RAM immediately. In the ideal situation using SSD is really recommended.

Ingredients of this tutorial

  1. A server / VPS with enough RAM and HDD or SSD. In this article I use a 512MB cloud server from Atlantic.net. Do not have one? Read my list of recommended VPS providers as well as this list of 20 low end cloud server providers.
  2. A CentOS Distro installed (I use CentOS 7)
  3. Putty and basic knowledge on how to use it.
  4. A computer or laptop to access your server
  5. A cup of coffee or tea.

So here it is a simple tutorial you can follow. Let’s start with common rule of how large is a swap file should be created. The most common practice is to add half of your existing RAM up to 4GB. For example: if you have 1GB actual RAM allocated to your vps, then you can create about 512MB swap file.

The simple calculation is:

1024 block size x 512MB = 524288 block size. Now add that to the command:

dd if=/dev/zero of=/swapfile bs=1024 count=524288

it simply looks like this

2015-06-10_225908

Next, create a swap file area using this command syntax:

mkswap /swapfile

pic:

2015-06-10_225946

Define the owner of the newly created swap file and swap area then set correct permission on it:

chown root:root /swapfile
chmod 0600 /swapfile

Activate Swap you newly setup using this command:

swapon /swapfile

Finally, issue command below to verify that Swap has been setup and enabled:

swapon -s

screenshot:

2015-06-10_230104

The last thing to do is to configure Swap to run and enabled each time your server reboots. Use Nano editor (or vi) to adjust fstab setting:

nano /etc/fstab

then add following line at the very bottom (Thanks to Adam):

/swapfile none swap sw 0 0

which in my case it looks like this:

2015-06-10_230340

Save changes and exit the editor (in Nano it is Control+O then Control+X).

From here on, each time you check your RAM usage using free -m command, it should display your swap too.

2015-06-10_230242

3 Comments

Add a Comment

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

Get more stuff like this
in your inbox

Subscribe and get interesting stuff plus faster updates to your email.