Add swap to linux

  1. Check swap status. 
    • If nothing is returned by the command, then the summary was empty and no swap file exists.​​
      swapon -s
    • Another way. We can see our current memory and swap usage (in megabytes).
      free -m
                   total       used       free     shared    buffers     cached
      Mem:          3953        315       3637          8         11        107
      -/+ buffers/cache:        196       3756
      Swap:            0          0       4095
  2. Check Available Storage Space
    df -h
    Filesystem      Size  Used Avail Use% Mounted on
    /dev/vda1        59G  1.5G   55G   3% /
    devtmpfs        2.0G     0  2.0G   0% /dev
    tmpfs           2.0G     0  2.0G   0% /dev/shm
    tmpfs           2.0G  8.3M  2.0G   1% /run
    tmpfs           2.0G     0  2.0G   0% /sys/fs/cgroup
  3. Create a Swap File, We create a 4 gigabyte file by typing:
    sudo fallocate -l 4G /swapfile
  4. Change the permission of swap file.
    sudo chmod 600 /swapfile
  5. Tell our system to set up the swap space
    sudo mkswap /swapfile
    Setting up swapspace version 1, size = 4194300 KiB
    no label, UUID=b99230bb-21af-47bc-8c37-de41129c39bf
  6. Enable swap
    sudo swapon /swapfile
  7. To verify that the procedure was successful.
    swapon -s
    Filename                Type        Size    Used    Priority
    /swapfile               file        4194300 0     -1


Make the Swap File Permanent

  1. Edit "/etc/fstab" file with sudo privileges in your text editor.
    Add the following to the bottom of the file.
    /swapfile   swap    swap    sw  0   0
  2. Save and close the file. Now, the swap file has been permanently on your server even if the server has been rebooted.