What Is a Swap Partition & How to Create One

September 14, 2023

Introduction

A swap partition is a feature in Linux that provides virtual memory space and multiple benefits. It allows the OS to handle memory demands efficiently. As a result, swap partitions improve system stability, responsiveness, and heavy workload processing.

This guide will explore swap partitions and their pros and cons and outline the steps for creating and managing one on your Linux system.

What is a swap partition and how to create one - a tutorial.

Prerequisites

  • A system running Linux.
  • An account with root privileges.
  • Free space on the hard drive.

What Is a Swap Partition?

A swap partition is a part of the hard drive that serves as swap memory, the overflow space for RAM. Using a swap partition aims to make the computer more capable of handling memory requests than with only RAM.

When RAM starts to fill up, the operating system moves less frequently used processes or data from RAM to the swap partition. The underlying mechanism is swapping or paging, which uses the swap partition as virtual memory. The mechanism extends the available memory when there isn't enough physical RAM to hold all the currently active data and programs.

Although using a swap partition sounds like an easy way to increase the amount of usable memory without upgrading the machine with more RAM, that isn't the case. There are some limitations and guidelines, which are explained below.

Benefits of Using a Swap Partition

A swap partition provides multiple benefits in Linux or other Unix-like operating systems. Some of the advantages of using a swap partition are:

  • Virtual Memory Expansion. Swap space serves as an extension to the physical memory (RAM). When the RAM is fully utilized, the OS temporarily stores less frequently accessed data in swap space. Doing so increases the system's virtual memory, allowing the users to run more applications simultaneously.
  • Improved System Stability. If a system runs out of physical RAM, it may become unstable and even crash. A swap partition prevents this by providing a safety net when the physical memory is overloaded.
  • Multitasking. A swap partition allows users to run more applications simultaneously without experiencing slowdowns or crashes caused by low memory conditions. This feature is particularly beneficial for servers and systems with heavy workloads.
  • Hibernation Support. Many OSes, including Linux and Windows, use the swap partition to store RAM's contents when the machine is in a hibernation state. Hibernation allows users to power off the machine and later resume their work where they left off.
  • No Out-of-Memory (OOM) Situations. If a process occupies excessive memory, having swap space can prevent an OOM situation. The OS swaps out less essential data to the swap partition to allow the critical system processes to continue running.
  • Emergency Recovery. A swap partition can be helpful in case of a kernel panic or crash. The swap partition captures a memory dump, which is valuable for diagnosing the cause of the crash and troubleshooting.
  • Compatibility. Swap partitions are supported by various operating systems, making them a reliable and widely used solution for memory management.

Disadvantages of Using a Swap Partition

Swap partitions offer numerous benefits but have disadvantages and considerations if they are overused. The potential drawbacks are:

  • Disk Space Usage. A swap partition takes up a portion of the disk space, which is inconvenient in systems with limited storage capacity.
  • Slower Performance. Performance degrades because reading and writing to disk is significantly slower than accessing data in RAM. Excessive swapping (thrashing) slows down system performance.
  • Disk Wear. Solid-state drives (SSDs) have limited write cycles for each memory cell. Frequent swapping increases wear on the SSDs, reducing their lifespan. Disk wear is less of a concern on traditional hard disk drives (HDDs).
  • Inefficient Resource Use. In some cases, swap partitions can mask issues related to having insufficient physical RAM. While the solution would be to add more RAM or optimize software, relying heavily on swap space can lead to performance degradation.
  • Complex Management. Managing a swap partition can be more complex than managing a swap file. The partition needs to be created and managed manually during system setup or expansion, which is less user-friendly than configuring a swap file.
  • Fragmentation. Over time, swap partitions become fragmented, which degrades system performance. Fragmentation occurs as data is written and deleted from the swap space.
  • Limited Flexibility. Changing the size of a swap partition may require resizing system partitions or even reconfiguring the entire storage setup, which can be time-consuming and risky.
  • Potential Security Risk. Sensitive data from running processes can end up in the swap space. If the swap space isn't properly encrypted, there's a security risk of unauthorized access to the disk.

