How to Extend Swap Space using Swap file in Linux

Swap space is a specialized storage area on the disk that can be partitioned or stored as a file. When the Linux kernel needs to allocate more memory to processes, it uses swap space to move infrequently utilized processes or tasks. In some cases, our Linux computer may run out of swap space, in which case we can increase the swap capacity by using a swap partition or a swap file. In this tutorial, we’ll look at how to use a swap file to expand swap space in Linux.

Steps to extend Swap Space using Swap File in Linux:

The swap partition is 2 GB in this situation. As a result, swap space will be increased by 1 GB.

Steps to extend Swap Space using Swap File in Linux:Steps to extend Swap Space using Swap File in Linux:

1 Create a swap file of size 1 GB:

[[email protected] ~]# dd if=/dev/zero of=/swap_file bs=1G count=1
        1+0 records in
        1+0 records out
        1073741824 bytes (1.1 GB) copied, 414.898 s, 2.6 MB/s
        [[email protected] ~]#

Change the values of ‘bs’ and ‘count’ to suit your needs.
To create a file, we can alternatively use the fallocate command, as seen below.

$ sudo fallocate -l 1G /swap_file

Step 3 Enable the Swap Area on Swap File:


To enable the swap area on the file, use the mkswap command.

Step 4: Add the swap file entry in fstab file:

To make the swap file persistent between reboots, add the following item to the fstab file. Use the echo command or the vi editor to add the following entry to the fstab file.

To activate swap space on the file, use the swapon command, which will eventually expand the swap space.

Step 6: Now verify the swap space:

To check swap space, use the ‘free -m’ or’swapon -s’ commands.

Note:  To disable the swap file for debugging purposes, use the swapoff command as shown below, and then use the swapon command as described in step 5 to re-enable it.