How to add swap on CentOS 7

Introduction

One of the easiest ways to make the server respond faster and prevent out of memory errors in your application is to add some swap space. Swap is an area on the storage drive where the operating system can temporarily store data that can no longer be stored in the memory.

This allows you to increase the amount of information the server can keep in its working memory, but there are some caveats. For reading and writing, swap is slower than using memory, but it can provide a good safety net when your server is running low on memory.

Without Swap, a server with insufficient memory may start to scan and kill applications to free up memory, or even crash. This may cause you to lose unsaved data or experience downtime. To ensure reliable data access, certain applications require the Swap function.

In this tutorial, we will introduce how to create and enable Swap files on a CentOS 7 server.

Note Although swap is usually recommended for systems using traditional rotating hard drives, swap using SSDs may cause hardware problems over time. For this reason, we do not recommend enabling Swap on any other providers that use SSD storage. Doing so will affect the reliability of the underlying hardware.

Preparation

Before starting this tutorial, you need to complete a few steps.

After you have a non-root user, you can use it to SSH to the CentOS server and continue to install the swap file. Users without a server can purchase and use [Tencent Cloud Server] (https://cloud.tencent.com/product/cvm?from=10680) or directly experience it on [Tencent Cloud Lab CentOS Server] (https://cloud.tencent.com/developer/labs/gallery?tagId=13&from=10680).

Check system swap information

Before we start, we should check the server's storage to see if we already have some available swap space. Although we can have multiple Swap files or Swap partitions, it should usually be enough.

We can check whether the system has any swap configured by using the swapon universal swap utility. Using the -s flag, swapon will display a summary of swap usage and availability on our storage devices:

swapon -s

If the command returns nothing, the summary is empty and there is no swap file.

Another way to check the swap space is to use the free utility, which shows us the overall memory usage of the system. We can view the current memory and swap usage (in megabytes) by entering the following:

free -m
    total       used       free     shared    buffers     cached
Mem:39533153637811107-/+ buffers/cache:1963756
Swap:004095

As you can see, the total swap space in the system is 0. This matches the swapon we have seen.

Check available storage space

The typical way to allocate space for swap is to use a separate partition dedicated to the task. However, due to hardware or software limitations, it is not always possible to change the partition scheme. Fortunately, we can easily create swap files that reside on existing partitions.

Before we do this, we should understand the current drive usage. We can enter the following information to obtain this information

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

**Note: The **-h flag just tells you dh to output drive information in a humanized reading format. For example, instead of outputting the number of raw memory blocks in the partition, df-h tells us the space usage and availability of M (megabytes) or G (gigabytes).

As you can see on the first line, our storage partition has 59 gigabytes, so we have quite a lot of space to use, and your actual usage may be very different.

Although there are many opinions on the appropriate size of the swap space, it really depends on your application requirements and your personal preferences. Generally, equal to or twice the amount of system memory is better.

Since my system has 4 gigabytes of memory, and the number of chunks from my storage space is more than I am willing to participate in, I will create a 4 gigabyte swap space to match my system RAM.

Create swap file

Now that we know the available storage space, we can create a swap file in the file system. We will create a file named swapfile in the root (/) directory, but you can name the file other files if you want. The file must allocate the amount of space we want for our swap file.

The fastest and easiest way to create a swap file is to use fallocate. This command immediately creates a file of pre-allocated size. We can enter the following to create a 4 gigabyte file:

sudo fallocate -l 4G /swapfile

After entering the password to authorize the sudo permissions, the swap file will be created immediately and a prompt will be returned to you. We can verify whether the correct amount of space ls is reserved for swap using the following method:

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

As you can see, our swap file was created with the correct amount of space.

Enable swap file

Now, our file has been created, but our system does not know that this should be used for swap. We need to tell our system to format this file as swap and then enable it.

Before we do this, we should adjust the permissions of our swap file so that no one but the root account can read it. Allowing other users to read or write to this file would be a huge security risk. We can lock the permission chmod with the following command:

sudo chmod 600/swapfile

This will only restrict the read and write permissions of the root account. We can use ls again

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

Since our swap file is more secure, we can tell our system to set up the swap space for use by typing the following:

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

Our swap file can now be used as a swap space. We can start using it by typing:

sudo swapon /swapfile

To verify the success of the program, we can check whether our system now reports swap space:

swapon -s
Filename                Type        Size    Used    Priority
/swapfile               file        41943000-1

This output confirms that we have a new swap file. We can use the free utility again to confirm our findings:

free -m
    total       used       free     shared    buffers     cached
Mem:39533153637811107-/+ buffers/cache:1963756
Swap:409504095

Our swap has been successfully set up, and our operating system will start using it as needed.

Make the swap file permanent

Our swap file is currently enabled, but when we restart, the server will not automatically enable the file for use. We can change it by modifying the fstab file, which is a table for managing file systems and partitions.

Edit the file in a text editor with sudo permissions:

sudo nano /etc/fstab

At the bottom of the file, you need to add a line to tell the operating system to automatically use the swap file you created:

/swapfile   swap    swap    sw  00

After adding rows, you can save and close the file. The server will check this file every time it starts so that it is ready to use the swap file from now on.

Adjust your exchange settings (optional)

You can configure some options that will affect the performance of the system when processing the exchange. In most cases, these configurations are optional, and the changes you make will depend on your application needs and personal preferences.

Swappiness

The swappiness parameter determines how often the system will swap data from the memory to the swap space. This is a value between 0 and 100, which indicates the percentage of memory usage that will trigger the use of swap.

When the value is close to zero, the system will not swap data to the drive unless absolutely necessary. Keep in mind that interactions with swap files are "expensive" because they are much slower than interactions with memory, and this difference in read and write speeds can cause a significant reduction in application performance. Telling the system not to rely on swap will usually make your system faster.

A value close to 100 will try to put more data into swap in an effort to keep more memory free. Depending on the memory profile of the application or the usage of the server, in some cases this may be a better choice.

We can view the current swappiness value by reading the swappiness configuration file:

cat /proc/sys/vm/swappiness
30

CentOS 7 defaults to a swappiness setting of 30, which is a fair middle ground for most desktops and local servers. For [Cloud Server] (https://cloud.tencent.com/product/cvm?from=10680), we may want to move it closer to 0. We can use the sysctl command to set swappiness to different values. For example, to set swappiness to 10, we can enter:

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

This setting will last until the next reboot. To keep the settings between restarts, we can add the output line to the sysctl configuration file:

sudo nano /etc/sysctl.conf

Add your swappiness settings to the bottom of the file:

vm.swappiness =10

After adding rows, you can save and close the file. The server will now automatically set swappiness to the value you declared each time it starts.

Cache pressure

Another related value you might want to modify is vfs_cache_pressure. This setting affects the storage of special file system metadata entries.

Constantly reading and refreshing this information is usually very expensive, so it takes longer to store it in the cache, which is very useful for system performance.

You can check the current value of this cache pressure by querying the file system again through proc:

cat /proc/sys/vm/vfs_cache_pressure
100

Due to the current configuration, our system deletes inode information from the cache too quickly. We can use sysctl to set it to a more conservative setting, such as 50;

sudo sysctl vm.vfs_cache_pressure=50

vm.vfs_cache_pressure =50

Again, this only applies to our current session. We can change it by adding it to the configuration file, just like we use the swappiness setting:

sudo nano /etc/sysctl.conf

At the bottom, add a line specifying the new value:

vm.vfs_cache_pressure =50

After adding rows, you can save and close the file. The server will now automatically set the cache pressure to the value you declare each time it starts.

in conclusion

Follow the steps in this tutorial and you will give your server some breathing room in terms of memory usage. The swap space is very useful in avoiding some common problems.

If you encounter an OOM (out of memory) error, or if you find that the system cannot use the required application, the best solution is to optimize the application configuration or upgrade the server. However, configuring swap space can provide you with greater flexibility.


Reference: "How To Add Swap on CentOS 7"

Recommended Posts

How to add swap on CentOS 7
How to add swap space on Ubuntu 20.04
How to increase swap space on CentOS 8
Explain how to add swap partition on Ubuntu 16.04
How to add and delete users on CentOS 8
How to install jdk1.8 on centOS7
How to install MySQL on CentOS 8
How to install R on CentOS 8
How to install FFmpeg on CentOS 8
How to install Virtualbox on CentOS 8
How to install TensorFlow on CentOS 8
How to Update to gcc4.9.x on Centos7
How to install TeamViewer on CentOS 8
How to install Gradle on CentOS 8
How to install Elasticsearch on CentOS 8
How to install Jenkins on CentOS 8
How to install Go on CentOS 8
How to install GCC on CentOS 8
How to install Yarn on CentOS 8
How to install Nginx on CentOS 8
How to install Asterisk on CentOS 7
How to install Jenkins on CentOS 8
How to install Vagrant on CentOS 8
How to install Skype on CentOS 8
How to install htop on CentOS 8
How to install Python on CentOS 8
How to install Elasticsearch on CentOS 8
How to install Postgresql on CentOS 8
How to install Wordpress on Centos
How to install htop on CentOS 8
How to install TeamViewer on CentOS 8
How to install MariaDB on CentOS 8
How to install MongoDB on CentOS 7
How to install Odoo 13 on CentOS 8
How to install Apache on CentOS 8
How to disable SELinux on CentOS 8
How to install OpenCV on CentOS 8
How to install PHP on CentOS 8
How to install MongoDB on CentOS 8
How to add swap partition in Ubuntu
How to install Apache Maven on CentOS 8
How to install Apache Kafka on CentOS 7
[Graphic] How to install tomcat on centos
R&D: How To Install Python 3 on CentOS 7
How to install GCC compiler on CentOS 7
How to modify the hostname on CentOS 8
How to install offline JDK1.8 on centos7.0
How to add Apt software source on Ubuntu
How to install and configure Elasticsearch on CentOS 7
How to install Visual Studio Code on CentOS 8
How to install and use Docker on CentOS 7
How to install RPM packages on CentOS Linux
How to set up SSH keys on CentOS 8
How to install and configure VNC on CentOS 8
How to install and use Composer on CentOS 8
How to install and configure Redis on CentOS 8
How to install Node.js and npm on CentOS 8
How to install jdk1.8.0_151 and mysql5.6.38 on centos7.2.1511
How to install and configure phpMyAdmin on CentOS 6
How to install and configure Owncloud on CentOS 8
How to build a LAMP environment on centos7.2