Swap

Updated: November 20, 2024

Setup swap as either a swapfile or swap partition.


NOTE: by-uuid and by-label should not be used with randomEncryption.
UUIDs and labels get erased every boot when partitions are encrypted.

Create flash drive as swap

# check for which device to use
lsblk

# unmount disired device
sudo umount /dev/sdX1

# create swapfile partition
sudo fdisk /dev/sdX
  g  - create a new GPT
  n  - new partition
  enter x3
  w  - write changes

# format the partition (-L sets label)
sudo mkswap -L swap /dev/sdX1

Once we have a swap partition, we can use it:

# add this to nixos configuration to enable swap
swapDevices = [
  { device = "/dev/disk/by-label/swap"; }   # could do UUID
];

Create a swapfile

We just need to tell nixos to create a swapfile and assign size.
When size is set, device is interpreted as a path of a swapfile.
Nixos will maintain the file, including permissions, ownership, etc.

swapDevices = [
  {
    device = "/swapfile";  # other linux like /var/lib/swapfile
    size = "16384";  # Number is in MB
  };
];

we can check if swap is working with:

free -h
swapon --show