Swap space is useful for systems having less memory (RAM). If your system facing the problem of lack of memory continuously and you don’t want to increase memory on the server, Then it can be helpful to enable swap in your system. Swap is comparatively much slower than physical memory but the operating system uses swap space in case system goes out of memory. To know more about working of swap visit here.
This article will help you to enable swap filesystem in your running instance. There are two methods to add swap in Amazon ec2 Linux instances. This article has been tested with CentOS 6.9, but it will work on most of Linux distributions.
Method 1 – Using Swap File
This option is helpful if we don’t want to add extra disks in our systems, In this, we simply create a file in our current file system and make it type swap, which can be used as swap in our system. Use the following commands to create and enable swap on our system.
sudo dd if=/dev/zero of=/var/myswap bs=1M count=4096 sudo mkswap /var/myswap sudo swapon /var/myswap
bs=1M count=4096 means it will create 4 GB 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 make it enable on system boot, simply edit /etc/fstab file and add following entry at end of file. My fstab file looks like below after adding the swap entry.
cat /etc/fstab LABEL=/ / ext4 defaults,relatime 1 1 tmpfs /dev/shm tmpfs defaults 0 0 devpts /dev/pts devpts gid=5,mode=620 0 0 sysfs /sys sysfs defaults 0 0 proc /proc proc defaults 0 0 /var/myswap swap swap defaults 0 0
Method 2 – Using Additional Disk for Swap
This option is helpful if you do not have enough space in our current drives mounted in the system. In this option, first, we need to add extra disk in our system first. In my case new disk mounted as /dev/xvdd (It may change in your case)
sudo mkswap -f /dev/xvdd sudo swapon /dev/xvdd
To make it enable on system boot, simply edit /etc/fstab file and add following entry at end of file. After adding swap entry, the
cat /etc/fstab LABEL=/ / ext4 defaults,relatime 1 1 tmpfs /dev/shm tmpfs defaults 0 0 devpts /dev/pts devpts gid=5,mode=620 0 0 sysfs /sys sysfs defaults 0 0 proc /proc proc defaults 0 0 /dev/xvdd swap swap defaults 0 0
In this tutorial you have learned to create and enable Swap memory on EC2 Linux instance.