Skip to content
RIPE NCC member · Local Internet RegistryCall us on 020 3318 3449sales@hosting-telecom.uk

Swap file

Why a server needs swap, how to add it on Linux and FreeBSD, and when you are better off adding memory.

Contents

Swap is space on the disk where the system puts data from memory when it runs short. It doesn’t replace memory — a disk is much slower — but it is a safety net: without swap, when memory runs out the system simply stops the most memory-hungry program, and that is often the database. If you are constantly short of memory, it’s better to add more in your control panel.

To see whether you have swap now, run swapon --show and free -h (on FreeBSD, swapinfo).

Linux

A 2 GB swap file:

sudo dd if=/dev/zero of=/swapfile bs=1M count=2048 status=progress
sudo chmod 600 /swapfile
sudo mkswap /swapfile
sudo swapon /swapfile
echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab

The last line makes swap switch on again after a reboot. To stop the system moving data to disk too eagerly, lower the “swappiness”:

echo 'vm.swappiness=10' | sudo tee /etc/sysctl.d/99-swap.conf
sudo sysctl -p /etc/sysctl.d/99-swap.conf

To remove swap, run sudo swapoff /swapfile, delete the line from /etc/fstab and delete the file itself.

FreeBSD

sudo dd if=/dev/zero of=/usr/swap0 bs=1m count=2048
sudo chmod 0600 /usr/swap0
echo 'md none swap sw,file=/usr/swap0,late 0 0' | sudo tee -a /etc/fstab
sudo swapon -aL

Our FreeBSD images use the UFS file system, so this works. Don’t put a swap file on ZFS: the system may hang.

Didn’t find the answer? Ask our support team — we’ll help.

Choose which cookies we may use. You can change your mind at any time with the “Cookie settings” link at the bottom of every page.

Necessary

Always active

They keep the site secure and remember your cookie choice. They don’t identify you.

Google Analytics counts visits and shows which pages people find useful, so we can improve the site. Which cookies