How to increase swap space in Linux

I recently had to run a RAM intensive task on a system with limited RAM. To make the task run successfully, I created a swap file large enough to hold the application’s data. In this post, I’ll show you how to increase the swap space on your computer.

Swap memory or swap space is an extension of the computer’s RAM created on the hard drive. It is useful in preventing crashes in running programs when the available system RAM is exhausted. It isn’t a substitute for real RAM but having it helps give your programs a little more wiggle room. To add more swap space, do the following:

Create a swap file


sudo dd if=/dev/zero of=/swapfile_extend_60GB bs=1GB count=60

if=/dev/zero is the input file. /dev/zero is a special input file that returns as many null characters as a read operation requests. This is useful for creating a contiguous file without any holes in it, which is exactly what we need to do for swap memory.

Next, we specify of=/swapfile_extend_60 which is the output file. bs is the block size. Here we create 60 blocks of 1GB each, making a 60GB file.

Set Permissions

We need to set permissions to only allow root to interact with this file:

sudo chmod 600 /swapfile_extend_60GB

Set Up Swap area

Next, initialise the file you just created as a swap file by running mkswap on it:

sudo mkswap /swapfile_extend_60GB

Enable The Swap File

Activate and make the swap file available to the system by running:

sudo swapon /swapfile_extend_60GB

Verify Swap Creation

# Verify the swap was created
free -h
# OR
sudo swapon --show

Make The Change Permanent

To make the change permanent, add an entry in /etc/fstab. The /etc/fstab file is a system configuration file that defines how disks and files should be mounted:

sudo nano /etc/fstab

# Add the following line
/swapfile_extend_60GB none swap sw 0 0

Save the file and close it.

Disable The Swap File

To disable the swap file run swapoff on it and delete it to recover disk space:


sudo swapoff /swapfile_extend_60G

sudo rm /swapfile_extend_60G

Conclusion

You’ve seen how to create and enable a swap file in a Linux operating system.