How to Enable Swap on Ubuntu systems

Swap is very useful for those systems which required more RAM If memory is full services got crashed due to insufficient memory. In this situation system required more RAM to run applications properly as it check for swap space and transfer files there.

In general terms, So the creation of Swap file is better to keep the services up.

Check System Swap

Before proceeding further make sure that system already has swap enabled. If there are no swap, you will get output header only.

sudo swapon -s

Create Swap File

Now we will create a file to use for swap in system. Before making file make sure you have enough free space on disk. Normally, it is recommends that swap size should be equal to double of installed physical memory.

We have 2GB memory in my system. So will create swap of 4GB in size.

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

Make It Swap

Now we make it usable file using mkswap command.

sudo mkswap /swapfile

Enable Swap

Now setup the swap for system using swapon command.

sudo swapon /swapfile

Now again check that swap is enabled or not. You will see results something like below.

sudo swapon -s

Filename Type Size Used Priority
/swapfile file 4194300 0 -1

Setup Swap Permanent

Add the following entry in /etc/fstab file to enable swap on system reboot.

nano /etc/fstab

/swapfile none swap sw 0 0

Setup Kernel Parameter

Now time to change the swappiness kernel parameter as per your requirement. It will tell the system how often system utilize this swap area.

Edit /etc/sysctl.conf file and add following configuration in file.

sudo nano /etc/sysctl.conf

vm.swappiness=10

Now reload the sysctl configuration file

sudo sysctl -p

Now, you have successfully enabled swap on your Ubuntu system.