Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 57

Managing Swap Space

Recommended resources

Hello! Let's dive into the next lesson in our "Storage and Filesystem Management" module.

In our previous session, we focused on mounting filesystems and making them permanent using /etc/fstab. You learned how to attach a storage device to your directory tree and why using UUIDs is crucial for a stable system. Today, we'll build on those concepts by looking at a special kind of storage that isn't for your files, but for your system's memory: swap space.

This lesson directly addresses the learning outcome: Create, activate, and manage swap space. We'll cover:

  • What swap space is and its role as virtual memory.
  • The two types of swap: partitions and files.
  • How to create, activate, and manage both swap partitions and swap files.
  • How to make your swap space persistent across reboots using /etc/fstab.
  • How to tune your system's swapping behavior.

Understanding swap is essential for ensuring system stability, especially on machines with limited physical memory (RAM).

1. What is Swap Space?

At its core, swap space is an area on a storage device (like a hard drive or SSD) that the Linux kernel uses as an extension of your computer's physical RAM. When your RAM starts to fill up, the kernel can move inactive data "pages" from RAM to the swap space. This frees up RAM for active applications, preventing the system from crashing due to a lack of memory. The total memory available to your system—physical RAM plus swap space—is often called virtual memory.

RAM and Swap Memory Interaction
This diagram shows the fundamental concept of swap. When physical RAM is full, the operating system moves unused data to the swap space on the hard disk. When that data is needed again, it's moved back into RAM.

There are two primary reasons to have swap space:

  1. To handle memory overflow: It acts as a safety net when your applications demand more memory than you have physically available.
  2. To enable hibernation: During hibernation (or suspend-to-disk), the entire contents of your RAM are written to the swap space, allowing the computer to be completely powered off and later restored to its exact previous state. For hibernation to work, your swap space must be at least as large as your physical RAM.

Let's begin with a short article that provides a solid theoretical foundation.

Swap Space in Linux: What It Is & How It Works - Low-Level Lore

The article 'Swap Space in Linux: What It Is & How It Works' from Low-Level Lore provides an excellent overview of the fundamentals.

Please read the first three sections of the article: 'Understanding Swap Space Fundamentals,' 'Memory Management and Swap Interaction,' and 'Types of Swap Space Implementation.' Focus on the distinction between swap partitions and swap files and their respective pros and cons.

As the article explained, there are two ways to implement swap:

  • Swap Partition: A dedicated disk partition used only for swapping. This generally offers the best performance because there's no filesystem layer in between. However, it's inflexible; changing its size usually requires repartitioning your drive.
  • Swap File: A regular file that resides within an existing filesystem (like ext4). This is highly flexible, as you can create, resize, and remove swap files easily without altering disk partitions. The performance difference is minimal on modern systems, especially with SSDs.

2. Checking and Managing Current Swap

Before creating new swap space, you should check what's already active. You can do this with several commands. The most direct is swapon.

# Show active swap spaces
swapon --show

If this command produces no output, you have no active swap.

Another useful command is free, which shows memory and swap usage. The -h flag makes the output human-readable.

free -h
              total        used        free      shared  buff/cache   available
Mem:          3.8Gi       1.2Gi       1.5Gi       3.0Mi       1.1Gi       2.4Gi
Swap:         2.0Gi          0B       2.0Gi

Here, you can see this system has a 2.0Gi swap space.

To deactivate all swap spaces, you use the swapoff command. You'll need sudo privileges. This is often a necessary first step before modifying swap partitions or files.

# Deactivate all swap spaces
sudo swapoff -a

3. Method 1: Creating a Swap Partition

Creating a swap partition is the traditional method. This process will be familiar, as it uses the partitioning tools we've discussed before.

The workflow is:

  1. Create a new partition using a tool like fdisk.
  2. Set the partition's type to "Linux swap".
  3. Format the partition with mkswap.
  4. Activate it with swapon.
  5. Add an entry to /etc/fstab to make it permanent.

The following video demonstrates this entire process clearly.

GNU/Linux Create Partitions And Swap Partitions and Files

This clip from the video 'GNU/Linux Create Partitions And Swap Partitions and Files' by Frank the Programmer walks through creating and activating a swap partition.

Please watch from 17:36 to 22:46. Pay close attention to these steps: Using fdisk to create a new partition and setting its type to 82 (Linux swap). Using mkswap to prepare the partition. Using swapon to activate it and free -m to verify. Editing /etc/fstab to ensure the swap partition is activated on boot.

