Historically linux distributions have created a dedicated partition to be used as swap space and while this does come with some advantages there are other issues with it as well. Being a fixed size partition means it is relatively difficult to later change your mind about how much swap your system actually needs.

Thankfully there is another way: using a swap file instead of a swap partition.

To do this all you need to do is create a file that will hold your swap, set the right permissions to it, format it and use it. The ArchWiki has an excellent guide on the whole process here but I’ve re-created my steps below.

I like to use fallocate but you could also use dd or whatever. For example the following will create a 2GB swap file in the root directory:

sudo fallocate -l 2G /swapfile

Next up set the permissions:

sudo chmod 600 /swapfile

Format it:

sudo mkswap /swapfile

Use it:

sudo swapon /swapfile

That’s pretty much it. At this point you have the ability to add as much swap (via swap files) as you’d like. If you ever want to stop using swap, for example to get rid of the file when you’re done, simply issue the following command:

sudo swapoff /swapfile

One other thing to note is that every time you reboot your system you will have to re-run the swapon command above. To avoid this you can add it to your fstab file so that it is done on startup.

/swapfile none swap defaults 0 0

The nice thing about using swap files is that they are really flexible, allowing you to allocate as much or as little as you need at any given time.