Example: create, increase, or decrease existing swap file size

swapoff -a # turn off swapping
sizeMb=16384 # specify data size of 16GiB

# if file system is NOT ZFS (use df -T to investigate)
# Preempt error: 'swapon: /swapfile: skipping - it appears to have holes.'
sudo dd if=/dev/zero of=/swapfile bs=1M count=$sizeMb # copying zeros to swap with specified file size

sudo chmod 600 /swapfile # set correct permissions
sudo mkswap /swapfile # create swapfile
sudo swapon -a # turn on swapping
sudo swapon /swapfile # direct swap to use /swapfile

# Check contents of fstab
cat /etc/fstab

# If creating new swapfile, create this entry to make /swapfile load on reboots
sudo echo "/swapfile swap swap sw 0 0" >> /etc/fstab

# if file system is ZFS (source: github.com/zfsonlinux/pkg-zfs/wiki/HOWTO-use-a-zvol-as-a-swap-device)
sudo zfs create -V 16G -b $(getconf PAGESIZE) -o compression=zle \
      -o logbias=throughput -o sync=standard \
      -o primarycache=metadata -o secondarycache=none \
      -o com.sun:auto-snapshot=false rpool/swap
sudo mkswap -f /dev/zvol/rpool/swap
sudo echo /dev/zvol/rpool/swap swap swap defaults 0 0 >> /etc/fstab
sudo swapon -a # turn on swapping
sudo swapon /dev/zvol/rpool/swap # direct swap to use /swapfile

# Instead of rebooting the computer for changes to take effect, a more efficient method is to run this command
sudo mount -av # v for verbose

# Check for status of swapping
free -m

Example: adding additional swap file(s)

# Create a new swap2 file 4GB in size
# Option 1: lvm
lvcreate -L 4G -n swap2 /swap2
# Option 2: dd
sudo dd if=/dev/zero of=/swap2 count=4096 bs=1M

# Set permissions
sudo chmod 600 /swap2

# Format it
sudo mkswap /swap2

# Enable it
sudo swapon /swap2

# Set it on as default
sudo echo "/swap2 swap swap sw 0 0" >> /etc/fstab

Example: creating swap partitions

# Create swap volume
ali@kimlinux:/home/ali# lvcreate -L 16G -n swap volumegroup1
  Logical volume "swap" created.

# Creating swap file
ali@kimlinux:/home/ali# mkswap /dev/volumegroup1/swap
Setting up swapspace version 1, size = 32 GiB (34359734272 bytes)
no label, UUID=494c818b-c00e-47cd-8937-f7443f218af8
ali@kimlinux:/home/ali# sudo chmod 600 /dev/volumegroup1/swap

# Find disk uuid
ali@kimlinux:~$ ls -l /dev/disk/by-uuid
total 0
lrwxrwxrwx 1 root root 10 Sep  1 20:57 4061-23B6 -> ../../sdb1
lrwxrwxrwx 1 root root 10 Sep  1 20:57 a7e20382-d8f0-4d64-82ad-f161fc45610e -> ../../sdb2
lrwxrwxrwx 1 root root 10 Sep  1 20:59 c7d5f77d-29d6-4ac7-bcf6-cf32b691ce48 -> ../../dm-1
lrwxrwxrwx 1 root root 10 Sep  1 20:57 d7623939-d093-4461-bcd9-deef3e22427c -> ../../dm-0

# set disk variable
ali@kimlinux:~$ swapdisk=/dev/disk/by-uuid/d7623939-d093-4461-bcd9-deef3e22427c

# Enable swap
ali@kimlinux:# sudo su
ali@kimlinux:# swapdisk=/dev/disk/by-uuid/d7623939-d093-4461-bcd9-deef3e22427c
root@kimlinux:# swapon $swapdisk

# Set swap to load on startup
root@kimlinux:/home/kim# echo "$swapdisk swap swap sw 0 0" >> /etc/fstab

# Check results of creating swapfile
ali@kimlinux:/home/ali# free -m
              total        used        free      shared  buff/cache   available
Mem:          32015        4672       24376        1162        2966       25744
Swap:         32767           0       32767