Swap Partition Workflow Summary:

  1. Partition the disk:

    sudo fdisk /dev/sdb # (replace /dev/sdb with your disk)
    

    Inside fdisk, use n to create a new partition, then t to change its type to 82. Finally, use w to write the changes.

  2. Format as swap: After creating the partition (e.g., /dev/sdb2), format it using mkswap.

    sudo mkswap /dev/sdb2
    
  3. Activate the swap:

    sudo swapon /dev/sdb2
    
  4. Make it persistent: Just as with filesystems in our last lesson, use the UUID for reliability. First, find the UUID.

    sudo blkid /dev/sdb2
    # Output might look like:
    # /dev/sdb2: UUID="c1b2a3d4-..." TYPE="swap" ...
    

    Then, add it to /etc/fstab.

    # Open the file
    sudo nano /etc/fstab
    
    # Add this line at the end, using your UUID
    UUID=c1b2a3d4-...    none    swap    sw    0    0
    

    The fields mean: UUID, mount point (none for swap), type (swap), options (sw is a common alias for defaults), and dump/pass (both 0).


4. Method 2: Creating a Swap File

Using a swap file is more flexible and is the default on many modern distributions like Ubuntu.

The workflow is:

  1. Create a file of a specific size using fallocate.
  2. Set secure permissions so only the root user can access it.
  3. Format the file with mkswap.
  4. Activate it with swapon.
  5. Add an entry to /etc/fstab.

This next video demonstrates this modern approach.

Linux Swap | Different Kinds and How to Use It

In 'Linux Swap | Different Kinds and How to Use It,' Chris Titus Tech shows how to create and manage a swap file.

Please watch from 05:11 to 08:31. Focus on these commands and concepts: Using fallocate to create a file for the swap space. Setting permissions with chmod 600. This is a crucial security step. The mkswap and swapon commands applied to a file instead of a partition. Important: Note the warning about using swap files on a Btrfs filesystem. This is a key real-world consideration.

Swap File Workflow Summary:

  1. Allocate the file: Use fallocate to instantly create a file of a given size. Let's create a 4GB swap file in the root directory.

    sudo fallocate -l 4G /swapfile
    

    An older alternative you might see is the dd command, as shown in the video by Frank the Programmer (23:58-27:20), but fallocate is much faster.

  2. Set permissions: This is critical. The swap file might contain sensitive data from memory, so it should only be readable by the root user.

    sudo chmod 600 /swapfile
    
  3. Format as swap:

    sudo mkswap /swapfile
    
  4. Activate the swap:

    sudo swapon /swapfile
    
  5. Make it persistent: Open /etc/fstab and add a line pointing to the file.

    # Open the file
    sudo nano /etc/fstab
    
    # Add this line at the end
    /swapfile    none    swap    sw    0    0
    
Test your understanding!

You have created a new partition at /dev/sda3 and a new file at /data/myswap. You've run mkswap on both. What two lines would you add to /etc/fstab to make both of them active as swap space on boot? (You can use a placeholder for the UUID).

Show answer
# For the partition (using its UUID)
UUID=your-uuid-for-sda3    none    swap    sw    0    0

# For the file (using its path)
/data/myswap             none    swap    sw    0    0

5. Managing Swap Behavior: Swappiness

Just having swap space isn't the end of the story. You can also tell the kernel how aggressively it should use swap. This is controlled by a parameter called vm.swappiness.

  • swappiness is a value from 0 to 100.
  • A low value (e.g., 10) tells the kernel to avoid swapping as much as possible and keep things in RAM. This is good for desktops or systems with plenty of RAM, where you want maximum performance.
  • A high value (e.g., 60) tells the kernel to swap more aggressively. This can be useful on servers with heavy memory usage or systems with very little RAM.
  • A value of 0 doesn't disable swap entirely, but tells the kernel to only use it to avoid an out-of-memory error.

You can check your current swappiness value with:

cat /proc/sys/vm/swappiness

To change it persistently, you edit the /etc/sysctl.conf file (or add a file in /etc/sysctl.d/).

# Open the configuration file
sudo nano /etc/sysctl.conf

# Add or modify this line at the end to set swappiness to 10
vm.swappiness=10

The change will be applied at the next reboot. To apply it immediately, run sudo sysctl -p.


Conclusion

You have now learned how to provision, enable, and manage one of the core components of a Linux system's memory management subsystem. This is a critical skill for building and maintaining stable servers and desktops.

Key Takeaways:

  • Swap space acts as virtual memory, extending your system's RAM onto a disk.
  • You can implement swap as a partition (fast but rigid) or a file (flexible and modern).
  • The core workflow is to create the space (with fdisk or fallocate), format it (mkswap), and activate it (swapon).
  • Persistent swap is configured in /etc/fstab, using a UUID for partitions and a file path for swap files.
  • The swappiness kernel parameter lets you control how aggressively your system uses swap space, allowing you to tune performance based on your hardware and workload.

Preview of the Next Lesson:

We will continue our journey into advanced storage by looking at RAID (Redundant Array of Independent Disks). In the next lesson, you'll learn how to use the mdadm utility to combine multiple physical disks into a single logical device to improve performance, provide data redundancy, or both.