Skip to content

Linux Foundations / Understand the system underneath ยท Step 8 of 38

Lesson: Swap SpaceSwitch
โ† Linux Foundations

System administration

Swap Space

Learn what swap does and how to create, enable and check a swap file or partition.

Swap is space on disk that the kernel can use to hold memory pages that are not needed in RAM right now. It lets the system keep more work going than RAM alone allows.

Disk is far slower than RAM. Swap is a safety margin, not a substitute for memory. Heavy, constant swapping makes a machine crawl.

Check what you have

$ swapon --show
NAME      TYPE      SIZE USED PRIO
/dev/sda3 partition   2G   0B   -2

$ free -h
               total        used        free      shared  buff/cache   available
Mem:           3.8Gi       1.2Gi       1.1Gi        20Mi       1.5Gi       2.4Gi
Swap:          2.0Gi          0B       2.0Gi

If swapon --show prints nothing, no swap is active. Priority numbers vary between versions. Some distributions, such as Fedora, use zram by default, which is compressed swap held in RAM.

Partition or file

Swap can be a dedicated partition or an ordinary file. A file is easy to create and resize. To make a 1 GiB swap file:

$ sudo dd if=/dev/zero of=/swapfile bs=1M count=1024
$ sudo chmod 600 /swapfile
$ sudo mkswap /swapfile
$ sudo swapon /swapfile

mkswap writes the swap signature. swapon starts using it. The chmod matters because swap can contain sensitive data from memory.

For a partition, run mkswap and swapon on the device, for example /dev/sdb2. Be certain it is the right one, because mkswap overwrites what is there.

Swap files on Btrfs need extra care (a file without copy-on-write), so follow your distribution's documentation there.

Turning it off

$ sudo swapoff /swapfile

The kernel must first bring the swapped pages back, so there needs to be enough free memory.

Make it permanent

Add a line to /etc/fstab:

/swapfile  none  swap  sw  0  0

Swappiness

The vm.swappiness setting influences how readily the kernel swaps process memory compared with dropping cached file data:

$ cat /proc/sys/vm/swappiness
60

Lower values favour keeping process memory in RAM. The usual default is 60.

Try it

Run swapon --show and free -h. On a test VM, create a small swap file, confirm it appears, then swapoff it and delete the file.

Check your understanding

Swap Space

All 5 sections ยท no timer

Unlimited retries

Questions from every section are combined into one assessment. Answer them all correctly to complete the article.

Your completion saves in this browser. Sign in to sync it to your account.