Category Archives: Linux
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:
1 | 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:
1 | chmod 600 /swapfile |
Mark the “swapfile” as swap space:
1 | mkswap /swapfile |
Enable the swap file:
1 | swapon /swapfile |
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:
1 | /swapfile none swap sw 0 0 |
Or simply by using this command do insert the line for you in the file:
1 | 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.
1 | fallocate -l 2G /swapfile && chmod 600 /swapfile && mkswap /swapfile && swapon /swapfile && echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab |