Swap memory is a part of system permanent storage (harddisk). When the system found the physical memory of the system is full, then it automatically starts the utilization of Swap memory available on the system. In simple terms, swap memory is a part of the hard disk used as RAM on the system.
If your system is facing issues like system running out of memory frequently and you don’t want to increase physical memory. Then this is the best idea to add Swap memory on your system. Remember, swap memory is good but much slower than physical memory. This tutorial will help you to create a swap file on the Linux system and use it as swap memory.
Create Swap File in Linux
Here is the step by step tutorial to create a swap file on the Linux machine and configure in the system.
1. Check System Swap
Before start working, check if the system has already swap enabled. If there is no swap, you will get an output header only.
sudo swapon -s
2. Create Swap File
Let’s create a file to use for swap in the system of the required size. Before making a file make sure you have enough free space on the disk. Generally, it recommends that swap should be equal to double of installed physical memory.
My system have 2 GB physical memory installed. So I am creating a swap file of 4 GB using following command. Then set the proper permission on file:
sudo fallocate -l 4G /swapfile chmod 600 /swapfile
3. Make It Swap
Now make this file as swap usable file using mkswap command.
sudo mkswap /swapfile
4. Enable Swap
After that, enable the swap memory on your 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
5. Setup Swap Permanent
Append the following entry in /etc/fstab file to enable swap on system reboot. Its a good idea to make a copy of this file before changes:
cp /etc/fstab /etc/fstab.backup vim /etc/fstab
/swapfile none swap sw 0 0
6. Setup Kernel Parameter
Now change the swappiness kernel parameter as per your requirement. It tells the system how often the system utilizes this swap area.
Edit /etc/sysctl.conf file and append following configuration in file.
sudo vim /etc/sysctl.conf
Now reload the sysctl configuration file
sudo sysctl -p
You can also use the free or top command to view Swap memory.
If you don’t need a swap file or need to increase swap file. You can disable an already active swap file on the system using the following command.
You can create a new larger swap file using the above steps or to disable permanently remove the entry from /etc/fstab file.
You have successfully created a swap file on your Linux machine and configured it as swap memory.