Adding SWAP to Linux

Tired of the privacy invasion of the Chrome webbrowser? Worried about the risk of seeing ads everywhere? Give the Brave Browser a try. It supports all the same Chrome extensions, with none of the telemetry. It auto-blocks ads and helps support content creators like me.

Give the Brave browser a try »

Profile image of Mattias Geniar

Mattias Geniar, June 30, 2020

Follow me on Twitter as @mattiasgeniar

Here are the steps needed to add a new SWAP partition to your Linux machine. This’ll allocate 2GB of space on your disk, and allow it to be used as RAM if your server is running low.

Allocate the space for SWAP

First, let’s create a 2GB file on the disk that’ll be used as SWAP space. You need to have this space available on your hard drive!

$ fallocate -l 2G /swapfile
$ chmod 600 /swapfile

Mark the file as use for SWAP

Next up, we’ll have to explicitly mark that file to have the necessary layout to be used as a SWAP partition.

$ mkswap /swapfile

Activate the SWAP partition

Now, time to let the system use that 2GB file as the new SWAP space!

$ swapon /swapfile

Depending on your system load (or how urgent you’re adding new SWAP space), this may take a few seconds.

You can verify if the system has loaded this correctly as follows:

$ swapon --show
/swapfile file   2G 56.4M   -2

The free utility, which shows the total amount of memory and the free memory, will also list your SWAP space:

$ free -h
              total        used        free
Mem:           1.9G        1.1G        694M
Swap:          2.0G         68M        1.9G

Add the SWAP partition to /etc/fstab

To make sure the new SWAP partition is loaded on reboot, add this to your /etc/fstab line at the very bottom.

$ cp /etc/fstab /etc/fstab.backup
$ echo "/swapfile swap swap defaults 0 0" >> /etc/fstab

Your /etc/fstab should now look similar to this, with your root partition and the SWAP partition included (and probably some other partitions, as that’ll depend on your distro).

$ cat /etc/fstab
LABEL=cloudimg-rootfs   /           ext4    defaults	0 0
LABEL=UEFI              /boot/efi   vfat    defaults	0 0
/swapfile               swap        swap    defaults    0 0

To play it safe: reboot your machine and see if it works!

If it doesn’t, reboot in recovery mode and comment out (or remove) the last line in /etc/fstab, and reboot again.

Want to subscribe to the cron.weekly newsletter?

I write a weekly-ish newsletter on Linux, open source & webdevelopment called cron.weekly.

It features the latest news, guides & tutorials and new open source projects. You can sign up via email below.

No spam. Just some good, practical Linux & open source content.