Running low on memory can cause applications to crash, the system to become unresponsive, and other issues. This is common on memory limited systems, especially on SBCs like the Raspberry Pi. Swapping to disk can be used to allow for some extra breathing room at the cost of performance.
You can check to see if you already have swapping enabled by running the following command in a root shell, or with
# swapon --show
To add a new swap file, first you must allocate a swap file. In this example, we allocate 1GB. See
man fallocate for more length suffixes. Recommendations for swap size differ wildly, but Red Hat has a fairly comprehensive table.
# fallocate -l 1G /swap
Later commands will complain if the file permissions are set incorrectly, so ensure that
600 is used (owner read and write).
# chmod 600 /swapfile
In order to be used, you must first initialize the file as a swap area.
# mkswap /swap
Now you can enable the new swap area.
# swapon /swap
Finally, to ensure the swap is mounted on startup, add the following line to
/swap none swap sw 0 0
Note that enabling or expanding the swap on an SD card, like in the case of a Raspberry Pi, can significantly decrease the lifespan of the card.