Although we have already come to a time when high-volume memory is not an issue, for some old Linux machines or entry level virtual private servers, memory is still a kind of critical resource in face of memory-hungry jobs. In this article, the author is going to show an easy way to add swap space, and thus mitigate the risk of out-of-memory error, for Linux machines.

First, we need to check how much swap space we have now.

$ free -ght
            total        used        free      shared  buff/cache   available
Mem:        892Mi       494Mi        94Mi        37Mi       303Mi       213Mi
Swap:          0B          0B          0B
Total:      892Mi       494Mi        94Mi

If you would like to display buffered and cached memory separately, add w option. From the output of free command, we can notice that there is no swap space and the system is running low on memory. We only have 94MiB which is completely unused, though we still have 213MiB for new processes in total. You can also use swapon command to get a list of all swap areas.

$ swapon --show

If there is no swap space on the system, nothing will be printed. Then, we will pre-allocate 1GiB of space by creating a swap file on the disk and set its permission to 600.

$ sudo fallocate -l 1G /swapfile
$ sudo chmod 600 /swapfile
$ ls -l /swapfile
-rw------- 1 root root 1073741824 Jan 17 02:49 /swapfile

Then, we will format the file as a swap area. Note: if you did not set the correct permission in the previous step, mkswap will complain that 644 permission is insecure. Out of security, it's recommended to set the swap file to the correct permission.

$ sudo mkswap /swapfile
Setting up swapspace version 1, size = 1024 MiB (1073737728 bytes)
no label, UUID=<your_uuid>

The last step is to enable the swap file. At this point, you should be able to find it by free or swapon --show command.

$ sudo swapon /swapfile
$ swapon --show
NAME      TYPE  SIZE USED PRIO
/swapfile file 1024M   0B   -2
$ free -ght
            total        used        free      shared  buff/cache   available
Mem:        892Mi       498Mi        74Mi        37Mi       318Mi       208Mi
Swap:       1.0Gi          0B       1.0Gi
Total:      1.9Gi       498Mi       1.1Gi

There is yet another optional step to do: adding the swap area into the file system table (/etc/fstab) to make it permanent. Records listed in the table will be automatically mounted during boot time.

$ echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab
/swapfile none swap sw 0 0

This is everything you need to know to add a swap space to Linux machine. In the next article, the author will show how to safely remove a swap space from the system.