How to Make a SWAP file in Linux

Swap is a space on a disk that is used when the amount of physical RAM memory is full. When a Linux system runs out of RAM, inactive pages are moved from the RAM to the swap space. Swap space can take the form of either a dedicated swap partition or a swap file. In most cases, when running Linux on a virtual machine, a swap partition is not present, so the only option is to create a swap file.

In this article, I will show you how to create a swap file in Linux, but before that, watch my other tutorial on how to create an EC2 instance. Once you have done the setup of the EC2 instance, then follow the instructions below to make a swap file.

1.    Use the dd command to create a swap file on the root file system. In the command, bs is the block size and count is the number of blocks. The size of the swap file is the block size option multiplied by the count option in the dd command. Adjust these values to determine the desired swap file size.

The block size you specify should be less than the available memory on the instance or you receive a “memory exhausted” error.

In this example dd command, the swap file is 4 GB (128 MB x 32):  

$ sudo dd if=/dev/zero of=/swapfile bs=128M count=32

2.    Update the read and write permissions for the swap file:

$ sudo chmod 600 /swapfile

3.    Set up a Linux swap area:

$ sudo mkswap /swapfile

4.    Make the swap file available for immediate use by adding the swap file to swap space:  

$ sudo swapon /swapfile

5.    Verify that the procedure was successful:

$ sudo swapon -s

6.    Enable the swap file at boot time by editing the /etc/fstab file.

Open the file in the editor:

$ sudo vi /etc/fstab

Add the following new line at the end of the file, save the file, and then exit:

/swapfile swap swap defaults 0 0

If you have reached so far without any error then it means you have successfully setup SWAP on your Linux system. Enjoy 🙂

Leave a Comment

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