Skip to content

Adding Swap to Linux⚓︎

Overview⚓︎

In Chris Down’s In defence of swap blog post he explains the importance of swap and that it is still best practice to add swap to systems and not depend on memory alone.

When a system runs out of memory and does not have swap, or does have swap but it is in full use, you can add a temp swap to get yourself out of a tight spot if you have a local volume with free space.

Process of Adding Temp Swap⚓︎

Bash
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# review your current memory and swap usage
free -h
swapon

# verify you have free disk space
df -h

# create an empty file for use as swap
dd if=/dev/zero of=/tmp_swap bs=1M count=256
# note, you may be able to use 'fallocate -l 256M /tmp/tmp_swap' to create the swap file on some file systems. This may create a file with 'holes', and is not suggested on xfs, see below

# secure the swap file as it may contain secrets
chmod 600 /tmp_swap

# setup the file as a swap area
mkswap /tmp_swap

# enable the swap file for usage by the kernel
swapon /tmp_swap

# review your new memory and swap usage
free -h
swapon

# if you need this to persist after a reboot, do the following
vi /etc/fstab
  append the following to fstab
/tmp_swap    swap    swap   defaults 0 0

# when ready to remove the swap remove it from fstab and perform
swapoff -v /tmp_swap
rm /tmp_swap

Common Issues⚓︎

When using fallocate on some file systems the file will be created with ‘holes’. See the man swapon for more information.

If you receive the following error you likely have holes in the swap file.

swapon: /tmp/tmp_swap: swapon failed: Invalid argument

Check journalctl for ‘swapon’ to confirm this finding.

kernel: swapon: swapfile has holes

To work around this use dd as shown above.


References⚓︎