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=1024 count=2M

You will see output like

2097152+0 records in
2097152+0 records out
2147483648 bytes (2.1 GB, 2.0 GiB) copied, 41.7768 s, 51.4 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 (`mkswap manual`):

# 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 = 2 GiB (2147479552 bytes)
no label, UUID=f30730f3-eb1d-4d30-a088-a0274f3c2f3e

Turn on the swap file for Linux’s swap

Now, use `swapon` (swapon manual):

# 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 (for the example in this post)

/swapfile swap swap defaults 0 0

Eric Ma

Eric is a 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 *