This article explains how to configure and manage swap space in Linux, covering both swap partitions and swap files with practical examples.
In this article, we explain how to configure and manage swap space in Linux. Swap space is a dedicated area on your disk that Linux uses to temporarily offload data from RAM when physical memory is low. This guide covers both swap partitions and swap files, providing the necessary commands and practical examples to help you manage them effectively.
Imagine a computer with 4 GB of RAM. You open a video editor that uses 2 GB of RAM and an audio editor that uses the remaining 2 GB. With no free memory left, you may wonder how you can still run additional applications like Chrome. This is where swap space becomes essential:
Linux monitors memory usage and identifies inactive applications (e.g., a video editor that hasn’t been used for a while).
It moves data from RAM to a designated swap area, for example, a 2 GB swap partition. This process frees up RAM, allowing new applications like Chrome to run.
The scenario above is a simplified illustration that demonstrates why and how swap space is used in Linux systems.
Before using a swap partition, check if your system is already using swap areas:
Copy
Ask AI
$ swapon --show
Since swap is not activated initially, this command may not return any output. Next, review the available partitions. For example, assume that a swap partition on /dev/vdb3 was created earlier. The following command displays your system’s block devices:
This partition is currently empty. Before Linux can utilize it as swap space, you need to initialize it—similar to formatting a USB stick with FAT32 or NTFS, where a small header is written to define the file system type.Initialize the partition as swap with:
Copy
Ask AI
$ sudo mkswap /dev/vdb3Setting up swapspace version 1, size = 2 GiB (2146410496 bytes)no label, UUID=a39c80a1-a0c6-4ba2-a4a3-8a2058d8859
$ swapon --showNAME TYPE SIZE USED PRIO/dev/vdb3 partition 2G 0B -2
The swap configuration made above is temporary. After a reboot, the swap partition will not activate automatically unless it is added to the system’s fstab file.
Linux also supports swap files, which can be an alternative to swap partitions. Many modern Ubuntu systems, for instance, use a swap file by default. Follow these steps to create and use a swap file:
Create a Swap File:
Use the dd command to create a file filled with binary zeros. The following command creates a 128 MB swap file:
Copy
Ask AI
$ sudo dd if=/dev/zero of=/swap bs=1M count=128
Increase the Swap File Size:
To create a larger swap file (e.g., 2 GB), run:
By following these steps, you can effectively configure and manage both swap partitions and swap files on your Linux system. These methods help ensure that your system can handle low-memory situations efficiently, enhancing overall performance.For additional information, check out these resources: