Add Swap Swap Space on CentOS 7

foreword

How to make the server respond faster? How can I avoid out of memory errors in my app? The easiest way is to increase the swap space. Swap is a reserved space on the storage disk, where the operating system can temporarily store some things that cannot fit in the memory.

This is somewhat equivalent to increasing the available memory of the server. Although reading and writing from swap is slower than memory, it is better than nothing, and it is a safety net when memory is insufficient.

If there is no swap, once the server runs out of memory, it will start killing applications to free memory, or even crash, which will cause you to lose some data that has not yet been saved, or cause a crash. Some applications explicitly require the system to configure swap to ensure reliable data access.

This article describes how to create and enable swap file on CentOS 7 server.

Note: Swap usually performs better on traditional HDDs, and using swap on SSDs can cause problems, especially as the hardware ages. Therefore, for DigitalOcean and other users of SSD-based cloud hosting services, we do not recommend enabling swap. This can even affect other users sharing the host with your virtual machine.

For DigitalOcean users, the best way to improve performance is to update your Droplets. Generally speaking, an upgraded console will perform better and be less susceptible to hardware issues.

Ready to work

First, you need a CentOS 7 server, configured with sudoa non-root user with privileges (for the configuration process, please refer to the first to fourth steps of this tutorial ).

When ready, SSH into your CentOS server with that username, ready to install the swap file.

Check the Swap information of the system

First we need to check the system's storage to see if swap has been configured. A system can set up multiple swap files or partitions, but generally one is enough.

Use the swaponcommand to check whether the system has been configured with swap, which is a general swap tool. Use -slabels to list swap usage on the current storage device:

swapon -s

If the command does not return a result, it means that the system has not been configured with swap.

Alternatively, we can also use freetools to view the overall memory usage of the system. Here we can see the usage status of memory and swap (displayed in MB):

free -m


             total       used       free     shared    buffers     cached
Mem:          3953        315       3637          8         11        107
-/+ buffers/cache:        196       3756
Swap:            0          0       4095

Here we can see that the total swap space of our system is 0, that is, no swap has been configured. This matches swaponthe results we saw there.

Check available storage space

Usually, we create a separate partition as swap. However, sometimes due to hardware or software limitations, the method of creating a new partition cannot be implemented. In this case, a swap file can be created to achieve the same function.

Before you start, check the free space on your disk. Enter the following command:

df -h


Filesystem      Size  Used Avail Use% Mounted on
/dev/vda1        59G  1.5G   55G   3% /
devtmpfs        2.0G     0  2.0G   0% /dev
tmpfs           2.0G     0  2.0G   0% /dev/shm
tmpfs           2.0G  8.3M  2.0G   1% /run
tmpfs           2.0G     0  2.0G   0% /sys/fs/cgroup

The -hflag here is to tell dhthe information to be output in a human-friendly format, such as outputting space usage and vacancy in MB or GB, rather than directly outputting the number of memory blocks.

From the first line, we can see that there is still 59GB of space left on our storage partition, which is enough for us to operate. (I'm a medium-sized new cloud host, everyone's situation may be very different.)

What is the appropriate swap space? There are many options for this, depending on your application needs and your personal preference. Generally, twice the amount of memory is a good starting point.

My system has 4GB of RAM, and 8GB of swap would take up too much space, so I decided to just set 4GB.

Create Swap file

Next we will create the swap file on the file system. /We are going to create a file named under the root directory ( ) swapfile, of course you can also choose a file name you like. The space allocated by this file will be equal to the swap space we need.

The quickest way to create it is fallocatewith the command, which creates a file that preallocates a specified size of space. Enter the following command to create a 4GB file:

sudo fallocate -l 4G /swapfile

After entering the password, the swap file will be created immediately. We can lscheck the file size with the command:

ls -lh /swapfile


-rw-r--r-- 1 root root 4.0G Oct 30 11:00 /swapfile

At this point, our swap file is created.

Enable Swap file

Now we have the swap file, but the system doesn't know that it should be used as swap, which requires us to tell the system to format the file as swap and enable it.

First of all, we need to change the permissions of the swap file to ensure that only root can read it, otherwise there will be great security risks. Use the chmodcommand for permission operation:

