Skip to main content

Swap Allocation

Creating swap memory for your host could prevent system or services from crashing when under heavy loads. To do this, run the following commands.

Creating Swap Files

# To createa 512MiB swap file - 
sudo dd if=/dev/zero of=/swapfile bs=1M count=512 status=progress

# To create a 1GiB swap file - 
sudo dd if=/dev/zero of=/swapfile bs=1GB count=1

# To create a 10GiB swap file - 
sudo dd if=/dev/zero of=/swapfile bs=1GB count=10

Enabling Swap

After creating the swap file of the desired size, in the desired directory, we'll need to set some permissions and prepare our file to be used for swap space -

# Set permissions
sudo chmod 600 /swapfile

# Format file to be used for swap allocation
sudo mkswap /swapfile

# Tell our system to mount this file for swap usage
sudo swapon /swapfile

Adding Default Swap Entry - fstab

In short, an fstab entry for mounting the swap partition we created above -

# <device> <dir> <type> <options> <dump> <fsck>
/swapfile none swap defaults 0 0

Add this line to your /etc/fstab to mount and use this partition for swap automatically on system reboots.

For more information, see Mounting Default Filesystems or ArchWiki - Fstab

Verifying Swap Configuration

To check available system swap space, run free -h to see output similar to the below -

root@host:~# free -h
              total        used        free      shared  buff/cache   available
Mem:          983Mi       260Mi        62Mi       0.0Ki       660Mi       560Mi
Swap:         1.0Gi        15Mi       1.0Gi

Alternatively, we could run 'sudo swapon --show' to see the below output

sudo swapon --show
/swapfile file 1024M 15.8M   -2

Swappiness Values

The default swappiness value is set to 60, but to check, change, or verify your system swappiness, see the commands below

# Check system swappiness setting
cat /proc/sys/vm/swappiness 

# Set a new swappiness value
sudo sysctl vm.swappiness=10
# Check the setting was applied
cat /proc/sys/vm/swappiness 

Swappiness Persistance

Upon setting a custom swappiness value and rebooting, your custom configuration will be lost. Edit /etc/sysctl.conf to contain the line below to ensure this value is kept between system reboots


Removing Swap Files

First, turn off the swap file -

sudo swapoff -v /swapfile

Remove the swap file entry from your /etc/fstab if you previously created one. If present, remove the line similar to the below

/swapfile swap swap defaults 0 0

Last, delete the swap file using rm -

sudo rm /swapfile