CH-J Server Managerserver management over SSH
Menu
All guides and articles →

How to create or grow swap on Ubuntu and Debian

Check memory use, create a swap file, make it persistent and resize it safely, with notes on Btrfs and zram.

Check whether you need more swap

Swap gives the system room when memory runs short, but it is much slower than RAM. Look at the available column rather than free, because Linux uses unused memory as cache and releases it when needed. Constant swap activity means the server needs more memory or fewer processes, and more swap will not solve that.

free -h
swapon --show
vmstat 1 5

Create a swap file

Check free disk space first, then create the file, restrict its permissions, format it and activate it. The file must be readable by root only.

df -h /
sudo fallocate -l 2G /swapfile
sudo chmod 600 /swapfile
sudo mkswap /swapfile
sudo swapon /swapfile
swapon --show

Keep it after a restart

Add one line to /etc/fstab, after backing up the file. A mistake in fstab can prevent a normal boot, so verify the file before restarting.

sudo cp /etc/fstab /etc/fstab.backup
echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab
sudo findmnt --verify

Resize a swap file

Before deactivating swap, make sure its contents fit into available memory: swapoff moves them back to RAM, and if they do not fit, processes may be killed. Then deactivate the file, create it again at the new size and activate it. The fstab line stays the same as long as the path does.

free -h
sudo swapoff /swapfile
sudo fallocate -l 4G /swapfile
sudo mkswap /swapfile
sudo swapon /swapfile

Btrfs and zram

On Btrfs a swap file needs special handling: use btrfs filesystem mkswapfile, and note that a subvolume with a swap file cannot be included in a snapshot. zram is different from a swap file, because it keeps compressed pages in RAM instead of on disk, and it is managed by its own service, not through fstab.

Swap in CH-J Server Manager

System Monitor shows a RAM breakdown, the history of RAM and swap and every swap area with its type, priority and activity. With root or sudo you can create, activate, deactivate, resize and delete swap files in /swapfile*, /swap/<name> or /var/lib/swap/<name>, from 64 MiB to 64 GiB, on ext2/3/4, XFS, Btrfs and F2FS. The application refuses to deactivate swap whose contents would not fit into memory and backs up /etc/fstab before each change. zram and zswap are read-only there.

Detailed documentation

man: swapon →

man: mkswap →

Biometric unlock and security →