sudo chmod 600 /swapfile

In this way, only root can read and write the file. ls -lhCheck it out with the command:

ls -lh /swapfile


-rw------- 1 root root 4.0G Oct 30 11:00 /swapfile

Then, tell the system to use the file for swap using the following command:

sudo mkswap /swapfile


Setting up swapspace version 1, size = 4194300 KiB
no label, UUID=b99230bb-21af-47bc-8c37-de41129c39bf

Now, the swap file can be used as swap space. Enter the following command to start using the swap:

sudo swapon /swapfile

We can enter the following command to confirm whether the settings have taken effect:

swapon -s


Filename                Type        Size    Used    Priority
/swapfile               file        4194300 0     -1

You can see that the returned result already contains the swap we just set. Then use the freetool to confirm:

free -m


             total       used       free     shared    buffers     cached
Mem:          3953        315       3637          8         11        107
-/+ buffers/cache:        196       3756
Swap:         4095          0       4095

At this point, our swap is set up and the OS will use it when needed.

Make the Swap file permanent

So far, we have enabled the swap file in the system, but once the system restarts, the server cannot automatically enable the file. To make the swap automatically take effect after the system restarts, we can do it by modifying the fstabfile (this is a table that manages file systems and partitions).

Open the file for editing with sudopermissions:

sudo nano /etc/fstab

Add the following line to the end of the file to tell the operating system to automatically use the swap file you just created:

/swapfile   swap    swap    sw  0   0

After adding, save and exit. Every subsequent server restart will check this file and automatically enable swap.

Change the Swap configuration (optional)

There are several options involving swap that may affect system performance. In most cases these options are optional, and what to modify depends on your application needs and personal preference.

Swappiness

swappinessThe parameter determines the frequency at which the system exchanges data from memory to swap space. The value is set between 0 and 100, which represents the strength of the system to exchange data from memory to swap space.

The closer the value is to 0, the more inclined the system is not to perform swap, and only perform swap operations when necessary. Since swap is much slower than memory, less reliance on swap means higher system performance.

The closer the value is to 100, the more likely the system is to perform swaps. The memory usage habits of some applications are more suitable for this situation, which is also related to the purpose of the server.

Enter the following command to view the current swappiness value:

cat /proc/sys/vm/swappiness


30

CentOS 7 defaults to a swappiness of 30, which is a moderate value for most desktop systems and local servers. For VPS systems, a value closer to 0 may be more appropriate.

sysctlThe swappiness can be modified using the command. For example, set swappiness to 10:

sudo sysctl vm.swappiness=10


vm.swappiness = 10

This modification will remain in effect until the next reboot. If you wish to permanently modify this value, you will need to edit the sysctlconfiguration file:

sudo nano /etc/sysctl.conf

Paste the following at the end of the file:

vm.swappiness = 10

After editing, save and exit, and then the swappiness will be set to this value every time the server restarts.

Cache Pressure

Another configuration item to consider changing is vfs_cache_pressurethat this configuration item involves the storage of special filesystem metafile entries. Frequent reading of such information is very performance-intensive, so prolonging its storage time in the cache can improve system performance.

procView the current setting of cache pressure through the file system:

cat /proc/sys/vm/vfs_cache_pressure


100

This value is relatively high, which means that the system removes inode information from the cache faster. A conservative value is 50, sysctlset with the command:

sudo sysctl vm.vfs_cache_pressure=50


vm.vfs_cache_pressure = 50

This command is only valid until reboot. To make this setting permanent, the sysctlconfiguration file needs to be edited:

sudo nano /etc/sysctl.conf

Add the following at the end of the file:

vm.vfs_cache_pressure = 50

Save and exit, the server will automatically set the cache pressure to 50 after each restart.

Summarize

At this point, our system memory has gained some breathing room. Having swap space can effectively avoid some common problems.

If you still get out of memory (OOM, out of memory) error messages, or your system can't run the application you need, then the best way is to optimize your application configuration or upgrade your server, but configure swap Space is also a flexible saving option.

 

 

This article is sourced from the DigitalOcean Community . English original: How To Add Swap on CentOS 7  by  Josh Barnett

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324923460&siteId=291194637