How to Create SWAP File On CentOS Server
| |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
- 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.
- A CentOS Distro installed (I use CentOS 7)
- Putty and basic knowledge on how to use it.
- A computer or laptop to access your server
- 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
Next, create a swap file area using this command syntax:
mkswap /swapfile
pic:
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:
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:
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.
It should be:
/swapfile none swap defaults 0 0
and not,
/swapfile swap swap defaults 0 0
There is no directory named ‘swap’.
And, instead of ‘default’, you can use sw to ensure the swapfile is mounted safely on all Linux variants:
/swapfile none swap sw 0 0
Thanks for the tip Adam
Hi,
I have installed centos web panel on 16 GB RAMserver, but i am seeing everyday the RAM utilization getting crossed 12Gb,Can you tell me how we can stop unwanted RAM utilization and how can restrict users for utilization for more RAM.
Thanks