Linux Swap File

Linux provides a Swap file which is used as a memory or RAM. Typically currently running processes, tasks and jobs use memory and RAM in order to store volatile information. But in some cases, the available memory space is not enough. When the memory filled up a disk-based memory file named Swap is used to store running processes, tasks, and job information. The swap file is also called as 3rd level memory.

The swap file is a type of virtual memory because it is not originally created like memory or physical memory. By creating and using the swap file the memory is extended or increased.

Swap File Size

There is no technical limitation for the swap file size. but there are some best practices where generally half of the physical memory or RAM is preferred. For example if the system has 8 GB RAM or memory the swap file can be made as 4GB. In total the system has 12GB memory.

Create Swap File

The swap file can create in different ways. A regular file can be used as a swap file as well as a partition of the disk can be also used as swap file. But using a disk partition as swap file is more reliable than using a file. Also, the swap file should have a swap file system in order to address data properly. In the following example, we will create a swap file that is located under the root. the fallocate command is used to allocate space for the specified file. We will create a 4GB swap file.

sudo fallocate -l 4GB /swap

Alternatively, the dd command can be used to create a swap file and allocate the required space. Because fallocate may be missed in some Linux distributions.

sudo dd if=/dev/zero of=/swap bs=1024 count=4048576

The swap file system can be created by using the mkswap command.

sudo mkswap /swap

Enable Swap File

The swap file can be enabled by using the swapon command. This command enables and sets the specified file as a swap file but after reboot, this configuration is lost.

sudo swapon /swap

The swap file configuration can be made permanent by configuring the /etc/fstab file for the swap. The following line makes /swap file as swap and uses permanently in every reboot.

/swap swap swap defaults 0 0

Disable Swap File

The swap file can be also easily removed or disabled if not required. The swapoff command can be used temporarily to remove the specified swap file.

sudo swapoff -v /swap

Alternatively, if the swap file is configured in /etc/fstab and we want to remove it permanently the swap file configuration line can be removed or commented like below.

# /swap swap swap defaults 0 0

Swap Performance

The swap file is secondary memory used to store volatile information. RAM provides high speeds, low latency to read, write and change the information in memory. But the swap file is a regular file where it is less performative than the RAM. So the swap file performance is very low according to the RAM. If you do have enough memory or less memory requirement prevent the usage of the swap file.

Leave a Comment