Create a Linux Swap File

30 Jul 2018 4 44  0
Create a Linux Swap File
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:


/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

/swapfile file 1024M 507.4M   -1


sudo free -h


              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
Add a comment

Leave a Reply

Related Tutorials