Add Swap partition on Ubuntu

In this tutorial we will add swap partition on Ubuntu 18.04 LTS.

Add Swap partition on Ubuntu
  1. Check if swap partition already exists:
    sudo swapon --show

    If the output is empty, you have no swap space enabled. Therefore, we need to create it.

  2. Create a Swap File
    sudo fallocate -l 1G /swapfile

    NOTE to self: in some very rare occasions this might fail, because “fallocate” is not installed: then try with this:
    sudo dd if=/dev/zero of=/swapfile bs=1024 count=1048576
  3. Set the correct permissions:
    sudo chmod 600 /swapfile
  4. Use the mkswap utility to set up a Linux swap area on the file:
    sudo mkswap /swapfile
  5. Activate the swap file:
    sudo swapon /swapfile
  6. Make sure the swap file is ON every time you reboot:
    sudo nano /etc/fstab
    …then add this anywhere within the file: /swapfile swap swap defaults 0 0
  7. Check again if the swap is working: sudo swapon --show
  8. Swappiness Value: this is ok to leave as is, but if you are low on RAM you should set it to a higher value. Default is 60. You can set it between 0 -100.
    Check current value: cat /proc/sys/vm/swappiness
    Set it to 10: sudo sysctl vm.swappiness=10

    If you want to make this effective even after reboot, then add it here:
    sudo nano /etc/sysctl.conf
    …then add this line within the file: vm.swappiness=10

If by any chance you need to remove the swap, then:
1. deactivate the space: sudo swapoff -v /swapfile
2. remove the swap file entry /swapfile swap swap defaults 0 0 from the /etc/fstab file.
3. remove the actual swapfile : sudo rm /swapfile

Now you know how to add swap partition on Ubuntu with ease, or to remove it, also with ease.
Good luck, have fun.


Please enter your comment!
Please enter your name here