Create a Linux Swap Using a File in 5 minutes


What is Swap Memory in Linux?

Linux systems use swap space instead of RAM to process the inactive pages (process requests to CPU) in the physical memory. If the amount of physical memory (RAM) is full when the system needs more memory resources, then inactive pages in the RAM will be moved to the swap space to process the requests with the CPU.

So, one might ask, since I have more than enough memory available, wouldn’t it better to delete swap space? The short answer is, No. There are many performance benefits available when swap space is enabled, even when you have more than enough RAM. Swap does not change the amount of RAM required for a healthy server, it’s designed to be complementary to the performance of systems. Swap space can be either a disk partition or a file present in the hard drive.

Benefits of using SWAP

  • Prevents from running out of memory (OOM).
  • Help to run heavy applications more conveniently.
  • Enhances the overall performance of your system.

There are two ways to create a swap space to the linux systems.

  1. Swap partition
  2. Swap file.

We are going to learn configuring a simple swap file method in less than the 5 minutes using with below steps…

  • Step1: Switch to root user and enter password
  • Step2: Create a swap file using the dd command
  • Step3: Make a swap file for Linux swap area
  • Step4: Secure swap file
  • Step5: Enable the swap file
  • Step6: Update fstab records – Just to ensure swap file always available even 
    • after the reboot.
  • Step7: Enable and verify the created swap area

Commands

#1 su root

#2 dd if=/dev/zero of=/root/swapfile1 bs=1M count=1024

if =/dev/zero: Read from /dev/zero file. /dev/zero is a special file in that provides as many null characters to build storage file called /swapfile1.
of =/swapfile1: Read from /dev/zero write storage file to /swapfile1.
bs =1M: Read and write 1Mega bytes at a time.
count =2048: Copy only 2048 BLOCKS input blocks.

#3 mkswap /root/swapfile1

#4 a) chown root:root /root/swapfile1
   b) chmod 600 /root/swapfile1

#5 swapon /root/swapfile1

#6 vi /etc/fstab – Add below lines
/root/swapfile1	swap	swap	defaults		0 0

#7 a) swapon –s
   b) free –m

Conclusion

In this article, we have gone through the configuration of swap memory along with its usage and benefits. In this digital world, all sophisticated applications require a large amount of RAM to operate smoothly. So we would need a sufficient amount of RAM to avoid our applications from crashing but there is a cost behind adding in more RAM to the systems. Hence, the only option we are left with is to use swap memory which can make our system work very efficiently without any cost!

  1. Pingback:
  2. March 30, 2021

    Excellent!

    Reply

Leave A Comment

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