# Add Swap Space on Ubuntu 20.04

# Step 1 – Checking the System for Swap Information

We can see if the system has any configured swap by typing:

sudo swapon --show

You can verify that there is no active swap using the free utility:

free -h
Output
              total        used        free      shared  buff/cache   available
Mem:          981Mi       122Mi       647Mi       0.0Ki       211Mi       714Mi
Swap:            0B          0B          0B

# Step 2 – Checking Available Space on the Hard Drive Partition

Before we create our swap file, we’ll check our current disk usage to make sure we have enough space. Do this by entering:

df -h
Output
Filesystem      Size  Used Avail Use% Mounted on
udev            474M     0  474M   0% /dev
tmpfs            99M  932K   98M   1% /run
/dev/vda1        25G  1.4G   23G   7% /
tmpfs           491M     0  491M   0% /dev/shm
tmpfs           5.0M     0  5.0M   0% /run/lock
tmpfs           491M     0  491M   0% /sys/fs/cgroup
/dev/vda15      105M  3.9M  101M   4% /boot/efi
/dev/loop0       55M   55M     0 100% /snap/core18/1705
/dev/loop1       69M   69M     0 100% /snap/lxd/14804
/dev/loop2       28M   28M     0 100% /snap/snapd/7264
tmpfs            99M     0   99M   0% /run/user/1000

# Step 3 – Creating a Swap File

Adjust the 8G to meet the needs of your own server:

sudo fallocate -l 8G /swapfile

We can verify that the correct amount of space was reserved by typing:

ls -lh /swapfile

# Step 4 – Enabling the Swap File

Make the file only accessible to root by typing:

sudo chmod 600 /swapfile
ls -lh /swapfile
Output
-rw-r--r-- 1 root root 8.0G Apr 25 11:14 /swapfile

We can now mark the file as swap space by typing:

sudo mkswap /swapfile
Output
Setting up swapspace version 1, size = 8192 MiB (1073737728 bytes)
no label, UUID=6e965805-2ab9-450f-aed6-577e74089dbf

We can enable the swap file, allowing our system to start using it:

sudo swapon /swapfile

Verify that the swap is available by typing:

sudo swapon --show
Output
NAME      TYPE  SIZE USED PRIO
/swapfile file 8192M   0B   -2

We can check the output of the free utility again to corroborate our findings:

free -h
Output
              total        used        free      shared  buff/cache   available
Mem:          981Mi       123Mi       644Mi       0.0Ki       213Mi       714Mi
Swap:         8.0Gi          0B       8.0Gi

# Step 5 – Making the Swap File Permanent

Back up the /etc/fstab file in case anything goes wrong:

sudo cp /etc/fstab /etc/fstab.bak

Add the swap file information to the end of your /etc/fstab file by typing:

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