When u use AWS Lightsail, it is highly possible u will encounter a memory limit problem because lightsail only cares about your CPU usage. If your application is a memory eater and u have chosen a cheap one, you will end up with instance random panic due to the lack of resources.
However, at this time, it usually means that your cue to upgrade your instance. But the CPU usage is still below 10%, there is no need for a higher pay grade, right? So we can make the memory a little bit bigger by setting the swap memory.
Swap memory
Swap memory is a technique that can borrow a part of a hard drive for extra memory. Of course, it will be slow compared to real memory. However, it just works 😂
Create the swap memory
Let’s use the command free -h to see current memory usage:
1 2 3 |
total used free shared buff/cache available Mem: 966Mi 344Mi 61Mi 12Mi 560Mi 447Mi Swap: 0B 0B 0B |
For now, it looks quite alright, but I can tell you that even a little burst will make my instance panic because the free memory is not enough for my application to handle the requests.
So let’s create the swap memory.
First, we create a file that uses for swap. The size will be the swap memory size, which is usually the same size as your real memory size. Here, 1G.
1 2 |
sudo fallocate -l 1G /swapfile sudo chmod 600 /swapfile |
Now we have created the swap file and have set the correct permission for the file. Let’s tell the system to use it!
1 2 |
sudo mkswap /swapfile sudo swapon /swapfile |
We first mark the swapfile file as a special swap use file. Then we told the system to use this file as a swap.
1 2 3 4 5 |
sudo free -h total used free shared buff/cache available Mem: 966Mi 342Mi 60Mi 12Mi 562Mi 449Mi Swap: 1.0Gi 0B 1.0Gi |
Now u can see the swap space is not zero anymore.
Finally, we tell the system, don’t use the swap except for really no memory. I know the swap is really slow, so use it only if necessary.
1 2 |
sudo sysctl vm.swappiness=10 cat /proc/sys/vm/swappiness |
Make sure the swapiness is 10 instead of the default 60. Less swappiness will make the system lesser tend to use the swap.
Make the swap permanent
At last, we have to make this change persist in case the instance restarts.
Edit the file /etc/fstab file, add a new line:
1 |
/swapfile swap swap defaults 0 0 |
Then we change the swappiness, edit file /etc/sysctl.conf , add a new line:
1 |
vm.swappiness=10 |
Wrap up
Now, hopefully ur server will not panic again. However, this only solve the problem that small burst caused memory shortage. If ur code/service starts to eats more memory as ur business grows, migrate to a bigger real memory instance is the best choice.
Ref
How To Add Swap Space on AWS Lightsail Server Instance
本文由 落格博客 原创撰写:落格博客 » Add swap memory to lightsail instance
转载请保留出处和原文链接:https://www.logcg.com/archives/3833.html