Create a FreeBSD swapfile (tutorial)

Home > Blog > Create a FreeBSD swapfile (tutorial)

After having to deploy a new FreeBSD server, I found out there’s an overlooked trick needed to keep the swapfile mounted after reboots. So here’s a quick tutorial on how to use a swapfile in FreeBSD 10 and onwards!

The basics

Swap in operating systems basically means using disk space as extra RAM. It’s definitely not optimal if you use a lot of it but it’s wise to have some, as memory exhaustion is never nice and can lead to application downtime. The FreeBSD handbook comes in handy in a lot of situations. It states here that you should have twice the amount of swap as RAM, but I deploy with enough memory after doing research and experiments. I create less or equal the amount of RAM as swap. Measure twice, cut once!

Let’s go already…!

Okay, okay, easy. For the following examples you might replace doas with sudo, or gain root privileges depending on how you set your system up. Doas is more secure.

We start with creating an 8GB swapfile under /usr. Alter the count for your intended size, e.g. 1024 will give you 1GB, 2048 will give you 2GB, etc.

doas dd if=/dev/zero of=/usr/swap0 bs=1m count=8192

Afterwards we modify the permissions, this is very important!

doas chmod 0600 /usr/swap0

Then, we add this to the bottom of our fstab to mount it during startup.

md99	none	swap	sw,file=/usr/swap0,late	0	0

The late keyword is crucial here! It allows the system to mount it with a delay, otherwise the system finds it can’t mount it at boot and doesn’t do it.

You can now either reboot or run swapon -aq to enable it during runtime! You should now think and consider if you want to encrypt your swap or not.

I hope you’ve found this useful after pulling your hair out, because you didn’t read the handbook like me. BTW, this website is proudly hosted on FreeBSD!

The FreeBSD logo.