The cart is empty

Proper memory management in Linux distributions like Ubuntu and Debian is crucial for system performance. SWAP is a special area on the disk that acts as an extension of physical RAM. If the RAM becomes full, the system can temporarily move data to SWAP, preventing crashes. This article describes how to add or extend SWAP space in Ubuntu and Debian.

What is SWAP and Why Add It?

SWAP is a portion of the disk that acts as virtual memory when physical RAM is exhausted. If the system runs out of RAM, it uses SWAP to store less frequently accessed data. Adding SWAP is especially useful on systems with limited memory, such as older computers or servers running resource-intensive applications.

Steps to Add or Extend SWAP in Ubuntu/Debian

1. Check the Current SWAP Status

The first step is to check if there is existing SWAP space and its current size. This can be done using the following command:

sudo swapon --show

If no output is shown, the system is not currently using any SWAP.

2. Create a New SWAP File

You can add SWAP by creating a special file on the disk that will act as virtual memory. To create a 2GB SWAP file, use the following command:

sudo fallocate -l 2G /swapfile

If the fallocate command is not available, you can use:

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

3. Set Proper Permissions

The SWAP file should be protected from unauthorized access. Set the correct permissions using this command:

sudo chmod 600 /swapfile

4. Activate the SWAP File

Now, convert the newly created file into SWAP space and activate it:

sudo mkswap /swapfile

Then activate it:

sudo swapon /swapfile

5. Add SWAP to fstab for Automatic Mounting

To ensure that SWAP is activated after each reboot, you need to add an entry to the /etc/fstab file. Open the file in a text editor:

sudo nano /etc/fstab

Add the following line at the end of the file:

/swapfile none swap sw 0 0

6. Verify SWAP and Its Functionality

After adding the SWAP, check its functionality with this command:

sudo swapon --show

You can also use the free -h command to see an overview of memory usage, including SWAP space.

Optimizing SWAP: Setting Swappiness

The swappiness value determines how often the system will use SWAP instead of physical RAM. The default value is 60, meaning the system starts using SWAP when about 40% of physical memory remains. To reduce SWAP usage, you can set a lower value, such as 10:

sudo sysctl vm.swappiness=10

To make this change permanent, add the following line to the /etc/sysctl.conf file:

vm.swappiness=10

Conclusion

Adding or extending SWAP space in Ubuntu/Debian is a straightforward and effective way to improve system stability and performance, especially on systems with limited memory. SWAP allows the system to handle more data without crashing or slowing down. It’s important to configure the swappiness value properly to ensure efficient SWAP usage.