How to create a swap file on Ubuntu
Swap is particularly useful in situations where physical memory is limited, especially when dealing with low memory VPS/systems. This does not mean that swap is useless in all the other situations. Any system with close to 100% RAM utilization without swap enabled will cause application crashes or even worse, a system crash.
Moreover, some applications, in rare cases, require swap to be enabled regardless of memory capacity/usage, otherwise they simply crash.
To enable swap on Ubuntu follow the steps below (requires administration rights):
Create an empty file called “swapfile” using fallocate:
fallocate -l 2G /swapfile
Feel free to change the “2G” value if you believe you require more or less swap space.
Change the permissions of the swap file to 600 in order to make it accessible only for the root user:
chmod 600 /swapfile
Mark the “swapfile” as swap space:
Enable the swap file:
Note: It is extremely important to note that any changes we have made so far are temporary and will be removed when we reboot the machine.
In order to make our changes permanent we will need to update the fstab file located at /etc/fstab. You can do so by editing the file and adding the following line inside:
/swapfile none swap sw 0 0
Or simply by using this command do insert the line for you in the file:
echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab
We put together a one line command using the instructions above. It comes in handy when deploying new machines and we want to speed up the process. Feel free to use and modify it to suit your needs.
fallocate -l 2G /swapfile && chmod 600 /swapfile && mkswap /swapfile && swapon /swapfile && echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab