Check the current swap space configuration

Use swapon --show or free -h. If swap space is not used, swapon --show will output nothing, while free -h outputs with 0 byte for swap, for example:

              total        used        free      shared  buff/cache   available
Mem:          1.9Gi       214Mi       138Mi       2.0Mi       1.6Gi       1.6Gi
Swap:            0B          0B          0B

Create swap space and configure

  • Allocate swap space: sudo fallocate -l 5G /swapfile. My suggestion to the size of the swap space is 1.5x to 2x the memory size. (check this post for my suggestion on partition strategy in Linux).
  • Update the permission on the created file: sudo chmod 600 /swapfile.
  • Setup swap structure on the created file: sudo mkswap /swapfile.
  • Enable the swap space: sudo swapon /swapfile.
  • Make the change permanent and prevent from being reset after restart. Open and append the following line to /etc/fstab.
/swapfile swap swap defaults 0 0

The file content after the edit:

$ 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>
# / was on /dev/vda1 during installation
UUID=7786cb30-0552-4bf8-99bc-4b5960cc7c22 /               ext4    errors=remount-ro 0       1
/dev/fd0        /media/floppy0  auto    rw,user,noauto,exec,utf8 0       0
/swapfile swap swap defaults 0 0

Confirm the configuration

Same as the first part of this post, with swapon --show.

/swapfile file   5G   0B   -2

With free -h:

              total        used        free      shared  buff/cache   available
Mem:          1.9Gi       213Mi       139Mi       2.0Mi       1.6Gi       1.6Gi
Swap:         5.0Gi          0B       5.0Gi

Remove the swap space

  • Turn of the swap space sudo swapoff /swapfile.
  • Remove the appended line in /etc/fstab.
  • Remove the file allocated for swap to restore the space: sudo rm /swapfile.

Configure swappiness

Swapiness is a value between 0 and 100 to control how much the swap space should be used by the system. 0 means ignoring the swap area unless RAM memory is over.

Ubuntu comes with the value of 60 by default.

  • To check the swappiness:
# sysctl -a | grep swap
vm.swappiness = 60
  • To change the swappiness instantly: sudo sysctl vm.swappiness=50. Note: this change will be reset after machine restarts.
  • To make the change permanently, open /etc/sysctl.conf append or edit the swapiness configuration to: