How to add swap on ubuntu server

Check if swap is enabled on your server

sudo swapon -s
free -m

Create 256MB or 1GB file

sudo fallocate -l 256MB /swapfile
sudo fallocate -l 1G /swapfile

Check created file

ls -lh /swapfile

Set correct permission. Lock down for root use only

sudo chmod 600 /swapfile

Verify permission

ls -larh /swapfile


Make swap

sudo mkswap /swapfile

Swap on (enable swap)

sudo swapon /swapfile

Verify swap space

sudo swapon -s


Check current swappiness value. Default = 60

cat /proc/sys/vm/swappiness

Set swappiness to 10 (Lower the better for server as swap is not used frequently)

sudo sysctl vm.swappiness=10

For permanent effect

sudo nano /etc/sysctl.conf
vm.swappiness=10 #add at the end of the file


Check cache pressure. Filesystem is very costly to look up.

cat /proc/sys/vm/vfs_cache_pressure

Set cache pressure (Lower the better for server. Default = 100)

sudo sysctl vm.vfs_cache_pressure=95

For permanent effect

sudo nano /etc/sysctl.conf
vm.vfs_cache_pressure = 95 #add at the end of the file


Make the Swap File Permanent

sudo nano /etc/fstab

Add at the end of the /etc/fstab

/swapfile none swap sw 0 0

Leave a Comment

Your email address will not be published. Required fields are marked *