1. Home
  2. Linux
  3. General
  4. Create a Swap File in Linux

Create a Swap File in Linux

Create a Swap File in Linux
Create a Swap File in Linux

A New Day! A New tutorial ” How to Create a swap file in Linux”.
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

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.
Before going to details, let’s have look at best VPS hosting and what we have already covered about Linux:

  1. How To Find Installed Packages Version In Linux
  2. Install Config Server Firewall (CSF) on a Linux VPS

Creating a Swap File in Linux

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

One more thing..
Share this tutorial with your hosting administrators and networking experts friends, as it will help them and make my countless hours of work count.
Thanks!

Updated on December 23, 2018

Was this article helpful?

Related Articles

Leave a Comment

[apsl-login-lite login_text='Please login with a social account']