Create a Linux Swap File
Swap is space on a disk which is used once the total amount of available physical RAM is used. Once a Linux system begins running out of RAM, inactive pages are moved from RAM to the swap space.
Swap can be a dedicated swap partition or a swap file. In a lot of cases, a swap partition is not present on virtual machines, but we can still create a swap file.
Creating a Swap File
Step 1: Create the file which will be used for swap storage.
In this example, we are going to create a 1 GB swap file:
sudo fallocate -l 1G /swapfile
Step 2: Set the correct permissions:
sudo chmod 600 /swapfile
Step 3: Set up the swap file:
sudo mkswap /swapfile
Step 4: Enable the swap file:
sudo swapon /swapfile
To make the change permanent, open the /etc/fstab file and append the following line:
/etc/fstab /swapfile swap swap defaults 0 0
Step 5: Verify the swap status:
To verify that the swap is available, we can use either the swapon or the free command as shown below:
sudo swapon --show
NAME TYPE SIZE USED PRIO /swapfile file 1024M 507.4M -1 Copy sudo free -h Copy total used free shared buff/cache available Mem: 488M 158M 83M 2.3M 246M 217M Swap: 1.0G 506M 517M
Removing a Swap File
If for any reason you want to remove the swap file, first you need to disable the swap file using the following command:
sudo swapoff -v /swapfile
Then remove the swap file entry /swapfile swap swap defaults 0 0 from the /etc/fstab file.
Finally, delete the actual swapfile file:
sudo rm /swapfile