create swap file in linux

How to Create Swap File in Linux

Swap space is a disk space or file that is used to move out inactive pages (processes) when your server’s memory becomes full. It can be configured as a separate partition or a swap file. In this article, we will look at how to create swap file in Linux.

How Does Swap Space work

Typically, processes are loaded into physical memory (RAM) and they run from that location, on a server. As more processes are run on your server, more and more physical RAM is consumed. When your server starts running out of memory, the operating system (Linux) swaps out inactive processes (organized as pages) into a parking space known as swap area. They are loaded back only when they become active once again. This swap area can be a part of your disk, a separate partition altogether, or a separate file known as swap file.

How to Create Swap File in Linux

Here are the steps to create swap file in Linux.

1. Create Swap file

Open terminal and run the following command to create a swap file of 1GB space for your server. If you want to increase it to 2GB just replace 1G with 2G in the command below.

$ sudo fallocate -l 1G /swapfile
$ sudo dd if=/dev/zero of=/swapfile bs=1024 count=1048576

2. Set Root Permissions

Since it is a sensitive file, only root user should be allowed to read-write to it. So run the following command to enable only root user to use swap file.

$ sudo chmod 600 /swapfile

3. Set up Swap file as Swap area

Next, run the mkswap command to setup the new swap file as swap area.

$ sudo mkswap /swapfile

4. Enable Swap File

Run the following command to enable swap file.

$ sudo swapon /swapfile

However, these changes will be lost on system reboot. To make these changes permanent, open /etc/fstab file in a text editor

$ sudo vi /etc/fstab

and add the following line to it.

/swapfile swap swap defaults 0 0

Save and close the file.

You can verify the swap space with either of the following commands.

$ sudo swapon --show
$ sudo free -h

5. (Optional) Remove Swap File

If you want to remove the swap file, you need to undo the above steps in reverse order. First, deactivate the swap file with the following swapoff command.

$ sudo swapoff -v /swapfile

Next, open /etc/fstab file and remove the following line from it.

/swapfile swap swap defaults 0 0

Save and close the file.

Finally, delete the actual swap file created in first step at the beginning of this article.

$ sudo rm /swapfile

That’s it. In this article, we have learnt how to create as well as remove swap file in Linux.

Also read:

SFTP Script to Transfer Files in Linux With Password
How to Reverse String in Python
How to Connect to PostgreSQL Database in Python
How to Remove Snap in Ubuntu
How to Select Random Records in MySQL

Leave a Reply

Your email address will not be published. Required fields are marked *