Jitdor Tech Tips

Adding Swap Space in Linux

Swap in Linux is the equivalent of virtual memory in Windows – a space on a disk that is used when the system runs out of RAM. For some reason unknown, many cloud instances are deployed without any swap.

Swap can be either a dedicated partition or a swap file. As most cloud disks provided in the cloud do not contain a swap partition, our only option is to create a swap file within the existing file system. This would also allow for easy resizing and removal of the swap file.

To find out whether the current system has a swap space, we can use either the free -h or swapon --show command. If you only see the Mem: line or an empty output, swap space is not present in your system

Creating a swap file

The following commands would create, initialize and activate the swap file in your system:

fallocate -l 1G /swapfile
chmod 600 /swapfile
mkswap /swapfile
swapon /swapfile

After which, run swapon --show again to see if everything is in order. Below is a sample output:

/swapfile file 1024M 45M -2

free -h would also indicate the presence of the swap space now:

total        used        free      shared  buff/cache   available
Mem: 372M 236M 64M 272K 71M 124M
Swap: 1.0G 43M 980M

Making the changes permanent

By default, the swap space would be disabled when you restart the cloud instance. To make the changes persistent, add the following line in the /etc/fstab file:

/swapfile swap swap defaults 0 0






Leave a Reply