Home  »  ArticlesGuidesHow ToTechnology   »   How to Add Swap Space in Ubuntu 20.04 LTS

How to Add Swap Space in Ubuntu 20.04 LTS

Here you will learn how to add swap in Ubuntu 20.04 LTS. This will help you out of-memory errors on your server if you find they are occurring. Swap space may not be the best solution above properly optimizing your server or increasing RAM.

Swap space is a portion of your hard drive to store persistent data that is not accessed as frequently and to keep RAM free for other apps that are active. Swap is significantly slower than RAM so it is not ideal for the operating system to use it for running programs.

Your server may resort to using swap as a RAM fallback when the latter is depleted and this is why we want to reserve some hard disk space for the server whenever the need arises.

Warning: It is important to note that using swap space on SSDs is not recommended as it can cause degradation of the disk over time. Therefore swap is only recommended on systems with traditional spinning hard disk drives. Again you want to prioritize optimizing your server services to suit the hardware you have otherwise you may benefit more from adding additional RAM onto the server.

Adding Swap Space in Ubuntu 20.04 LTS

Step 1: Check if Swap is Already Enabled

The first thing you will want to do is to check if swap space has already been added to your system. This can be done by running the command below:

$ sudo swapon --show

If you do not get any output it means your system does not have swap space otherwise you will get something similar to this:

NAME      TYPE      SIZE   USED PRIO
/dev/dm-1 partition 1G 	364M   -2

You can also use the free utility to check for active swap space.

$ free -h

The output will look something similar to this:

              total        used        free      shared  buff/cache   available
Mem:          981Mi       129Mi       640Mi       0.0Ki       211Mi       714Mi
Swap:            1G      364M          0B

Step 2 – Check for Available Space on the Hard Drive Partition

Swap has to be created on the physical disk so it is important that you make sure the space exists in the first place. Run the following command to check for available space:

$ df -h

Your output will look something similar to this:

Filesystem      Size  Used Avail Use% Mounted on
udev            474M     0  474M   0% /dev
tmpfs            99M  932K   98M   1% /run
/dev/vda1        40G  1.4G   38G   3% /
tmpfs           491M     0  491M   0% /dev/shm
tmpfs           5.0M     0  5.0M   0% /run/lock
tmpfs           473M     0  491M   0% /sys/fs/cgroup
/dev/vda15      104M  3.9M  101M   4% /boot/efi
/dev/loop0       56M   55M     0 100% /snap/core18/1705
tmpfs            99M     0   99M   0% /run/user/1000

You are interested in the root device identified by “/” in the “Mounted on” column. Ideally, that is where you will want to reserve your swap space. You also have to be careful about how much space you have available so that you leave some space for the normal operating system and data storage needs.

A good starting point to the amount of swap you want is usually the same amount as RAM or double the amount but not exceeding 4G. If you need 4G of swap it might be a sign that you need to add physical RAM to your system instead of adding such a large amount of swap.

Step 3: Add the Swap Space

Seeing it is possible to have multiple swap files or swap partitions, we will not be featuring such a setup. In this guide, we will stick to one swap file.

We are going to use the fallocate program to create a swap file called swapfile in the root “/” directory.

In this example, we are creating a 2G file by running this command.

$ sudo fallocate -l 1G /swapfile

Next, we verify that the correct amount of space was reserved by typing:

$ ls -lh /swapfile

The output should be similar to this depending on the size you chose.

$ -rw-r--r-- 1 root root 1.0G Jun 10 11:14 /swapfile

Step 4: Enable the Swap File

Before we actually turn the file into swap space, we need to restrict permissions to the space to users with root privileges.

$ sudo chmod 600 /swapfile

Next, we mark the file as swap space by running the following:

$ sudo mkswap /swapfile

The following is the output:

Setting up swapspace version 1, size = 1024 MiB (1073737728 bytes)
no label, UUID=ce45582-0a2a-450f-cdd4-527e54026db7

Finally, we enable the swap file so that our system can use it:

$ sudo swapon /swapfile

Once again verify that the swap is available:

$ sudo swapon --show

The output should look something similar to this:

NAME      TYPE  SIZE USED PRIO
/swapfile file 1024M   0B   -2

Using the free utility:

$ free -h

Here’s the confirmed output:

              total        used        free      shared  buff/cache   available
Mem:          981Mi       115Mi       652Mi       0.0Ki       213Mi       714Mi
Swap:         1.0Gi          0B       1.0Gi

Step 5: Make the Swap File Permanent

The above commands will create the swap file which will be valid for the current session until the system is rebooted. We need to add the swap file to our “/etc/fstab” file to make the configuration permanent.

First thing, as a good practice, when doing any configuration changes, back up the “/etc/fstab” file.

$ sudo cp /etc/fstab /etc/fstab.bak

Add the swap information to the tail end of your /etc/fstab using this command:

$ echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab

Step 6: Optimize your Swap Settings

You will need to change the swappiness parameter which determines how often your system swaps data out of RAM to the swap space. The default is 60. This is a percentage anywhere between 0 and 100.

For values closer to zero, the system will not swap data to the disk unless absolutely necessary. Values that are closer to 100 put as much data as possible into swap in an effort to keep more RAM space free. You can test your swappiness by running the following:

$ cat /proc/sys/vm/swappiness

By default it will output:

60

The general rule is for Desktop flavors of Ubuntu, a swappiness setting of 60 is a good value. For a server environment values closer to zero are ideal. Around 10 is recommended as a good starting point.

You can change swappiness by running the following:

$ sudo sysctl vm.swappiness=10

With the successful output being:

vm.swappiness = 10

This value is only valid for the current session until the server is rebooted. To make it more permanent you need to edit the /etc/sysctl.conf file by running:

$ sudo nano /etc/sysctl.conf

Then add this line at the end of the file:

vm.swappiness=10

Save and close the file to make the changes permanent. Now, that is how to add swap in Ubuntu 18.04 LTS.

Adjusting the Cache Pressure Setting

We may now optionally modify is the vfs_cache_pressure setting which configures how much the system will choose to cache inode and dentry information over other data.

vfs_cache_pressure is basically access data about the filesystem which is very costly to look up furthermore it is very frequently requested. This is a good example of data you want your system to cache. You can see the current value by querying the proc filesystem again:

$ cat /proc/sys/vm/vfs_cache_pressure

Output

100

The default 100 may not be ideal as it tells our system to remove inode information from the cache too quickly. We can set this to a more conservative setting like 50 by typing:

$ sudo sysctl vm.vfs_cache_pressure=50

Output

vm.vfs_cache_pressure = 50

We now need to make the change permanent by adding it to our configuration file like we did with our swappiness setting:

$ sudo nano /etc/sysctl.conf

At the bottom, add the line that specifies your new value:

vm.vfs_cache_pressure=50

Save and close the file when you are finished.

Conclusion

The steps above should drastically reduce if not totally get rid of out-of-memory exceptions. Swap space, though useful, should be avoided on SSD-based storage in favor of optimizing your application configurations or upgrading your server RAM.

Found this article interesting? Follow Brightwhiz on Facebook, Twitter, and YouTube to read and watch more content we post.

Available under:
Articles, Guides, How To, Technology