Debug School

Cover image for Add Swap Space
Suyash Sambhare
Suyash Sambhare

Posted on

Add Swap Space

What is Swap?

The operating system uses the swap, a section of hard disc storage, to temporarily store data that it can no longer hold in RAM. With some restrictions, this enables you to expand the quantity of data that your server can store in its working memory. When there is no more room in RAM to store application data that is not being used, the swap space on the hard disc will be used.
Information written to disc will be substantially slower than information stored in RAM, but the operating system will prefer to keep running application data in memory while swapping out older data. Overall, having swap space as a backup for when your system's RAM runs out can be a decent safeguard against out-of-memory errors on systems with non-SSD storage.

Check for Swap

Before we begin, we can determine whether the system already has some swap space available. It is possible to have numerous swap files or swap partitions, but in most cases, one is sufficient.

We can see if the system has any configured swap by typing: sudo swapon --show
If you don’t get back any output, this means your system does not have swap space available currently.

You can verify that there is no active swap using the free utility:

free -h
               total        used        free      shared  buff/cache   available
Mem:           3.8Gi       262Mi       2.1Gi       3.0Mi       1.5Gi       3.3Gi
Swap:            0B          0B          0B
Enter fullscreen mode Exit fullscreen mode

As you can see in the Swap row of the output, no swap is active on the system.

Available Space

Check disk usage.

df -kh
Filesystem                         Size  Used Avail Use% Mounted on
tmpfs                              392M  1.3M  390M   1% /run
/dev/mapper/ubuntu--vg-ubuntu--lv   97G   48G   45G  52% /
tmpfs                              2.0G   28K  2.0G   1% /dev/shm
tmpfs                              5.0M     0  5.0M   0% /run/lock
/dev/vda2                          1.8G  245M  1.4G  15% /boot
tmpfs                              392M  4.0K  392M   1% /run/user/1000
Enter fullscreen mode Exit fullscreen mode

In this instance, our disc is the device that has / in the Mounted on column. With this case, we have a lot of area. It's likely that your usage will differ.

Although there are many different viewpoints on the optimal size of a swap area, it ultimately depends on your own preferences and application requirements. In general, an amount equal to or double your system's RAM is a decent starting point. Another fair rule of thumb is that anything more than 4GB of swap is usually unneeded if you're only utilising it as a RAM backup.

Create Swap

Now that we know how much hard drive space we have available, we can build a swap file on our filesystem. We will create a file called swapfile with the desired size in our root / directory. The best way to create a swap file is to use the fallocate application. This command instantaneously generates a file of the requested size. Because the server in our example has 4GB of RAM, we will generate a 8GB file in this tutorial. Change this to fit the requirements of your own server: sudo fallocate -l 8G /swapfile
To verify run :

ls -lh /swapfile
-rw------- 1 root root 8.0G Apr 29 02:23 /swapfile
Enter fullscreen mode Exit fullscreen mode

Enable swap

To convert a file into swap space, lock its permissions to only allow root users to access the contents, preventing normal users from accessing it, thereby ensuring security: sudo chmod 600 /swapfile
To verify run:

ls -lh /swapfile
-rw------- 1 root root 8.0G Apr 29 02:23 /swapfile
Enter fullscreen mode Exit fullscreen mode

Mark the file as swap space by typing:

sudo mkswap /swapfile
Setting up swapspace version 1, size = 8192 MiB (8589934592 bytes)
no label, UUID=6e765505-2bc3-76d2-be33-998f79799abc
Enter fullscreen mode Exit fullscreen mode

Enable the swap: sudo swapon /swapfile
Verify that the swap is available by typing:

sudo swapon --show
NAME      TYPE SIZE  USED PRIO
/swapfile file   8G 69.7M   -2
Enter fullscreen mode Exit fullscreen mode

Check the swap in free command

free -h
               total        used        free      shared  buff/cache   available
Mem:           3.8Gi       262Mi       2.1Gi       3.0Mi       1.5Gi       3.3Gi
Swap:          8.0Gi        69Mi       7.9Gi
Enter fullscreen mode Exit fullscreen mode

Swap

Make it permenant

The swap file is now enabled for the current session due to our recent modifications. But the server won't automatically save the swap settings if we restart it. By include the swap file in our /etc/fstab file, we can alter this. In case something goes wrong, make a backup of the /etc/fstab file: sudo cp /etc/fstab /etc/fstab.bak
Add the swap file information to the end of your /etc/fstab file by typing: echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab

Tuning your Swap Settings

There are a few options that you can configure that will have an impact on your system’s performance when dealing with swap.

Adjusting the Swappiness Property

The swappiness option determines how frequently your system swaps data from RAM to swap space. A percentage is represented by a figure ranging from 0 to 100. With values near zero, the kernel will not swap data to disc until absolutely essential. Remember that interactions with the swap file are "expensive" since they take much longer than interactions with RAM and can significantly reduce performance. Telling the system not to rely heavily on the swap will often improve system performance. Values closer to 100 will try to place more data into swap in order to free up more RAM space. Depending on your applications’ memory profile or what you are using your server for, this might be better in some cases.

We can see the current swappiness value by typing:

cat /proc/sys/vm/swappiness
40
Enter fullscreen mode Exit fullscreen mode

We can set the swappiness to a different value by using the sysctl command.
For instance, to set the swappiness to 10, we could type:

sudo sysctl vm.swappiness=10
vm.swappiness = 10
Enter fullscreen mode Exit fullscreen mode

This setting will persist until the next reboot. We can set this value automatically at restart by adding the line to our /etc/sysctl.conf file: sudo vi /etc/sysctl.conf
vm.swappiness=10
Save and close the file when you are finished.

Adjusting the Cache Pressure Setting

The vfs_cache_pressure is another relevant setting that you may choose to change. The system's preference for caching inode and dentry data over other data is determined by this setting.
In essence, this is filesystem access data. This is a great thing for your system to cache because it is typically quite expensive to search up and is frequently requested. By running a new query to the proc filesystem, you may view the current value: cat /proc/sys/vm/vfs_cache_pressure
sudo sysctl vm.vfs_cache_pressure=50
Again, this is only valid for our current session. We can change that by adding it to our configuration file like we did with our swappiness setting: sudo vi /etc/sysctl.conf
At the bottom, add the line that specifies your new value: /etc/sysctl.conf
vm.vfs_cache_pressure=50

Following the instructions in this guide will offer you some breathing room in situations that would otherwise result in out-of-memory exceptions. Swap space can be extremely valuable in preventing some of these frequent issues. If you are experiencing OOM (out of memory) difficulties or your system is unable to perform the apps you require, the best option is to optimise your application setups or upgrade your server.

Ref: https://www.digitalocean.com/community/tutorials/how-to-add-swap-space-on-ubuntu-20-04

Top comments (0)