There are at least two ways to configure swap on Linux. One is to format a partition directly and use that partition as the swap area. The other is to create a file and put all swap contents into it.

Formatting a partition for swap is usually handled by the system installer during setup; I only learned about it when installing Arch.

The general method is to partition the disk, run mkswap on that partition, and then write the partition’s location into /etc/fstab.

The contents look something like this.

/dev/mapper/sae-swap    swap  swap    defaults   0 0

It will automatically mount this partition as swap at boot, so you don’t have to worry about anything.

For a relatively stable, long-term swap setup, this should be the best choice.

But sometimes the requirements are a bit more complicated. For example, freeing up a partition, formatting it, and mounting it remotely isn’t difficult, but if there’s an easier way, I’d personally lean toward the simpler option.

Linux supports using a file as swap, and enabling or disabling swap online. The process is simple and can be done in a few steps after becoming root.

First, you need to prepare a file of the desired size. For example, 512 MB (that is, 1024 × 512 KB = 524288K).

Bash
# dd if=/dev/zero of=/swapfile1 bs=1024 count=524288

The above command writes 512 MB of zeros into /swapfile1. It has a serious problem: performance.

If I only create a 512 MB file with the above command, the speed is tolerable; but if I want to create a 700 GB file, I’d be waiting forever.

Our goal is simply to create a large enough empty file; another available command is fallocate.

The command is as follows:

Bash
# fallocate -l 700G /swapfile1

Although it still takes a few seconds, it’s very fast.

At this point, the file’s read/write permissions are too open, which is insecure. Set the file permissions as follows:

Bash
# chown root:root /swapfile1
# chmod 0600 /swapfile1

Then, format this file:

Bash
# mkswap /swapfile1

This makes /swapfile1 acceptable as a swap format.

Finally, enable swap:

Bash
# swapon /swapfile1

This easily gives us some new swap space.

If we no longer want this swap, disabling it is also easy:

Bash
# swapoff /swapfile1

Then we can safely delete the /swapfile1 file.

If we want it to automatically mount the swap on every boot, we need to edit /etc/fstab and add a line like this:

Bash
/swapfile1 none swap sw 0 0

/etc/fstab is executed during boot. If the file has errors, the system will fail to boot. Therefore, after making changes, it’s recommended to test it following the instructions in this article.

References: