Permanent swap space in Ubuntu

Upasana | July 21, 2020 | 2 min read | 42 views

In this article, we will add file system based additional memory to Ubuntu operating system using swap file.

Steps to add permanent swap space in Ubuntu 18.04/Ubuntu 20.04 LTS

1. Check if swap space is already enabled

$ sudo swapon -s

If swap space is already active, the above command will output information about swap

/swapfile file 1024M 507.4M   -1

2. Create a file which will be used as swap space:

$ sudo fallocate -l 4G /swapfile

this will allocate 4GB of disc space to swapfile.

3. Set correct permissions on this file to only allow root user

We want to ensure that only root user can read and write to this newly created swap file.

$ sudo chmod 600 /swapfile

4. Setup this file as linux swap file

$ sudo mkswap /swapfile

5. Activate the swap space

$ sudo swapon /swapfile

After this command you should be able to see the swap swpace in overall computer memory. Check it using below command.

$ sudo free -h

or the below command:

$ sudo swapon --show

6. Make swap permanent

By default this swap file will go away after you rebootyour system. To persist changes across reboots, you need to add the swap entry into /etc/fstab file.

$ sudo vi /etc/fstab

And paste the below line:

/swapfile swap swap defaults 0 0

7. Adjust system swappiness value

Swappiness value defines at what priority the swap space will be used by the operating system. Value can range from 0 (os avoids using swap) to 100 (os will aggressively use swap space). Default value of swap space could be around 30.

If you are using SSD, its better to keep system swappiness to a low value like 5 or 10 (so that lesser number of writes happen on swap)

$ cat /proc/sys/vm/swappiness


$ sudo vi /etc/sysctl.conf

Add the below line:


8. Remove swap space completely

If you want to remove the swap space completely, you can follow these steps:

  1. Turn off the swap $ sudo swapoff -v /swapfile

  2. Remove swap file entry from /etc/fstab which contains /swapfile swap swap defaults 0 0

  3. Delete the actual swap file on system using sudo rm /swapfile

That’s all.

Top articles in this category:
  1. Install Cassandra 4 on Ubuntu 20.04
  2. Install ElasticSearch 7 on Ubuntu 20.04
  3. Install RabbitMQ and Erlang 23 on Ubuntu 20
  4. Install OpenJDK 11 on Ubuntu 18.04 LTS
  5. Install & configure Redis on Ubuntu
  6. Upgrade Jenkins on Ubuntu 18.04 LTS
  7. Upgrade MySQL from 5.7 to 8 on Ubuntu 18.04

Recommended books for interview preparation:

Find more on this topic:
Buy interview books

Java & Microservices interview refresher for experienced developers.