Add swap memory on EC2 instances, or Digital Ocean droplets
Swap space may help to improve performance when it comes to a shortage of real memory (RAM) on your system, although it is much slower than RAM. In this case, without the swap memory, your server may become unresponsive, or crashed, or it may fall into some other bad unpredictable conditions. But by default EC2 instances and Digital Ocean droplets have no swap enabled (perhaps this is to prevent undesirable costs on EC2 instances, or too many write operations on SSD on DO droplets). Below is the way I use to enable swap on these virtual servers: (Note: You must have root access or “sudo” privilege to perform the following commands)
First, create a swap file:
touch /swapfile
Then, assign the size for swap file (in my case it is 1MB x 1024 = 1GB)
dd if=/dev/zero of=/swapfile bs=1MB count=1024
Then enable the file we’ve just created for swapping
mkswap /swapfile
swapon /swapfile
Now you can use free
command to check for memory status:
free -m
We’re done. But there’s more. We should make it enabled everytime the system starts by adding the following line to the file /etc/fstab:
# Open /etc/fstab using vim
vim /etc/fstab
# Then add this line
/swapfile swap swap defaults 0 0