Course contentsShow
← Linux
Lesson 637 of 1,8197. Storage Management and Logical VolumesFree lesson

Managing swap partitions and files

Implement virtual memory storage strategies for different workloads.

In this lesson, you will learn how to extend your system’s effective memory capacity by implementing swap storage to handle workloads that exceed your physical RAM.

Understanding Virtual Memory

When your system runs out of physical RAM, it cannot simply stop working. Instead, Linux uses swap—a dedicated area on your disk that acts as "overflow" memory. If an application is idle or your RAM is saturated, the kernel moves inactive memory pages to this storage. While much slower than RAM, this prevents the system from crashing (or triggering the Out-of-Memory killer) when memory demands spike.

Swap Partitions vs. Swap Files

You can implement swap in two ways:

  1. Swap Partitions: A dedicated slice of your disk reserved specifically for swap. Because the kernel accesses this directly at the block level, it is very efficient, but it is rigid; resizing it often requires repartitioning your disk.
  2. Swap Files: A regular file within an existing filesystem (like ext4 or xfs) that acts as a swap area. These are incredibly flexible because you can create, resize, or delete them without altering your partition table.

Implementing a Swap File

For most modern systems, a swap file is the preferred strategy because of its flexibility. You can quickly set one up using these commands:

# Create a 2GB file filled with zeros
sudo fallocate -l 2G /swapfile

# Secure the file so only root can read/write it
sudo chmod 600 /swapfile

# Format the file for swap usage
sudo mkswap /swapfile

# Enable the file immediately
sudo swapon /swapfile

To ensure your system automatically uses this file after a reboot, you must add an entry to your /etc/fstab file: /swapfile none swap defaults 0 0

Tuning for Workloads

You don’t want your system to swap too aggressively if you have plenty of RAM, as disk I/O is expensive. You can control this behavior via the swappiness kernel parameter (ranging from 0 to 100). A low value (e.g., 10) tells the kernel to avoid swapping unless absolutely necessary, which is ideal for desktop responsiveness, while a higher value is better for server workloads that prioritize memory availability for caches.

Key Takeaway: Swap acts as an essential safety net for your physical RAM, and while partitions offer raw performance, swap files provide the flexibility needed for dynamic storage management.