How to Create a Linux Swap File

In this tutorial, we will show you How to Create a Linux Swap File.

Swap is space on the hard disk that is reserved to use as virtual memory. When a Cloud Server runs out of memory the Linux kernel moves inactive processes into swap to make room for active ones in working memory.
If you don’t have Linux server get it by following this link.
To add 1GB swap file follow these steps.

First, create the file by running this command

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

If was not installed, run this command:

sudo dd if=/dev/zero of=/mnt/1GB.swap bs=1024 count=1048576

After, format the file:

sudo mkswap /mnt/1GB.swap

Next, add the file to the system:

sudo swapon /mnt/1GB.swap

After adding the file to the system, add this line in /etc/fstab (to edit /etc/fstab run this command nano /etc/fstab):
/mnt/1GB.swap none swap sw 0 0

To change the value of swap edit /etc/sysctl.conf by run this command:
nano /etc/sysctl.conf
And add this line
vm.swappiness=5


To see if swap file was created, run this command:
sudo swapon -s

Reboot the server and after rebooting chmod the file to take effect.
chmod 600 /mnt/1GB.swap

You successfully created a swap file in Linux.

Enjoy!

Register for free account now.

Related Articles