How To Create Swap On Debian | Ubuntu

Linux Nov 22, 2021

Sometimes there isn't much RAM on the server and we have no choice but to add swapfile.

Execute following commands:

sudo fallocate -l 2G /swapfile
sudo chmod 600 /swapfile
sudo mkswap /swapfile
sudo swapon /swapfile

Make swap persistent after reboot. It's a good practice to save fstab in case we need original later or if we mess it up :)

sudo cp /etc/fstab /etc/
echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab

We can further tweak swap:

sudo sysctl vm.swappiness=10
sudo sysctl vm.vfs_cache_pressure=50

Add two more lines at the end of the file /etc/sysctl.conf

sudo nano /etc/sysctl.conf

Check swap with:

sudo swapon --show

Remove swap:

swapoff /swapfile
sudo rm -rf /swapfile

And remove it from /etc/fstab.


Great! You've successfully subscribed.
Great! Next, complete checkout for full access.
Welcome back! You've successfully signed in.
Success! Your account is fully activated, you now have access to all content.