Skip to content

Swap setup

Setup swap files in RAM and btrfs filesystems.

Use a swap file (in btrfs)

Swap files are more flexible than swap partitions in terms of disk space and partition usage.

Source: btrfs docs and Arch Linux wiki.

The following commands create a swap file in the btrfs filesystem, which does not (and should not) use copy-on-write (COW).

sudo btrfs subvolume create /swap # Create a btrfs subvolume for the swap file's directory
sudo btrfs filesystem mkswapfile --size 4G --uuid clear /swap/swapfile # Create a 4 GB swap file
sudo swapon /swap/swapfile

If btrfs filesystem mkswapfile command is not available, use the following command

cd /swap
sudo truncate -s 0 /swap/swapfile
sudo chattr +C /swap/swapfile
sudo fallocate -l 4G /swap/swapfile
sudo chmod 0600 /swap/swapfile
sudo mkswap /swap/swapfile
sudo swapon /swap/swapfile

Add the following line to /etc/fstab to mount the swap file on next boot.

/etc/fstab
/swap/swapfile none swap defaults 0 0

See the current activated swap file(s):

cat /proc/swaps

Use ZRAM

ZRAM is a compressed RAM disk, which can be used as a swap device to reduce physical disk swap use under high memory pressure.

Install ZRAM in Ubuntu: Source

sudo apt update && sudo apt install zram-tools

edit /etc/default/zramswap to change the options.

/etc/default/zramswap
ENABLED=true
ALGO=zstd
PERCENTAGE=50

enable

sudo systemctl enable --now zramswap

check ZRAM status

sudo zramctl

Comments