In this tutorial, we will demonstrate a step by step guide to create swap file on Linux with examples. The process is same for Ubuntu and any other Linux distribution.
What is Swap File?
Swap is a space on the disk that is used when the amount of your physical RAM memory is full. The inactive pages will be moved to swap space from RAM when the system runs out of memory.
In most of the cases, a swap partition or swap space won’t be present and you will end with out of memory issue. In such cases the only option is to create a swap file.
This tutorial was tested on Linux bases systems with Ubuntu 20.04 and CentOS 8 but it should work with any other Linux distribution.
Create Swap File on Linux
Follow below steps to add 1G of swap to your server. If you want to add more swap then replace the
Note: Anything over 4G of swap is probably unnecessary if you are just using it as a RAM fallback.
Step 1: Create a file that we will be used for swap space.
sudo fallocate -l 1G /swapfile
Step 2: Set the permissions to the swap file so that only root user can write or read the file.
sudo chmod 600 /swapfile
Step 3: Use
mkspace to set up the file as Linux swap area.
sudo mkswap /swapfile
Step 4: Run the below command to enable the swap.
sudo swapon /swapfile
This is temporary. To make changes permanent, open the
/etc/fstab file and copy and paste the below snippet in newline.
/swapfile swap swap defaults 0 0
Step 5: To verify that the swap is active, you can use either
free command as shown below,
sudo free -h
total used free shared buff/cache availableMem: 488M 158M 83M 2.3M 246M 217M Swap: 1.0G 506M 517M
Tweak Swap Settings
swappiness property defines how often the system will use the swap space. This is a value between 0 and 100.
The lower value tells Linux kernel to avoid swapping whenever possible, while the higher values tells use swap space more aggressively.
You can check the current
swappiness value by executing below command,
swappiness value is set to 60.
The default swappiness value is OK for most of the Linux systems, but would recommend to set lower value for production servers.
To modify the swappiness value, run the below command,
sudo sysctl vm.swappiness=10
This will set value to 10 and to make this value persistent during reboot add the below code snippet to the
How to Remove Space File
Follow below steps to remove the swap file for any reason.
Step 1: First deactivate the swap.
sudo swapoff -v /swapfile
Step 2: Remove the swap file entry
/swapfile swap swap defaults 0 0 from the
Step3 : Now delete the actual swapfile file using the
sudo rm /swapfile
We hope this tutorial helped you to create swap file on Linux and also how to deactivate or delete the swap file.
If you face any issues, please do let us know in the comment section. We are happy to help you.