Creating Swap Space on Ubuntu 18.04
Of course, we do not recommend you use swap space as a replacement to physical memory, especially on cloud hosting. If you are continuously eating into swap space, you should upgrade your physical memory. Swap should really only be a fall back in case memory usage peaks abnormally.
First check if the system has any swap configured.
If the output is blank, there is no swap configured so we can continue with this guide.
1. Create a Swap File
We will use the fallocate
program to create a swap file. Best practice is to create a swap file double the amount of your RAM. If you have 1024MB of RAM, create a 2GB swap file.
Now check if the file was created.
If it was created correctly, you should see something like:
2. Configure Swap File
Make the swap file only accessible to root.
Mark the file as a swap file.
If it was successful, you should see something like
Finally we will tell the system to start using our new swap file,
To verify that the swap is now available type:
Result:
We can also run the following to see our new swap file alongside physical memory
Result:
3. Make it Persistent
This swap will only last until next reboot. In order to make it permanent, we will add it to the /etc/fstab
file.
4. Some Final Tweaks
For a server, you should change the swappiness
value to 10.
Now change the vfs_cache_pressure
value to 50.
To make these two settings persist after next reboot, edit the following file:
Add this to the bottom.
/etc/sysctl.conf
Save file and exit. (Press CTRL
+ X
, press Y
and then press ENTER
).
If you can, reboot the server with sudo reboot
and run sudo swapon --show
just to make sure the swap space was created automatically on startup.
A useful way to keep an eye on your swap usage and system resources is to run htop
.
Last updated