Intermediate · 8 min · practise every command in the built-in terminal

Swap — Extra Memory on Disk

When RAM runs out, Linux can move memory it hasn't touched lately out to disk: swap. Disk is far slower than RAM — but instead of the out-of-memory killer ending your database, the server only slows down for a while. Most cloud servers start without any:

free -h
              total        used        free      shared  buff/cache   available
Mem:          2.0Gi       305Mi       1.4Gi        18Mi       307Mi       1.5Gi
Swap:            0B          0B          0B

A swap file is the easy way — no partition needed:

sudo fallocate -l 2G /swapfile
sudo chmod 600 /swapfile
sudo mkswap /swapfile
sudo swapon /swapfile
  1. fallocate makes a 2 GiB file and reserves all its space at once.
  2. chmod 600 — only root may read it: it can hold anyone's memory, passwords included.
  3. mkswap writes the swap header.
  4. swapon puts it to use.
swapon --show
free -h
NAME      TYPE SIZE USED PRIO
/swapfile file   2G   0B   -2

Every boot

swapon lasts until the next reboot. One line in /etc/fstab makes it permanent:

/swapfile none swap sw 0 0

sudo swapon -a turns on every swap in fstab — the test, like mount -a.

RAMSwap to start with
up to 2 GBas much as the RAM
4–8 GB2–4 GB
16 GB and more4 GB

💡 truncate -s 2G makes a file with holes — mkswap warns about it and swapon refuses it. That's why fallocate.

Practice tasks

  1. Check the memory: is there any swap?
  2. Make a 2 GiB file /swapfile
  3. Let only root read and write it
  4. Turn it into swap space
  5. Start using it
  6. Show the swap in use
  7. Make it permanent: a line in /etc/fstab

Commands in this lesson

Disk & Memory