To mitigate these disadvantages, adhere to the general guidelines for using swap partitions to minimize swapping and create a partition based on your specific system requirements and constraints.

How to Check/Find Your Swap Partition

There are several ways to check the Linux swap partition size and usage:

swapon Command

Use the swapon command to activate a swap partition or to show the details about an existing one. Follow the steps below:

1. Open the terminal (Ctrl + Alt + T).

2. Run the following command:

swapon --show
Checking swap partition usage using the swapon command.

The output shows the path to the swap space, the swap type (partition or file), the size, and the amount of currently used swap. The Priority column determines the order in which swap devices are used when swapping data in case multiple swap spaces exist.

In the example above, the swap partition still hasn't been configured, so there is only a swap file present on the disk.

Check /proc/swaps File

The /proc/swaps file contains swap space information and its utilization. View the file using the cat command. Run:

cat /proc/swaps
Checking swap partition usage in the /proc/swaps file.

The output is the same as the one of the swapon command.

free Command

The free command provides information about memory usage in the system, including virtual memory. Run the following command:

free -m
Checking swap partition usage using the free command.

The output shows RAM and swap space, including the size, used memory, free memory, etc.

top or htop Command

The top command shows an interactive, real-time view of the system's resources. The htop command is an alternative to top, with a more user-friendly interface. Use top or htop to see swap space utilization in Linux. Follow the steps below:

1. Run the following:

top

2. Press Shift+O to open the "Order By" prompt.

3. Type VIRT (virtual memory usage) and press Enter.

Checking swap partition using the top command.

The output shows processes by virtual memory usage, including both RAM and swap space.

How to Create a Swap Partition

Depending on your preference, create a new partition or use the free space from an existing partition for a swap file. To create a new partition, you can use any disk utility, such as fdisk, gdisk, or parted. In this tutorial, we will use fdisk.

Note: New partitions can be created only from disk space that hasn't been already partitioned. For this tutorial, we have added a new disk /dev/sdb/.

Follow the steps below:

1. Run the fdisk command for the disk you want to partition:

sudo fdisk [disk_path]
Opening fdisk for a disk that needs to be partitioned.

Replace [disk_path] with your disk identifier.

2. Type p and press Enter for an overview of the disk.

Getting a disk overview in fdisk.

The output provides information about the available disk space for a new partition. If the last partition ends before the last sector of the hard drive, there is enough space to create a new partition. The output above shows the entire disk space is available for creating a new partition.

3. Type n and press Enter to create a new partition. For partition type, enter p and press Enter.

Creating a new partition using fdisk.

4. Set the partition number (or keep the default number 1) and press Enter to confirm.

5. Enter the first available sector for the new partition and press Enter. You can also keep the default one offered.

6. Set the last available sector for the partition. You can specify the partition size in KiB, MiB, or GiB units. We will create a swap partition of 1GiB, so the command is:

+1G
Creating a partition in fdisk.

7. Press p to verify the partition creation and confirm with Enter.

Verifying partition creation in fdisk.

8. By default, the partition type is 83, while 82 is a partition type identifier for swap space.

Type t and press Enter to change the partition type. Change the value to 82 and press Enter.

Changing the partition type in Linux.

9. Verify the change with p and confirm with Enter.

10. fdisk doesn't make any changes to the disk before confirmation. To proceed with the changes, type w, and press Enter.

Writing the changes to disk using fdisk.

12. Update the partition table using the following syntax:

sudo partprobe [disk_path]

Replace [disk_path] with your disk name.

For example, for the disk /dev/sdb, run:

sudo partprobe /dev/sdb

13. Use the mkswap command to format the partition for swap space. The command writes a swap signature in the partition, leaving the rest unformatted. The unformatted space stores the memory pages.

Use the following syntax to format the partition and create a swap space:

sudo mkswap [disk_path]

For example:

Formatting the disk after creating a swap partition in Linux.

After formatting, the swap partition is created and ready to use.

How Large Should a Swap Partition Be?

