Home » How To » How to Add Swap Space on Ubuntu Linux

How to Add Swap Space on Ubuntu Linux

Swap is a location on the hard disk that is used as Memory by the operating system. When the operating system detects that the main memory is getting full and required more RAM to run applications properly it check for swap space and transfer files there. In general terms, swap is a part of the hard disk used as RAM on the system.

I have a virtual machine running which don’t have a swap on it. Many times services got crashed due to insufficient memory. In this situation, the creation of a Swap file is better to keep them up. This article will help you to create a swap file on the Linux system after installation.

How to Add Swap in Ubuntu 20.04

Follow the below steps to create and enable Swap memory on your Ubuntu system.

1. Check Current Swap

Before working make sure that the system has already swap enabled. If there is no swap, you will get the output header only.

sudo swapon -s


2. Create Swap File

Let’s create a file to use for swapping in the system of the required size. Before making a file make sure you have enough free space on disk. Generally, it recommends that swap should be equal to double of installed physical memory.

Related:  How to Run Cron Jobs Every 5, 10, or 15 Minutes

My AWS EC2 VM has 2GB of memory. So creating the swapfile of 4GB in size.

sudo fallocate -l 4G /swapfile
chmod 600 /swapfile

Then, make it to swap format and activate on your system by running the following commands:

sudo mkswap /swapfile
sudo swapon /swapfile

3. Make Swap Permanent

After running the above commands, Swap memory is added to your system and the operating system can use when required. But after the reboot of the system swap will deactivate again.

You can make it permanent by appending the following entry in /etc/fstab file. Edit fstab file in editor:

sudo vim /etc/fstab

and add below entry to end of file:

/swapfile   none    swap    sw    0   0

Add swap in fatab

Save file and close. Now Swap memory will remain activated after the system reboots.

4. Check System Swap Memory

You have successfully added swap memory to your system. Execute one of the below commands to view current active swap memory on your system:

sudo swapon -s
free -m


Related:  Top 10 Rolling Release Linux Distributions


5. Update Swappiness Parameter

Now change the swappiness kernel parameter as per your requirement. It tells the system how often the system utilizes this swap area.

Edit /etc/sysctl.conf file:

sudo vim /etc/sysctl.conf

append the following configuration to end of file


Now reload the sysctl configuration file

sudo sysctl -p

In this tutorial, we have learned about adding Swap memory on the Ubuntu Linux system. Feel free to use the comment section in case of any query 😎

Leave a Comment