Imagine a scenario where our Linux system runs out of swap space, in which case we want to expand the swap space using the swap partition, but in some cases there is no free partition available on the disk, so we can't expand it.
Therefore, in this case, we can use the swap file to increase the swap space.
Here's how to extend the swap space on Linux using a swap file
Let's first check the size of the existing swap space/partition, using the command ' free-m ' or ' swapon-s '
My swap partition size is 2 GB and we will extend the swap space to 1GB.
Step One: Create a size 1GB interchange file using the following DD command
The code is as follows:
[Root@linuxtechi ~]# 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, 2.6 mb/s
[Root@linuxtechi ~]#
Replace the size of ' BS ' and ' count ' according to your needs.
Step two: Set the swap file permission to 600
The code is as follows:
[Root@linuxtechi ~]# chmod 600/swap_file
Step three: Open the Exchange area with file (Swap_file)
Open the swap area with the Mkswap command
The code is as follows:
[Root@linuxtechi ~]# Mkswap/swap_file
Setting up Swapspace version 1, size = 1048572 KiB
No label, uuid=f7b3ae59-c09a-4dc2-ba4d-c02abb7db33b
[Root@linuxtechi ~]#
Fourth step: Add an Interchange file entry in the Fstab file
Add the following entry in the Fstab file so that the swap file can continue to work each time it restarts.
The code is as follows:
/swap_file Swap Defaults 0 0
Step Fifth: Enable the swap file with the command ' Mkswap on '.
The code is as follows:
[Root@linuxtechi ~]# Swapon/swap_file
[Root@linuxtechi ~]#
Sixth step: View Swap space now
Note: To avoid an unexpected situation, use the Swapoff command to close it as shown below, using the Swapon command shown in step 5 to re-enable the swap file only when you need to use it.
The code is as follows:
[Root@linuxtechi ~]# Swapoff/swap_file
[Root@linuxtechi ~]#