Add Swap File on AWS EC2 Ubuntu Redhat Linux

Use following commands to create swap file on your system.

$ sudo dd if=/dev/zero of=/var/swapfile bs=1M count=2048

bs=1M count=2048 means it will create 2GB of swap file, You may change as per you need. After enabling swap we can see that our system has swap enabled by running “free -m” command.

To prevent the file from being world-readable, you should set up the correct permissions on the swap file:

$ sudo chown root:root /var/swapfile
$ sudo chmod 0600 /var/swapfile

Subsequently we are going to prepare the swap file by creating a linux swap area.

$ sudo mkswap /var/swapfile

Finish up by activating the swap file.

$ sudo swapon /var/swapfile

You will then be able to see the new swap file when you view the swap summary.

$ sudo swapon -s

This file will last on the virtual private server until the machine reboots. You can ensure that the swap is permanent by adding it to the fstab file.

$ sudo nano /etc/fstab

Paste in the following line:

/var/swapfile swap swap defaults 0 0

Ubuntu system comes with a default of 60, meaning that the swap file will be used fairly often if the memory usage is around half of my RAM. You can check your own system’s swappiness value by running:

$ cat /proc/sys/vm/swappiness

As I have 4 GB of RAM, so I’d like to turn that down to 10 or 15. The swap file will then only be used when my RAM usage is around 80 or 90 percent. To change the system swappiness value, open /etc/sysctl.conf as root. Then, change or add this line to the file:

vm.swappiness = 10

Reboot for the change to take effect.

You can also change the value while your system is still running

sysctl vm.swappiness=10

Skipping this step may cause both poor performance.

You can also clear your swap by running

swapoff -a

And then

swapon -a

As root instead of rebooting to achieve the same effect.