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 512MB of RAM, create a 1GB swap file.
sudo fallocate -l 1G /swapfile
Now check if the file was created.
ls -lh /swapfile
If it was created correctly, you should see something like:
-rw-r--r-- 1 root root 1.0G May 6 20:41 /swapfile
2. Configure Swap File
Make the swap file only accessible to root.
sudo chmod 600 /swapfile
Mark the file as a swap file.
sudo mkswap /swapfile
If it was successful, you should see something like
Setting up swapspace version 1, size = 1024 MiB (1073737728 bytes) no label, UUID=801104b5-1967-458d-a564-8d63e7a24403
Finally we will tell the system to start using our new swap file,
sudo swapon /swapfile
To verify that the swap is now available type:
sudo swapon --show
NAME TYPE SIZE USED PRIO /swapfile file 1024M 0B -1
We can also run the following to see our new swap file alongside physical memory
total used free shared buff/cache available Mem: 488M 218M 124M 37M 145M 203M Swap: 1.0G 0B 1.0G
3. Make it Persistent
This swap will only last until next reboot. In order to make it permanent, we will add it to the
echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab
4. Swap Settings
For a server, you should change the
swappiness value to 10.
sudo sysctl vm.swappiness=10
Now change the
vfs_cache_pressure value to 50.
sudo sysctl vm.vfs_cache_pressure=50
To make these two settings persist after next reboot, edit the following file:
sudo nano /etc/sysctl.conf
Add this to the bottom.
Save file and exit. (Press
Y and then press
A useful way to keep an eye on your swap usage is to run
htop. See: Better system monitoring with htop
p.s. I increased my AdSense revenue by 200% using AI 🤖. Read my Ezoic review to find out how.