What is Swap?
One way to increase the responsiveness of a server and prevent out of memory errors is to add swap space. Swap space designates an area of your hard drive where your operating system can temporarily store data that it can no longer hold in RAM.
Effectively, this gives you the ability to increase the amount of information that your server can keep in its working “memory”. A caveat of swap space is the information written to disk will be slower than information kept in RAM.
Swap space isn’t a long-term solution for a server that regularly lacks enough memory for the work you’re asking it to do, but it can be a good backup in edge-cases when your system’s RAM is depleted.
Use case
As an example, I often use low-memory budget servers from DigitalOcean in courses I teach. On these servers I have students use VSCode’s remote development tools to work on code directly on the server. Generally speaking, our demands on these servers are low - but occasionally VSCode’s remote dev tools can cause a memory spike that - without swap in place - would cause the server to lock up. Enabling swap fixes this issue.
For more on Remote Development with VSCode, check out this guide...
Configure swap
To configure a swap file, run through the following commands.
First, create the swap file:
> sudo fallocate -l 4G /swapfile
Next, adjust permissions on the resulting swap file so it isn’t readable by anyone besides root:
> sudo chmod 600 /swapfile
Next, tell the system to set up the swap space:
> sudo mkswap /swapfile
Next, enable the swap space:
> sudo swapon /swapfile
Finally, we want to make it so the server always enables this swap space, even after a reboot. To do this run the following command which will add the swap file to your file systems table (fstab) config file:
> sudo echo '/swapfile none swap sw 0 0' >> /etc/fstab
Confirm it worked: You can confirm your swap file with the following command:
> sudo swapon -s
Expected output:
Filename Type Size Used Priority
/swapfile file 4194300 0 -2