Creating the SWAP file for the server optimization

The user you are logged in as must have sudo privileges to be able to activate swap. In this example, we will add 1G swap. If you want to add more swap, replace 1G with the size of the swap space you need.

Perform the steps below to add swap space on Ubuntu 18.04.

  1. Start by creating a file that will be used for swap:

     sudo fallocate -l 1G /swapfile
    
  2. If fallocate is not installed or you get an error message saying fallocate failed: Operation not supported then use the following command to create the swap file:

     sudo dd if=/dev/zero of=/swapfile bs=1024 count=1048576
    
  3. Only the root user should be able to write and read the swap file. Set the correct permissions by typing:

     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 using the following command:

     sudo swapon /swapfile
    

    To make the change permanent open the /etc/fstab file:

     sudo nano /etc/fstab
    

    and paste the following line on the file /etc/fstab:

     /swapfile swap swap defaults 0 0
    
  6. Verify that the swap is active by using either the swapon or the free command, as shown below:

     sudo swapon --show
    
     sudo free -h
    

    https://linuxize.com/post/how-to-add-swap-space-on-ubuntu-18-04/