Add Swap space on CentOS 7

Source: Internet
Author: User

Add Swap space on CentOS 7
Preface

How to make the server respond faster? How to avoid Memory insufficiency errors in applications? The simplest way is to increase the swap space. Swap is a reserved place on the storage disk. The operating system can store something that cannot be stored in the memory.

To some extent, this is equivalent to increasing the available memory of the server. Although swap reads and writes are slower than the memory, it is always worse than the memory, which is the safety net when the memory is insufficient.

If there is no swap, the server will terminate the application to release the memory once the memory is insufficient, and even crash. This will cause you to lose some data that has not been saved yet, or cause the server to become a machine. Some applications explicitly require the system to configure swap to ensure data access reliability.

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

Note: swap usually performs better on traditional mechanical hard disks. Using swap on SSD may cause problems, especially after hardware aging. Therefore, we do not recommend that you enable swap for DigitalOcean and other cloud host services that use SSD. This may even affect other users who share the host with your virtual machine.

For DigitalOcean users, the best way to improve performance is to update Droplet. Generally, the host performance after the upgrade will be improved, and it will not be affected by hardware problems.

Preparations

First, you need a CentOS 7 server that has been configuredsudoNon-root users (for the configuration process, refer to steps 1 to 4 in this tutorial ).

After you are ready, use this username to SSH to your CentOS server and install the swap file.

Check System Swap information

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

UseswaponCommand to check whether swap has been configured in the system. This is a common swap tool. Use-sTags can be used to list the usage of swap on the current storage device:

swapon -s

If no result is returned for this command, the system has not configured swap.

Alternatively, we can usefreeTool to view the overall memory usage of the system. Here we can see the Usage Status of the memory and swap (displayed in MB ):

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

We can see that the total swap space of our system is 0, that is, no swap is configured. This works with us inswapon.

Check available buckets

Generally, we create a separate partition as swap. However, due to hardware or software restrictions, the method of creating a partition cannot be implemented. In this case, you can create a swap file to implement the same function.

Check the available disk space before starting. Enter the following command:

df -hFilesystem      Size  Used Avail Use% Mounted on/dev/vda1        59G  1.5G   55G   3% /devtmpfs        2.0G     0  2.0G   0% /devtmpfs           2.0G     0  2.0G   0% /dev/shmtmpfs           2.0G  8.3M  2.0G   1% /runtmpfs           2.0G     0  2.0G   0% /sys/fs/cgroup

Here-hMark to telldhOutputs information in a user-friendly format, such as outputting space usage and free space 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 space in our storage partition, which is enough for us to operate. (I am a medium-scale new cloud host, and the situation for each person may be very different .)

What is the proper swap space? There are many options for this question, depending on your application needs and your personal preferences. Generally, doubling the memory capacity is a good starting point.

My system memory is 4 GB. If I set 8 GB swap to occupy too much space, I decided to set only 4 GB.

Create a Swap file

Next we will create a swap file on the file system. In the root directory (/).swapfileOf course, you can also select the file name you like. The space allocated by this file will be equal to the swap space we need.

The fastest creation method isfallocateCommand to create a file with a pre-allocated size. Run the following command to create a 4 GB file:

sudo fallocate -l 4G /swapfile

After you enter the password, the swap file is created immediately. We can uselsCommand to check the file size:

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

So far, our swap file has been created.

Enable Swap files

Now we have a swap file, but the system does not know whether to use this file as a swap. This requires us to inform the system to format the file as a swap and enable it.

First, we need to change the permissions of the swap file to ensure that only the root is readable. Otherwise, there will be a great security risk. UsechmodCommand to perform permission operations:

sudo chmod 600 /swapfile

In this way, only the root user can read and write the file. Usels -lhCommand to check:

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

Then, run the following command to notify the system to use the file for swap:

sudo mkswap /swapfileSetting up swapspace version 1, size = 4194300 KiBno label, UUID=b99230bb-21af-47bc-8c37-de41129c39bf

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

sudo swapon /swapfile

Run the following command to check whether the settings have taken effect:

swapon -sFilename                Type        Size    Used    Priority/swapfile               file        4194300 0     -1

We can see that the swap we just set is already in the returned results. ReusefreeConfirm with the tool:

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

So far, our swap has been set up and the operating system will use it as needed.

Make the Swap file take effect permanently

So far, we have enabled the swap file in the system. However, once the system is restarted, the server cannot automatically enable the file. To make the system automatically take effect after restart, we can modifyfstabFile (this is a table that manages file systems and partitions ).

UsesudoPermission to open the file for editing:

sudo nano /etc/fstab

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

/swapfile   swap    swap    sw  0   0

Save and exit. After the server is restarted, the file will be checked and swap is automatically enabled.

Modify Swap configurations (optional)

Several swap-related options may affect the system performance. In most cases, these options are optional. The specific modification depends on your application requirements and personal preferences.

Swappiness

swappinessThe parameter determines the system's frequency of switching data from memory to swap space. The value ranges from 0 to 100, representing the intensity of the system's data switching from memory to swap space.

The closer this value is to 0, the more inclined the system is to perform swap operations only when necessary. Because swap is much slower than memory, reducing the dependency on swap means higher system performance.

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

Run the following command to view the current value of swappiness:

cat /proc/sys/vm/swappiness30

CentOS 7 has 30 swappiness by default, which is moderate for most desktop systems and local servers. For VPS systems, a value close to 0 is more suitable.

UsesysctlCommand to modify swappiness. For example, set swappiness to 10:

sudo sysctl vm.swappiness=10vm.swappiness = 10

This modification will take effect until the next restart. If you want to permanently modify the value, you need to editsysctlConfiguration file:

sudo nano /etc/sysctl.conf

Paste the following content to the end of the file:

vm.swappiness = 10

After editing, save and exit. After that, the server sets swappiness to this value every time it restarts.

Cache Pressure)

Another configuration item that you can consider changing isvfs_cache_pressure. Frequent reading of such information consumes a lot of performance, so extending the cache storage time can improve the system performance.

PassprocFile System to view the current set value of cache pressure:

cat /proc/sys/vm/vfs_cache_pressure100

This value is relatively high, which means that the system can quickly remove inode information from the cache. A conservative value is 50.sysctlCommand:

sudo sysctl vm.vfs_cache_pressure=50vm.vfs_cache_pressure = 50

This command is only valid before restart. To make this setting permanently valid, edit it.sysctlConfiguration file:

sudo nano /etc/sysctl.conf

Add the following content at the end of the file:

vm.vfs_cache_pressure = 50

The server automatically sets the cache pressure to 50 after each restart.

Summary

So far, our system memory has gained some breathing space. With swap space, you can effectively avoid some common problems.

If you still encounter an out of memory error message, or your system cannot run the application you need, the best way is to optimize your application configuration or upgrade your server, but configuring swap space is also a flexible solution to save money.

This article is from DigitalOcean Community. How To Add Swap on CentOS 7 byJosh Barnett

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.