Developer Notes

Creating a swap file in a Linux system

It is normally recommended to have swap space, especially for systems that have a tendency to run out of RAM.

What is swap space?

Swap space is virtual memory that is stored in the hard disk. It is basically an extension of RAM, but unlike RAM where data is stored in a physical RAM module, swap data is stored in the hard disk in either a swap file or a swap partition.

Reading and writing to disk is considerably slower than reading and writing to RAM, so heavily using swap can lead to performance issues. However, this is often still a better alternative to having the Linux system kill processes when it runs out of virtual memory, and more affordable than a RAM upgrade.

Adding swap space

Adding swap space to a Linux system can be done in a few simple steps.

Create a swap file. The swap file needs to be pre-allocated to the capacity of the swap space. To allocate 2 GB of hard disk space, you can run:

sudo fallocate -l 2G /swapfile

Secure the file. Make sure that the file is readable and writable only to the root user:

sudo chmod 600 /swapfile

Set up the file as a swap area. This needs to be done before enabling the file as swap space.

sudo mkswap /swapfile

Enable the swap file to be used as swap space.

sudo swapon /swapfile

Configure the system to use the swap file even after a reboot. The swapon command only enables the swap file temporarily, and this change would not persist after a system reboot.

To always enable to the swap file automatically after system boot, edit /etc/fstab and add the following line:

/swapfile swap swap defaults 0 0

Checking swap space status

You can check the status of swap areas in the Linux system with swapon:

$ sudo swapon --show
NAME TYPE SIZE USED PRIO
/swapfile file 2G 81.3M -2

That’s it! You can start enjoying a more stable Linux system.

Leave a Reply

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

Related Articles

Want your website to turn up in Google Search results? You can submit your website for indexing in Google Search
Occasionally, we need to bring our website visitors to a maintenance page. Don't worry, you can spin up a Maintenance
When you are deploying changes to a WordPress website, you might encounter an error about PHP's upload_max_filesize. Here is one
After installing Android Studio in Ubuntu, you might experience getting a blank screen instead of the Android Studio Setup Wizard.
It might surprise you how much storage space Snap packages use. You will most likely find that your Snap packages
The Loop Grid widget allows you to set the total number of items to load and display in the Loop

Recent Articles

Topics

Related Topics