Configuring Swap Files on Ubuntu

A swap file provides virtual memory when physical RAM runs low. This guide covers the differences between swap partitions and swap files, performance considerations, and the complete setup process for Ubuntu 24.04 but should be fine with any modern debian based distribution.

Swap File vs Swap Partition

A swap partition is a dedicated disk partition used exclusively for swap space. It is created during installation and cannot be easily resized without repartitioning tools. A swap file is a regular file in an existing filesystem that serves the same function as a swap partition.

Swap files offer greater flexibility. They can be created, resized, or removed without modifying partition tables. Multiple swap files can coexist on the same system. Performance differences between swap files and swap partitions on modern filesystems are negligible for most workloads.

Swap partitions may provide minor performance benefits on systems with fragmented filesystems or mechanical hard drives, but these advantages rarely justify the inflexibility. For most self-hosted and homelab configurations, swap files are the preferred option.

Performance Considerations

Swap space operates significantly slower than RAM. The system should rely on swap only when physical memory is exhausted. Excessive swapping indicates insufficient RAM for the workload.

The swappiness parameter controls how aggressively the kernel moves processes to swap. The default value of 60 encourages preemptive swapping to keep RAM available for cache. For systems with adequate RAM, reducing swappiness to 10 or 20 keeps applications in memory longer and uses swap primarily as emergency overflow.

On solid state drives, excessive swap usage contributes to write wear. Systems that consistently swap should receive additional RAM rather than relying on swap as a permanent solution. Swap files on NVMe drives perform better than those on SATA SSDs or mechanical drives.

The size of swap space depends on use case. For systems that hibernate, swap must equal or exceed total RAM. For servers that will never hibernate, 2-4 GB often suffices as emergency space. Older guidance recommending swap at 1.5x or 2x RAM size applies primarily to systems with very limited physical memory.

Checking Existing Swap Configuration

Before creating a swap file, verify whether swap space already exists. Display active swap devices:

swapon --show

If the command returns no output, no swap is currently active. If swap exists, the output displays the device name, type, size, and usage.

Memory and swap usage can be checked with:

free -h

The output shows total, used, and available memory along with swap statistics. The -h flag presents values in human-readable format.

Creating a Swap File on Ubuntu

This procedure creates a 2 GB swap file. Adjust the size parameter based on system requirements.

Allocate space for the swap file using fallocate:

sudo fallocate -l 2G /swapfile

Some filesystems do not support fallocate for swap files. If the command fails or if swap activation later produces errors, use dd instead:

sudo dd if=/dev/zero of=/swapfile bs=1M count=2048 status=progress

Set restrictive permissions on the swap file. Swap files must only be accessible by root:

sudo chmod 600 /swapfile

Verify the permissions:

ls -lh /swapfile

The output should show -rw——- with root ownership.

Format the file as swap space:

sudo mkswap /swapfile

The command creates the swap signature and displays the allocated size.

Activate the swap file:

sudo swapon /swapfile

Verify the swap file is active:

swapon --show

The output should now include /swapfile with the configured size.

Check system memory again:

free -h

The swap line should reflect the newly added capacity.

Making Swap Persistent Across Reboots

The swap file must be added to /etc/fstab to activate automatically on boot. Create a backup of the current fstab:

sudo cp /etc/fstab /etc/fstab.bak

Add the swap file entry to fstab:

echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab

Verify the entry was added correctly:

cat /etc/fstab

The last line should contain the swap file configuration.

Adjusting Swappiness

Check the current swappiness value:

cat /proc/sys/vm/swappiness

The default is typically 60. For a system with adequate RAM where swap serves primarily as emergency space, set swappiness to 10:

sudo sysctl vm.swappiness=10

This change takes effect immediately but will not persist across reboots. To make the setting permanent, add it to sysctl configuration:

echo 'vm.swappiness=10' | sudo tee -a /etc/sysctl.conf

Reload sysctl configuration:

sudo sysctl -p

Adjusting Cache Pressure

The vfs_cache_pressure parameter controls how aggressively the kernel reclaims inode and dentry cache memory. The default value of 100 represents balanced behavior. Reducing this value tells the kernel to retain cache longer.

For systems with sufficient RAM, a value of 50 can improve performance:

sudo sysctl vm.vfs_cache_pressure=50

Make the setting permanent:

echo 'vm.vfs_cache_pressure=50' | sudo tee -a /etc/sysctl.conf

Validating Swap Configuration

Test that the swap file survives a reboot. Restart the system:

sudo reboot

After the system comes back online, verify swap is active:

swapon --show

Confirm swappiness and cache pressure settings:

cat /proc/sys/vm/swappiness
cat /proc/sys/vm/vfs_cache_pressure

Both values should match the configured settings.

Removing or Resizing Swap Files

To remove a swap file, first deactivate it:

sudo swapoff /swapfile

Remove the entry from /etc/fstab by editing the file and deleting the swap line. Then delete the swap file:

sudo rm /swapfile

To resize a swap file, deactivate it, remove it, and create a new swap file with the desired size following the creation steps in this guide.

Monitoring Swap Usage

Regular monitoring helps identify whether swap is being used appropriately. The free command provides a quick snapshot. For continuous monitoring, use:

watch -n 5 free -h

This updates the display every five seconds. Exit with Ctrl+C.

For detailed swap usage by process, use:

sudo grep VmSwap /proc/*/status | grep -v '0 kB'

This displays processes currently using swap space.

If swap usage remains consistently high, the system needs more physical RAM. Swap exists as a safety mechanism and temporary overflow space, not as a substitute for adequate memory.

Ubuntu 24.04 Compatibility Notes

Ubuntu 24.04 uses the same swap configuration mechanisms as previous LTS releases. The procedures in this guide apply to Ubuntu 22.04 and 20.04 with no modifications. Ubuntu Server installations often include no swap by default, making manual configuration necessary.

Systems using Btrfs require additional considerations. Swap files on Btrfs must have copy-on-write disabled and cannot span multiple devices. Create the swap file, then disable COW before formatting:

sudo chattr +C /swapfile

This command must be run on an empty file before mkswap.

ZFS does not support swap files stored on ZFS datasets. For ZFS root systems, create swap on a separate non-ZFS partition or use a zvol configured as swap space.

AI assistance is used on this site for language, formatting, and turning research into a consistent template. It is not used to perform the underlying research or verify technical claims. Every command, configuration, and step in this post is tested by hand before publication.

Leave a Reply

Your email address will not be published. Required fields are marked *

2 × five =