Difference between revisions of "How To Configure SWAP on Centos 7"
(Created page with "==How To Configure SWAP on Centos 7== One of the easiest ways to make your server more responsive, and guard against out-of-memory errors in your application, is to add some...") |
(No difference)
|
Revision as of 19:10, 18 January 2015
Contents
How To Configure SWAP on Centos 7
One of the easiest ways to make your server more responsive, and guard against out-of-memory errors in your application, is to add some swap space. Swap is an area on a storage drive where the operating system can temporarily store data that it can no longer hold in memory.
This gives you the ability to increase the amount of information that your server can keep in its working memory, with some caveats. Reading from and writing to swap is slower than using memory, but it can provide a good safety net for when your server is low on memory.
Check if you already have SWAP setup
Before we begin, we should take a look at our server's storage to see if we already have some swap space available.
We can see if the system has any configured swap by using swapon, a general-purpose swap utility. With the -s flag, swapon will display a summary of swap usage and availability on our storage device:
swapon -s
If nothing is returned by the command, then the summary was empty and no swap file exists.
Create the SWAP File
Although there are many opinions about the appropriate size of a swap space, it really depends on your application requirements and your personal preferences. Generally, an amount equal to or double the amount of memory on your system is a good starting point.
Since my system has 4 gigabytes of memory, and doubling that would take a larger chunk from my storage space than I am willing to part with, I will create a swap space of 4 gigabytes to match my system's memory.
The fastest and easiest way to create a swap file is by using fallocate. This command creates a file of a preallocated size instantly. We can create a 4 gigabyte file by typing:
fallocate -l 4G /swapfile
Enable a Swap File
Make the SWAP file secure
This will restrict both read and write permissions to the root account only.
chmod 600 /swapfile && chown root. /swapfile
Configure the SWAP file to be used
Now that our swap file is more secure, we can tell our system to set up the swap space
mkswap /swapfile
Our swap file is now ready to be used as a swap space
swapon /swapfile
Now to verify that the everything was successful
swapon -s
Make the Swap File Permanent
Our swap file is enabled at the moment, but when we reboot, the server will not automatically enable the file for use. We can change that by modifying the fstab file, which is a table that manages filesystems and partitions.
echo "/swapfile swap swap sw 0 0" >> /etc/fstab
The server will check this file on each bootup, so the swap file will be ready for use from now on.