How to add a file based swap for Linux?

I want to add some swap space for a Linux box. Unfortunately, I find that all disk space is partitioned and mounted. Some partition has large available free space. I do 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?

asked Jul 26, 2015 by anonymous

1 Answer

You 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


# 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

# 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

# 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
answered Jul 30, 2015 by Eric Z Ma (44,280 points)

Please log in or register to answer this question.

Copyright © SysTutorials. User contributions licensed under cc-wiki with attribution required.
Hosted on Dreamhost