How to Create Swap File on Ubuntu 19.10 & 19.04

What is Swap?

Swap is basically a partition or a file that acts as RAM in situations where your server’s memory is saturated. If we manage a server properly, we hope to never need it, as swap partition is stored on your hard disk which is orders of magnitude slower than RAM. But if something goes wrong on your server and your memory usage skyrockets, swap may save you from having your server go down.

Check Swap space

The Linux free command

free -h

When you check your free memory, you’ll see swap listed whether you have it or not, but when swap is deactivated, you will see all zeros for the size totals.

The swapon command

You can use the swapon command to check swap.

swapon --show

Create swap file on Ubuntu

In most cases, you would’ve had a swap file created for you during installation. You could, of course, add a swap partition later if for some reason you don’t have one.

Step 1 : you’ll first create the actual file to be used as swap. This can be stored anywhere, but /swapfile is typically ideal. You can use the fallocate command to create the actual file:

sudo fallocate -l 4G /swapfile
sudo chmod 600 /swapfile

Here, I’m creating a 4 GB swap file, but feel free to make yours whatever size you want in order to fit your needs

Step 2 : Next, we need to prepare this file to be used as swap:

sudo mkswap /swapfile

Step 3 : Now, we have a swap file stored in our root filesystem. Next, we’ll need to mount it. As always, it’s recommended that we add this to our /etc/fstab file. What follows is an example entry:

/swapfile       none     swap    sw      0        0

Step 4 : we can activate our new swap file with the swapon command

sudo swapon -a

Remove swap file in Linux

Step 1 : First, deactivate the swap

sudo swapoff /swapfile

Step 2 : Remove the swap entry in the /etc/fstab file (add # in front of the line).

#/swapfile       none     swap    sw      0        0

Step 3: Delete the actual swapfile file

sudo rm /swapfile

Add Comment