Your requirement

You need more memory permanently or temporarily, e.g., for a complex process. You cannot or do not want to create a new swap partition.

The solution

Linux can also swap into files. Swap files can be added and removed in a running system.

The procedure

First you create a file to swap to. Its size determines how much swap space you gain. The file is not automatically increased or reduced by Linux. You can create the file, for example, by copying zero bytes from the file /dev/zero with the dd command. bs stands for blocksize. The M stands for Megabyte. The following command creates a file /tmp/swap.img of the size 512 MB:

root@linux# dd if=/dev/zero of=/tmp/swap.img bs=1M count=512

Now you must create a swap signature in this file. The mkswap command is used for this:

root@linux# mkswap /tmp/swap.img
Swapbereich Version 1 wird angelegt, Größe 536866 KBytes

The new swap space is integrated with swapon and becomes active immediately:

root@linux# swapon /tmp/swap.img

The free -m command shows memory and swap space in megabytes:

root@linux# free -m
             total       used       free     shared    buffers     cached
Mem:          1977       1255        721          0         79        957
-/+ buffers/cache:        219       1758
Swap:          511          0        511

All active swap areas are listed by swapon -s:

root@linux# swapon -s
Filename                         Type            Size    Used    Priority
/tmp/swap.img                    file            524280  0       -1

The swapoff command deactivates the swap file:

root@linux# swapoff /tmp/swap.img

Then you can delete the file:

root@linux# rm /tmp/swap.img

Note: Swap files activated with swapon are not automatically reactivated after a reboot. For this, they must be entered in /etc/fstab.

Linux knowledge

These articles were written by the founder of Checkmk many years ago.
They are still valid though and thus we keep them on our website.
Mathias has since then developed a monitoring software called Checkmk

Find out more