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.
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).
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.
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 youdh
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.
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.
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.
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.
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.
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.
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.
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