Swap

This is a wiki page. Be bold and improve it!

If you have any questions about the content on this page, don't hesitate to open a new ticket and we'll do our best to assist you.

Key tools and files

swapon: enable swap.

swapoff: disable swap.

/etc/fstab: set up a permanent swap partition or swap file.

free: see system memory consumption, including swapped amount.

cat /proc/sys/vm/swappiness: indicates how much the linux kernel will make use of the swap space.

Understand your system

Before you try anything, it helps to build a proper understanding of how your system is configured, and how it performs.

# swapon --show
NAME      TYPE      SIZE   USED PRIO
/dev/sda4 partition 2.5G   339.9M   -1

free and top show you how much memory is used at any time.

cat /proc/sys/vm/swappiness shows the swappiness setting of the linux kernel, from 0 to 100.
0 = disable swapping altogether.
100 = always use swap.

Check how many partitions of type "swap" you have in /etc/fstab.
For example:

#<file system> <mount point>   <type>  <options>                      <dump>  <pass>
/dev/sda4     swap            swap    defaults                        0       0

Configuration

/etc/fstab

See also: /etc/fstab.

You may have several swap partitions, with different priorities:

/dev/ssd   swap swap defaults,pri=20   0 0
/dev/hdd   swap swap defaults          0 0
/swapfile  none swap sw                0 0

swappiness

Check current swappiness value:

# cat /proc/sys/vm/swappiness
60

Adjust swappiness value:

# sysctl vm.swappiness=20

As of Linux kernel 3.5+, vm.swappiness=0 completely disables swap!

To make the swappiness value permanent after a reboot, add the following setting:

vm.swappiness = 20

either to /etc/sysctl.conf or to /etc/sysctl.d/90-user.conf (or another .conf file within that directory), depending on your distribution.

Creating a swap file

If you find yourself in an urgent need for more swap space, you may create a swap file and add it to whatever existing swap space (partitions) you already have:

// 1M times 1024: this would create a 1GB swap file.
# dd if=/dev/zero of=/swapfile bs=1024 count=1M
# chmod 600 /swapfile
# sudo mkswap /swapfile
Setting up swapspace version 1, size = 1024 MiB (1073737728 bytes)
no label, UUID=2768af81-720a-4e04-acaf-848a39116347
# sudo swapon /swapfile
# swapon --show
NAME TYPE SIZE USED PRIO
/dev/sda4 partition 511M 307.5M -1
/swapfile file 1024M 0B -2

Add the swap file to /etc/fstab:

/swapfile       none            swap    sw                              0       0