How to Create Swap File in Linux

In Linux, a swap is an assigned area in the hard disk to hold temporary data. It works the same way as memory RAM, except that it is located within the hard disk instead of the RAM. Think of it as a backup to your RAM. When the RAM is full, temporary data in the RAM are moved to the swap to free up space in the RAM.

In computers with 4GB or less of RAM, it is often advised to have a dedicated swap partition that is of the same size as the RAM in the system. So for a 4GB computer, it is good to a swap partition of 4GB.

However, the computers nowadays come with more RAM than required, and swapping does not occur as frequent. As such, it is a waste to setup a dedicated swap partition that is not doing anything. A swap file is a better choice in this case.

What is a Swap File?

Same as the swap partition, a swap file is a swap that exists in the form of a file, rather than a partition. The good thing about a swap file is that it can be added/removed easily and there is no need to worry about the partition size as it can be expanded/shrunk as you wish.

How to Create a Swap File

It is easy to create a swap file in Linux.

1. Open a terminal. To create a swap file of 2GB, type the following:

sudo fallocate -l 2G /mnt/2GB.swap

Alternatively, if the above command fails, use this command instead:

sudo dd if=/dev/zero of=/mnt/2GB.swap bs=1024 count=2097152

2. Next, format the swap file:

sudo mkswap /mnt/2GB.swap

3. Change the permission:

sudo chmod 600 /mnt/2GB.swap

4. Activate the swap file:

sudo swapon /mnt/2GB.swap

That’s it. To check if the swap file is working:

sudo swapon -s
Swap File Swapon

To mount the swap file on boot up, first open up the “/etc/fstab” file:

sudo nano /etc/fstab

And add this line to the end of the file:

/mnt/2GB.swap swap swap defaults 0 0

Save and exit the file.

Swappiness

The swappiness value of a swap file determines how often the swap file is used to store temporary data. The swappiness value is a number from 0 to 100. The default value is 60. You can check it with the command:

cat /proc/sys/vm/swappiness
Linux Swappiness Value

The higher the value, the more likely the swap file will be used. In ideal case, you won’t want the swappiness value to be too high.

To change the swappiness value, open the file “/etc/sysctl.conf”

sudo nano /etc/sysctl.conf

and add the swappiness value in it:

vm.swappiness=10

Save and exit the file.

Removing the swap file

If you need to remove the swap file, do it in the reverse order:

1. Remove the swap entry from the “/etc/fstab” file.

2. Deactivate swap:

sudo swapoff /mnt/2GB.swap

3. Remove the swap file

sudo rm /mnt/2GB.swap

That’s it.

Wrapping Up

Unless you are still using a old computer with less than 4GB of RAM, it is better to use a swap file than a dedicated swap partition, as it is easier to create and manage.