DEV Community

Cover image for How to Add Swap Space on Ubuntu 20.04
Suresh Ramani
Suresh Ramani

Posted on • Originally published at techvblogs.com

How to Add Swap Space on Ubuntu 20.04


A swap is a space on a disk that is used when the amount of physical RAM memory is full. When a Linux system runs out of RAM, inactive pages are moved from the RAM to the swap space.

In the case of Linux, the swap file is an important part. It's not a must-have option but having one is crucial for a number of purposes. Generally, when installing the system, you have to declare the size of the swap file. The recommended size is 4GB but you can either decrease or increase it depending on your demand.

If you want to change the size of your swap file just follow the following steps.

Note:  Running all these commands requires root privilege, so I recommend running a root terminal.

  1. Turn off all running swap processes
swapoff -a
Enter fullscreen mode Exit fullscreen mode
  1. Resize swap
fallocate -l 2G /swapfile
Enter fullscreen mode Exit fullscreen mode

Here, the total size of the swap file will be 2GB .

  1. CHMOD swap
chmod 600 /swapfile
Enter fullscreen mode Exit fullscreen mode
  1. Make file usable as swap
mkswap /swapfile
Enter fullscreen mode Exit fullscreen mode

Activate the swap file

swapon /swapfile
Enter fullscreen mode Exit fullscreen mode

To verify your swap size run the following command and you will see the swap size.

free -m
Enter fullscreen mode Exit fullscreen mode

Removing a Swap File

To deactivate and remove the swap file, follow these steps:

Start by deactivating the swap space by typing:

sudo swapoff -v /swapfile
Enter fullscreen mode Exit fullscreen mode

Next, remove the swap file entry  /swapfile swap swap defaults 0 0 from the  /etc/fstab file.

Finally, remove the actual swapfile file using the  rm command:

sudo rm /swapfile
Enter fullscreen mode Exit fullscreen mode

Thank you for reading this blog.

Discussion (0)