The size of a swap partition in modern systems depends on several factors, such as the amount of physical RAM, workload size, hibernation support, hard drive type and speed, etc. In addition, different Linux distributions have specific recommendations for swap space size.

The following guidelines outline the recommendations for swap space for several Linux distros and offer swap size tips:

RedHat

RedHat distributions should have a swap partition size of 20% of the available RAM. The minimum amount of RAM is 4GB.

CentOS

CentOS provides the following guidelines:

  • The swap partition should be twice the amount of RAM if the total RAM amount is below 2GB.
  • If you have more than 2GB of RAM, then the swap partition should be the size of RAM + 2 GB. For example, use 8GB of swap for 6GB of RAM.

Ubuntu/Debian

Ubuntu has based its swap size recommendations on the use of hibernation.

  • If you use hibernation, the swap partition should be the same as the amount of RAM plus the square root of the RAM amount.

If you don't use hibernation:

  • For less than 1GB of RAM, the swap partition size should be at least the same as the amount of RAM and, at most, double the amount of RAM.
  • For more than 1GB of RAM, create a swap partition at least equal to the square root of the RAM amount and, at most, double the RAM amount.

How to Initialize/Enable a Swap Partition

Enable a swap partition using the Linux swapon command. This tutorial will show how to activate the partition and make the change persist. Follow the steps below:

1. Activate the Swap Partition

Use the swapon command to enable the swap partition temporarily:

sudo swapon [disk_path]

Replace [disk_path] with the path to your partition.

2. Check Swap Usage

Verify the swap partition is active by running the following command:

swapon --show
Checking swap usage in Linux.

The output should include the new swap partition.

3. Make Swap Persistent (Optional)

Include the partition in the /etc/fstab file to ensure the swap partition activates on boot. Open the file in a text editor (such as nano):

sudo nano /etc/fstab

Add the following line at the end:

/dev/sdb none swap sw 0 0

Replace /dev/sdb with the path to your swap partition.

How to Change the Size of a Swap Partition

You can change the size of a swap partition in Linux by extending or reducing it. The sections below outline the steps for each scenario.

How to Extend a Swap Partition

Extend a swap partition with tools like fdisk, gparted, or parted. For this tutorial, we will use fdisk, a CLI utility more complex than a graphical tool like gparted because it involves manual partition table editing.

Follow the steps below to extend a swap partition using fdisk:

Important: Be cautious when using fdisk, as incorrect actions can lead to data loss. Make sure to back up important data before proceeding.

1. Check Existing Swap

Before resizing the swap partition, check the current swap size and usage:

swapon --show

2. Disable Swap

To safely resize the swap partition, first disable it by running:

sudo swapoff -a

3. Open fdisk for the Correct Disk

Run fdisk for the disk containing the swap partition you want to resize. The syntax is:

sudo fdisk [disk_path]

Replace [disk_path] with the correct device path (e.g., /dev/sdb).

Using fdisk to partition a disk in Linux.

4. List Partitions

In fdisk, type p to print the current partition table. The output displays a list of partitions on the disk.

Listing the existing disk partitions in Linux.

5. Delete Swap Partition

Identify the swap partition in the list and note its starting sector. To delete the swap partition, type d, and press Enter. The swap partition entry disappears from the partition table.

6. Create a New Swap Partition

Type n to create a new partition. Follow the prompts:

  • Partition type: Select the default value (primary).
  • Partition number: Use the same number as the deleted swap partition.
  • First sector: Specify the start sector. Ensure that you specify the same starting sector as the original swap partition.
  • Last sector: Specify the new size for the swap partition. You can use +<size> to indicate the size in sectors (e.g., +2G for 2 gigabytes).

7. Write Changes to Disk

Type w to write the changes to the partition table and exit fdisk. The action recreates the swap partition with the new size.

8. Format New Partition

After resizing the partition, format it using the mkswap command. Use the following syntax:

sudo mkswap [disk_path]

Replace [disk_path] with your new swap partition.

Formatting a new partition in Linux after resizing.

9. Enable Swap

Re-enable the swap partition by running:

