Creating a swapfile in LInux

Rationale TL;DR

We ran out of memory or we forgot to provide a swap area and we don’t have a partition available

The solution

Another option we have is to use a regular file in the filesystem. The system would able to swap there. We can have as many files as we need (the same happens with dedicated filesystem partitions).

First, let’s create such a file. Let’s suppose 2G would be enough:

# fallocate -l 2G /swapfile 

Now, this file needs to be set up to be used as a swap area:

# mkswap /swapfile

Finally, the file needs to be root-protected, otherwise it would be a security problem:

# chmod 0600 /swapfile

We can now use the file. If we want to use it inmediately:

# swapon /swapfile

If we want to make it permanent, we would need something like this:

# echo '/swapfile none swap sw 0 0' >> /etc/fstab

Happy swapping!