Linux·28 questions

How to configure swap or add a swap file in Linux?

Answer

Virtual memory and the swap mechanism play a critical role in the stability of the operating system, especially when running resource-intensive applications or compiling heavy software. If physical RAM is insufficient, the Linux kernel starts moving inactive pages to a special swap partition or swap file.

If a swap partition was not created during system installation or its size turned out to be insufficient, the best solution is to create a dedicated swap file. This method does not require changing the disk layout and allows you to flexibly manage the size of virtual memory at any time.

The process of creating a swap file consists of several sequential steps:

Allocating disk space of the required size using the fallocate or dd utility.
Setting secure access permissions for the created file exclusively for the superuser.
Formatting the file as a swap area using the mkswap command.
Activating the swap file in the current session using the swapon command.

To make the operating system automatically attach the created file after each reboot, you need to add a corresponding entry to the system fstab file. To do this, a line is added to the end of the file specifying the path to the swap file, the mount point, and activation parameters.

It is also useful to adjust the vm.swappiness parameter, which determines how aggressively the Linux kernel uses swap. Decreasing this value forces the system to use physical RAM for as long as possible, increasing overall system performance on computers with sufficient RAM.

Was this answer helpful?

More questions in this topic

Related questions from other topics