Add a Swap Partition to a Ubuntu 22.04 instance

Below is a guide on how you can add a swap disk/partition to a Ubuntu 22.04 instance, I would recommend that you have a decent amount of hard disk space available to avoid constant use of the swap drive, a process called swapping.

Generally a swap partition should be equal or half the amount of installed RAM and not exceed 4GB, one of the uses of using a swap drive is mitigating a temporary malicious attempt at using all your servers resources by using the swap drives disk memory and avoiding issues such as OOM-Killer (Out Of Memory).

Create a 2GB Swap partition:

fallocate -l 2G /swapfile

Check it:

ls -lh /swapfile

You should see:

-rw-r--r-- 1 root root 2.0G Apr 25 11:14 /swapfile

Change permissions:

chmod 600 /swapfile

Declare it as swap:

mkswap /swapfile

Mark it as swap

swapon /swapfile

Verify the file:

swapon --show

You should see:

NAME      TYPE  SIZE USED PRIO
/swapfile file 2048M   0B   -2

Make it permanent (back up fstab first) :

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

Check swappiness level – should be 10:

cat /proc/sys/vm/swappiness
Output
10

If not, make it 10:

nano /etc/sysctl.conf
vm.swappiness=10

That’s it, you can check with free -m:

root@mel1:~# free -m
               total        used        free      shared  buff/cache   available
Mem:            3911        1532         453         288        1926        1800
Swap:           2047         305        1742

Or df -h

root@mel1:~# df -h
Filesystem      Size  Used Avail Use% Mounted on
tmpfs           392M  976K  391M   1% /run
/dev/vda1        59G   19G   38G  33% /
tmpfs           2.0G  448K  2.0G   1% /dev/shm
tmpfs           5.0M     0  5.0M   0% /run/lock
/dev/vda15      123M  6.1M  117M   5% /boot/efi
tmpfs           392M  4.0K  392M   1% /run/user/0

Leave all Comment