Swap space in a Linux system functions as a secondary memory, allowing the operating system to utilize it when the physical RAM is fully utilized. This “swapping” mechanism ensures smoother performance when the system requires more memory than is available. While many systems come with a dedicated swap partition, there are situations when adding or extending swap space via a swap file becomes necessary.
In a typical Linux system, if the RAM usage approaches its limit, the system will begin moving idle or less frequently accessed processes to the swap space, ensuring that the most crucial tasks have adequate memory to run efficiently. A swap file acts similarly to a swap partition but is more flexible, allowing for easy resizing and relocation.
For users who've opted not to create a swap partition during Linux installation, or who simply need additional swap space, creating a swap file is a straightforward process. This guide will outline the necessary steps to create a swap file in Linux.
$ sudo dd if=/dev/zero of=/swapfile bs=1M count=2048 status=progress
$ sudo chmod 600 /swapfile
$ sudo mkswap /swapfile
$ sudo swapon /swapfile
Activating the swap file with the swapon command will enable it for the current session. To make it persistent across reboots, add an entry to /etc/fstab.
$ sudo nano /etc/fstab
/swapfile none swap sw 0 0
$ free -h
The free command displays the total amount of free and used physical and swap memory in the system.
$ echo vm.swappiness=10 | sudo tee -a /etc/sysctl.conf
The swappiness parameter controls how often the system uses the swap file. A value closer to 100 makes the system use the swap more often, whereas a value closer to 0 makes it rely more on physical memory. Adjust this value based on your system's needs and performance.
Now, your Linux system is equipped with additional swap space using a swap file, ensuring smoother performance during high memory usage scenarios.
Comment anonymously. Login not required.