SWAP in Linux

In Linux, random access memory (RAM) is divided into blocks called pages. Swapping is the process of moving memory pages to a dedicated disk area called swap space to free up RAM. Swap space can be either a separate partition or a file. The total amount of RAM and swap is the amount of virtual memory available to the system.

Swapping is needed for the following reasons:

  • When an application or process needs more memory than is currently free in RAM, the kernel moves the least used pages to swap and gives the freed memory to the running application or process.
  • Many pages used by programs at startup are needed only during initialization. The system can move these pages to swap and free up RAM.

The main disadvantage of swap:

  • Disks are much slower than RAM. RAM access is measured in nanoseconds, while disk access is measured in microseconds (SSD) or milliseconds (HDD), so the same operations on disk take thousands to tens of thousands of times longer. The more pages are swapped, the slower the system works.

When memory runs out, the database often suffers first. You may see problems like these:

  • The site keeps going down with the error "database connection failed", which means, for example, that MySQL has crashed.
  • The MySQL log (/var/log/mysql/error.log) shows the error InnoDB: Fatal error: cannot allocate memory for the buffer pool. This means there is not enough RAM for the database buffer.

Even on an SSD, swap is much slower than RAM, so heavy swapping increases response time. Swap is a safety net, not a replacement for memory. If your server regularly runs out of RAM, we recommend upgrading to a plan with more memory, for example one of our Linux VPS plans.

How to Check Swap

Check whether swap is enabled:

swapon --show

Example output:

NAME      TYPE SIZE USED PRIO
/swapfile file   2G 256M   -2

You can also check memory and swap usage with free:

free -m
               total        used        free      shared  buff/cache   available
Mem:            3916        1520         310          42        2085        2120
Swap:           2047         256        1791

In this example, swap is enabled and partly used. If swapon --show prints nothing, the server has no swap.

How to Create a Swap File

Create a 2 GB file for swap (change count to set another size, in megabytes):

dd if=/dev/zero of=/swapfile bs=1M count=2048

Set the permissions so that only root can read and write the file:

chmod 600 /swapfile

Format the file as swap:

mkswap /swapfile

Enable it:

swapon /swapfile

To enable swap automatically at boot, open /etc/fstab and add this line:

/swapfile none swap defaults 0 0

Check the result with swapon --show or free -m.

Blog
Subscribe to our Newsletter