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.