Raspberry Pi

How to add swap to Raspberry Pi

By default, Raspberry Pi Linux images come without swap enabled. And it makes sense! SD Cards used as a default are not suited to be used with swap! They would wear out too fast and in general, would not improve performance that much.

However, with new generations of Raspberry Pi, where you can install operating system on a SSD drive (for Raspberry Pi 4 connected via USB) it starts to make sense to give our Raspberry Pi a little extra swap memory. This becomes especially important for Raspperry Pi 5 which has PCIe bus exposed and can easily be used with NVME M.2 drives (with a special HAT of course).

In this post let’s enable swap file on a Raspberry Pi running Ubuntu (or other Debian based OSes).

This tutorial assumes that you already have migrated your Raspberry Pi Ubuntu instance to a NVME SSD drive. Don’t do it if you still use SD Cards, it will do more hard than it’s worth it.

First step is to create out swap file. Here, with a size of 4 gigabytes

sudo fallocate -l 4G /swapfile

The, let’s set correct permissions

sudo chmod 600 /swapfile

Convert the file we just created to swap format

sudo mkswap /swapfile

And enable it

sudo swapon /swapfile

Finally, we should mount our swap file on every boot. To do it, edit fstab

sudo nano /etc/fstab

And add the following line

/swapfile none swap sw 0 0

From now on, our Raspberry Pi will be able to use a fast, SSD based swap memory.

Raspberry Pi with a swap enabled on NVME M.2 drive

Ah, one more thing. To check swap usage you have a couple of options. My favorite is good old top, but sudo swapon --show will also work


Posted

in

by

Comments

Leave a Reply

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