How To Add Swap Space on Ubuntu 18.04

Command to see if the system has any configured swap

sudo swapon --show

How to Create/Edit a Swap File

If there a swap space in the Ubuntu Server stop the swap file by using the command

sudo swapoff -a

If no swap files in the system follow the following steps to create a new swap file. In the following case, I am allocating 16GB:

sudo fallocate -l 16G /swapfile

Verify that the correct amount of space was reserved by typing

ls -lh /swapfile

Enabling the Swap File

Make the file only accessible to root by typing

sudo chmod 600 /swapfile

Mark the file as swap space by typing

sudo mkswap /swapfile

Enabling the swap file

sudo swapon /swapfile

Verify that the swap is available by typing

sudo swapon --show

Making the Swap File Permanent

Back up the /etc/fstab file in case anything goes wrong

sudo cp /etc/fstab /etc/fstab.bak

Add the swap file information to the end of your /etc/fstab file by typing

echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab

To increase the size of the Swap File

Disable the swap file:

sudo swapoff /swapfile

If you want to allocate more memory, simply change the size value. For example, to allocate 32GB, you would use:

sudo fallocate -l 32G /swapfile

Enable the swap file again:

sudo swapon /swapfile

Post a comment