Skip to content

Steps to Add Swap in Ubuntu 24.04

What is Swap Space

Swap space in Linux is the disk space allocated for use when the system has low RAM. When RAM fills up, inactive data is moved to this space on your disk, freeing up RAM for critical processes. It’s akin to using extra desk space when your primary workspace becomes cluttered.

Swap space assists your system in:

  • Performance: For systems with limited RAM, swap space can prevent the system from crashing under high load.
  • Flexibility: You can easily adjust the amount of virtual memory available without the need to physically add more RAM.

Prerequisites

  • A system operating on Ubuntu 20.04
  • Adequate disk space for the desired swap file size
  • Root or sudo privileges

Steps

Check the System for Existing Swap Space

sudo swapon --show

Creating a Swap File

Initially, decide on the required swap space size for your system. Generally, it’s recommended to have an amount equal to or double the size of your RAM, depending on your system’s usage and available disk space.

sudo fallocate -l 4G /swapfile
sudo chmod 600 /swapfile

Enabling the Swap File

sudo mkswap /swapfile
sudo swapon /swapfile
sudo swapon --show

Enabled Swap Memory when System starts

The swappiness parameter determines the frequency at which your system uses swap space. Adjusting it can help optimize your system’s performance in terms of RAM and swap usage.

sudo nano /etc/fstab
## add the following line
/swapfile none swap sw 0 0

Adjusting Swappiness

cat /proc/sys/vm/swappiness
sudo sysctl vm.swappiness=20

Reference

  • https://tecadmin.net/how-to-add-swap-in-ubuntu-24-04/
Feedback