# making some illustrative mistakes of mounting a swap volume as a directory
ali@kimlinux:/home/ali# mkdir /swap
ali@kimlinux:/home/ali# mount /dev/$groupname/swap /swap
mount: /swap: wrong fs type, bad option, bad superblock on /dev/mapper/volumegroup1-swap, missing codepage or helper program, or other error.
ali@kimlinux:/home/ali# lvcreate -L 32015 -n swap /vmstorage1/swap
  Volume group name expected (no slash)
  Run `lvcreate --help' for more information.
ali@kimlinux:/home/ali# mkdir /vmstorage1/swap
ali@kimlinux:/home/ali# chmod 600 /vmstorage1/swap
ali@kimlinux:/home/ali# mkswap /vmstorage1/swap
mkswap: warning: truncating swap area to 17179869180 KiB
mkswap: cannot open /vmstorage1/swap: Is a directory
ali@kimlinux:/home/ali# sudo dd if=/dev/zero of=/vmstorage1/swap count=32015 bs=1M
dd: failed to open '/vmstorage1/swap': Is a directory

# not able to mount swap filesystem or volume onto a directory
ali@kimlinux:/home/ali# mount /dev/$groupname/swap /swap
mount: /swap: unknown filesystem type 'swap'.

Example: Adding a New Swap Disk

# List disks
sudo lsblk

# Check available disk space
sudo df -h

# Check memory & swap file
free -m

# Set swapfile variable - be certain that a valid value is given here
# In this example: /dev/sda1 has been formatted as swap prior to this
swapdisk=/dev/sda1

# Zero out first 16MB of disk to effectively clear its partitioning table
sudo dd if=/dev/zero of=$swapdisk count=4096 bs=4096

# Set appropriate permissions to secure the directory
chmod 600 $swapdisk 

# Create swapfile in the /swapdisk directory
mkswap $swapdisk

#configure system to use $swapfile
swapon $swapdisk 

# Check swapdisk settings
swapon -s

# Enable swapfile to persist reboots
sudo echo "$swapdisk swap swap sw 0 0" >> /etc/fstab

# Check fstab
cat /etc/fstab

############## SAMPLE OUTPUT ##############
######### List disks ##############
brucelee@kimlinux:/home/brucelee# lsblk
NAME   MAJ:MIN RM   SIZE RO TYPE MOUNTPOINT
loop0    7:0    0  96.6M  1 loop /snap/core/9804
loop1    7:1    0  55.3M  1 loop /snap/core18/1885
loop2    7:2    0 161.4M  1 loop /snap/gnome-3-28-1804/128
loop3    7:3    0  29.9M  1 loop /snap/snapd/8790
loop4    7:4    0  62.1M  1 loop /snap/gtk-common-themes/1506
loop5    7:5    0    39M  1 loop /snap/remmina/4309
sda      8:0    0  14.9G  0 disk 
└─sda1   8:1    0  14.9G  0 part 
sdb      8:16   0   477G  0 disk 
├─sdb1   8:17   0   300M  0 part /boot/efi
└─sdb2   8:18   0 476.7G  0 part /

######### Check Disk Space ##############
brucelee@kimlinux:/home/brucelee# df -h
Filesystem      Size  Used Avail Use% Mounted on
udev             16G     0   16G   0% /dev
tmpfs           3.2G  1.7M  3.2G   1% /run
/dev/sdb2       469G  7.6G  437G   2% /
tmpfs            16G  401M   16G   3% /dev/shm
tmpfs           5.0M  4.0K  5.0M   1% /run/lock
tmpfs            16G     0   16G   0% /sys/fs/cgroup
tmpfs            16G     0   16G   0% /tmp
/dev/loop1       56M   56M     0 100% /snap/core18/1885
/dev/loop2      162M  162M     0 100% /snap/gnome-3-28-1804/128
/dev/loop3       30M   30M     0 100% /snap/snapd/8790
/dev/loop0       97M   97M     0 100% /snap/core/9804
/dev/loop4       63M   63M     0 100% /snap/gtk-common-themes/1506
/dev/loop5       39M   39M     0 100% /snap/remmina/4309
/dev/sdb1       300M  7.8M  292M   3% /boot/efi
tmpfs           3.2G   12K  3.2G   1% /run/user/1000

brucelee@kimlinux:/home/brucelee# swapdisk=/dev/sda1
brucelee@kimlinux:/home/brucelee# sudo dd if=/dev/zero of=$swapdisk count=4096 bs=4096
4096+0 records in
4096+0 records out
16777216 bytes (17 MB, 16 MiB) copied, 0.072039 s, 233 MB/s
brucelee@kimlinux:/home/brucelee# chmod 600 $swapdisk
brucelee@kimlinux:/home/brucelee# mkswap $swapdisk
Setting up swapspace version 1, size = 14.9 GiB (16012800000 bytes)
no label, UUID=21d57b4a-e385-4d21-a07b-3bee39de57a9
brucelee@kimlinux:/home/brucelee# swapon $swapdisk
brucelee@kimlinux:/home/brucelee# swapon -s
Filename                                Type            Size    Used    Priority
/dev/sda1                               partition       15637500        0       -2
brucelee@kimlinux:/home/brucelee# vim /etc/fstab
brucelee@kimlinux:/home/brucelee# free -m
              total        used        free      shared  buff/cache   available
Mem:          32015        3189       25054         753        3772       27636
Swap:         15270           0       15270

brucelee@kimlinux:/home/brucelee# cat /etc/fstab
# /etc/fstab: static file system information.
#
# Use 'blkid' to print the universally unique identifier for a device; this may
# be used with UUID= as a more robust way to name devices that works even if
# disks are added and removed. See fstab(5).
#
# <file system>             <mount point>  <type>  <options>  <dump>  <pass>
UUID=4061-23B6                            /boot/efi      vfat    umask=0077 0 2
UUID=a7e20382-d8f0-4d64-82ad-f161fc45610e /              ext4    defaults,discard 0 1
tmpfs                                     /tmp           tmpfs   defaults,noatime,mode=1777 0 0
/dev/sda1 swap swap sw 0 0

More Example: How to Modify the Swap File

# Check for currentl location of swap file
[root@localhost ~]# grep swap /etc/fstab
/dev/mapper/cl-swap     swap                    swap    defaults        0 0

# Turn off swap
swapoff /dev/mapper/cl-swap

# Add 4GB to swap
lvextend -L +4G /dev/mapper/cl-swap

# Reset swap file's signature
mkswap /dev/mapper/dev/mapper/cl-swap

# Turn swap back on
swapon -v /dev/mapper/dev/mapper/cl-swap

More Example: another way to modify swap

# First disable it
sudo swapoff /swapfile

# Change its size. This example will append 4GiB of zero bytes at the end of your swap file
sudo dd if=/dev/zero of=/swapfile bs=1M count=4096 oflag=append conv=notrunc

# Reinit swap
sudo mkswap /swapfile

# Re-enable it
sudo swapon /swapfile

Check memory

[root@localhost ~]# free m
              total        used        free      shared  buff/cache   available
Mem:       32667976      669624    30928356      328868     1069996    31274896
Swap:      16482300           0    16482300

Turn off Swap

# Turn off all instances of swap
swapoff -a

# Turn off a specific instance
swapoff /swap2
sed '/swap2/d' /etc/fstab

A quick note on re-purposing old disks

when reusing a disk that has been set as an LVM member previously, there are 2 options: a) recover its data or b) wipe the disk and repartition it for reuse. The follow illustration option (b) without repartitioning it using LVM.

# Scan disks for LVM partitions - although data on this disk has already been decided to be destroyed
root@kim-linux:/home/kim# pvscan
  WARNING: Couldn't find device with uuid GzSTjH-GYc0-xdN3-kGhW-UriG-X84G-YcIiv1.
  WARNING: VG volumegroup1 is missing PV GzSTjH-GYc0-xdN3-kGhW-UriG-X84G-YcIiv1 (last written to /dev/sdb3).
  PV /dev/sda   VG volumegroup1    lvm2 [14.91 GiB / 0    free]
  PV [unknown]  VG volumegroup1    lvm2 [76.64 GiB / 0    free]
  Total: 2 [91.55 GiB] / in use: 2 [91.55 GiB] / in no VG: 0 [0   ]

Per best practices, it’s often recommended to adjust the swappiness settings to enhance system performance. Here’s how to view and edit such values:

# View existing configured value
$ sudo sysctl vm.overcommit_memory     
vm.overcommit_memory = 0

# optimize swappiness value between 1 and 100, which stands for percentage as a threshold before being triggered
$ sudo sysctl vm.swappiness=1
vm.swappiness = 1
$ sudo sysctl -p # actualize changes without a reboot