Enable swap in Linux

Swap or the virtual memory paging mechanism in Linux is an important feature of the operating system. It is crucial for the proper operation of the system, although sometimes it leads to performance decrease. Swapping typically occurs when the physical memory (RAM) of a machine is not enough for all the running processes. When that happens, the operating system takes down some chunks of the RAM (pages) and temporarily writes them on the hard disk to free up some memory. Of course this where the performance cost comes, as the hard disk or even solid state drive is many time slower than the RAM. Besides it’s performance cost, swapping is still a very important process. It allows the operating system to continue it’s normal operation.

When a Linux machine has no swap enabled, it can perform sort of unstable. The most common situations are when a server load peaks and various server processes take up all the available RAM. If there is no RAM available for further operations the Linux kernel is quite drastic. It will simply kill a random process in order to free up memory.

As usually such behavior is not an option for a server machine, swap is always recommended.

If you happen to have a running server, that has swap disabled, or swapping hasn’t been setup, here a the steps to enable it.

Create a swap file

To enable swapping we need either an allocated file on the storage or a seperate swap partition. Usually Linux systems come with an swap partition, but both options behave pretty much the same way and files are a bit easier to handle on an already partitioned space.

So to allocate a swap file:

sudo fallocate -l 4G /swap

This we allocate a 4GB file on root partition. The general rule for the size is anywhere between the amount of RAM memory and twice that number, so for a 4GB RAM, this file size is good.

The file needs some permissions to be set:

sudo chmod 600 /swap

and then the file has to be set up as a swap area:

sudo mkswap /swap

Enable swap

Once the swap file is ready, we can enable swap:

sudo swapon /swap

And make it permanent by adding the following line to the /etc/fstab:

/swap swap swap sw 0 0

That’s all.

Leave a Reply

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