SWAP in Linux
Guide to creating a SWAP partition on Linux
SWAP is a virtual memory mechanism where part of the data from RAM is offloaded to a storage device such as an HDD (hard disk drive) or SSD (solid-state drive).
In Linux, RAM is divided into blocks called pages. Swapping is the process of copying these memory pages into a specially allocated area on disk called swap space (this can be either a dedicated disk partition or a swap file). The combined size of physical RAM and swap space defines the total amount of available virtual memory.
Why swapping is needed
- When the system requires more memory than is currently available, the kernel moves the least-used pages into swap, freeing RAM for active processes.
- Many memory pages used by applications during startup are no longer needed afterward. The system can push these to swap, freeing up RAM.
Drawbacks of SWAP
- Accessing disk storage is much slower than RAM: operations in RAM are measured in nanoseconds, while on a disk they are measured in milliseconds. That means the same operation can take tens of thousands of times longer on disk. As a result, the more pages are swapped, the slower the system performs.
Note
When applications start relying heavily on swap, performance can degrade significantly. At that point, it’s often better to increase available memory. One option is migrating your project to a VPS or a dedicated server, where you can scale resources more flexibly.
Databases are usually the first to be affected by memory shortages. Typical symptoms include:
- The website crashing with a “Database connection error” (for example, when MySQL stops responding).
- The log file
/var/log/mysql.log
showing InnoDB: Fatal error: cannot allocate memory for the buffer pool, which indicates that there isn’t enough RAM available to allocate the buffer.
If swap is located on an SSD, keep in mind that data still has to go through the storage subsystem, which increases latency.
Checking if swap is enabled
swapon -s
Filename Type Size Used Priority
/swapfile file 40956 40956 -1
You can also run:
free -m
total used free shared buff/cache available
Mem: 488 160 7 40 320 259
Swap: 39 39 0
Here we can see that swap is active and will be used when needed.
Creating a swap file (if missing)
Create a 512 MB swap file:
dd if=/dev/zero of=/swap.file bs=1M count=512
To change the size, adjust the count
value.
Set the correct permissions so only root can read and write:
chmod 600 /swap.file
Format the file as swap:
mkswap /swap.file
Edit /etc/fstab
to make the swap file permanent:
/swap.file swap swap defaults 0 0
After rebooting, verify that swap is active with:
free -m