sudo swapon -a

10. Update /etc/fstab

To make the changes permanent, update the /etc/fstab file using a text editor to reflect the new swap partition. Replace the old swap partition entry with the new one.

11. Reboot

Reboot the system to ensure that the changes take effect. Run:

sudo reboot

How to Reduce a Swap Partition

Reducing a swap partition is similar to extending it, with the only different step being Step 6, where instead of extending the swap partition, a smaller size is specified to shrink it.

Remember that resizing partitions carries some risk, which may lead to data loss if done incorrectly. Back up your data and double-check the commands before running them.

How to Disable and Remove a Swap Partition

To disable and then remove a swap partition using fdisk, follow the steps below:

Warning: Exercise caution when removing a swap partition, as it may affect system stability. Make sure you have a backup of any important data.

1. Check Current Swap Usage

Before removing a swap partition, check the current swap usage and available swap devices:

swapon --show

2. Disable Swap

Use the swapoff command to disable the swap partition. The syntax is:

sudo swapoff [disk_path]

Replace [disk_path] with the path to the swap partition you want to disable.

3. Remove Swap Entry (Optional)

If you want to delete the swap partition, the next step is to remove the entry from the /etc/fstab file. Open /etc/fstab with a text editor (such as nano):

sudo nano /etc/fstab

Delete the line corresponding to the swap partition

4. Open fdisk for the Appropriate Disk

Run fdisk for the disk containing the swap partition you want to remove. The syntax is:

sudo fdisk [disk_path]

Replace [disk_path] with the correct device identifier (e.g., /dev/sdb).

5. List Partitions

Type p to show the current partition table with a list of partitions on the disk. Identify the swap partition in the list (it should be "Linux swap" type code 82).

Note the partition identifier (e.g., /dev/sdb) and ensure you have selected the correct swap partition to delete.

6. Delete the Swap Partition Entry

Type d followed by the partition number (e.g., dN, where N is the partition number of the swap partition).

Deleting a partition in Linux.

This will delete the swap partition entry from the partition table.

7. Write Changes to Disk

Type w to write the changes to the partition table and exit fdisk. This step permanently deletes the swap partition.

8. Update Partition Information

After deleting the swap partition entry, update the partition information for the disk. Run the following command to refresh the information:

sudo partprobe

9. Reboot

It's a good practice to reboot the system to ensure that all changes take effect and there are no lingering references to the removed swap partition. Run:

sudo reboot

By following these steps, you have successfully disabled and then removed the swap partition from your Linux system using fdisk.

Conclusion

This tutorial has explained the concept of a swap partition, how it is used, and its pros and cons. After following the steps, you know how to create, resize, and remove a swap partition.

A swap partition is an essential feature of every Linux system, providing multiple benefits and improving overall system performance if used correctly.

Next, learn about swappiness, what it is, how it works, and how to manage it.

Was this article helpful?
YesNo
Bosko Marijan
Having worked as an educator and content writer, combined with his lifelong passion for all things high-tech, Bosko strives to simplify intricate concepts and make them user-friendly. That has led him to technical writing at PhoenixNAP, where he continues his mission of spreading knowledge.
Next you should read
Intel Optane Memory vs SSDs vs RAM
December 24, 2019

It's challenging to assemble the best hardware configuration for your business. We analyzed the Intel Optane memory Module and found it has a stable future in enterprise and data center environments.
Read more
How to Set Docker Memory and CPU Usage Limit
December 6, 2023

Docker containers have access to full RAM and CPU resources, causing it to occupy all system resources. This step-by-step guide explains how to prevent that.
Read more
How to Check Memory Usage in Linux, 5 Simple Commands
March 28, 2024

Learn the five most commonly used commands to check memory usage in Linux. See explanations of what they do and more importantly, how to interpret the results.
Read more
In-Memory Database Explained
November 3, 2022

In-memory databases (or in-memory stores) primarily rely on memory data storage rather than HDD or SSD. Learn more about their use cases, advantages, and disadvantages, as well as when and how to implement them.
Read more