How to Add a File Based Swap for Linux

We may want to add some swap space for a Linux box while only find that all disk space is partitioned and mounted. Some partition has large available free space. For such cases, we may not want to change the partition allocation. The solution may be to add a file based swap for Linux as what Windows does. How to add a file based swap for Linux is introduced in this post.

We can add a file based swap to Linux following these steps. Here, we use an example to add a 26GB swap file to Linux.

Create a swap file for swapping

Command:

# dd if=/dev/zero of=./swapfile bs=8192 count=3M

You will see output like

3145728+0 records in
3145728+0 records out
25769803776 bytes (26 GB) copied, 228.546 s, 113 MB/s

Note that the common tricks to create a sparse file by adding a `seek` option to `dd` should NOT be used.

It is a good idea to make the swap file only accessible to root since it will store memory content and possibly have sensitive data.

# chmod 700 ./swapfile

Make a swap partition on the swap file

By the `mkswap` command https://www.systutorials.com/docs/linux/man/8-mkswap/:

# mkswap ./swapfile

It will show output as follows

mkswap: ./swapfile: warning: don't erase bootbits sectors
on whole disk. Use -f to force.
Setting up swapspace version 1, size = 25165820 KiB
no label, UUID=f30730f3-eb1d-4d30-a088-a0274f3c2f3e

Turn on the swap file for Linux’s swap

Now, use `swapon` https://www.systutorials.com/docs/linux/man/8-swapon/:

# swapon ./swapfile

You can see all the swap files by

# swapon --show

Make the swap file permanent for Linux’s swap

Add this line to /etc/fstab

/path/to/swapfile swap swap defaults 0 0

Eric Z Ma

Eric is a father and systems guy. Eric is interested in building high-performance and scalable distributed systems and related technologies. The views or opinions expressed here are solely Eric's own and do not necessarily represent those of any third parties.

Leave a Reply

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