Add swap space to Amazon Lightsail

Only the smallest of Lightsail instances are configured for swap space. This is how to configure additional swap space.

I discovered this issue when I moved to a bigger instance and the server would keep intermittently crashing with OOM (Out Of Memory) errors, which was strange as the new server had twice the memory of the old instance. Some investigation found that the issue was that the new server did not have any swap space configured, so a transient peak memory load would cause an OOM crash. Further investigation found that this was due to the Bitnami configuration which by design only defined swap space on the smallest (ie: xmicro) instances.

Usually swap space is configured on a separate disk or partition, but the initial configuration of the Lightsail instance is to have only one SSD system disk which has everything on it (eg: Linux, app stack, user data, etc). While it is possible to add disks, there is a cost. They way Bitnami have worked around this is to configure a swap file within the system disk, which as it is an SSD is quite an acceptable solution.

The configuration can be seen in /opt/bitnami/scripts/init/swap_file

#!/bin/sh 
#
# Creates swap file in micro instances
# Copyright 2018 Bitnami.com All Rights Reserved
#
. /opt/bitnami/scripts/init/functions
SWAPFILE=/mnt/.bitnami.swap
SWAPSIZE=650000
instance_type=`get_generic_instance_type`
if [ "x$instance_type" = "xmicro" ] || [ "x$1" = "x--force" ] ; then
if ! (swapon -s | grep -q $SWAPFILE) && test $SWAPSIZE -lt `df -k |grep -m1 -e '/$'|awk '{print $4}'`; then
rm -f $SWAPFILE
dd if=/dev/zero of=$SWAPFILE bs=1K count=$SWAPSIZE
chmod 0600 $SWAPFILE
mkswap $SWAPFILE
swapon $SWAPFILE
fi
else
rm -f $SWAPFILE
fi

Note that the swap file is only configured for xmicro instances and the size is hard coded at 650K.

Using the Bitnami script and doing some research, I configured an additional 1G of swap space as follows.

sudo fallocate -l 1G /swapfile 
sudo chmod 600 /swapfile
sudo mkswap /swapfile
sudo swapon /swapfile
sudo cp /etc/fstab /etc/fstab.bak
echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab

https://manpages.ubuntu.com/manpages/cosmic/man1/fallocate.1.html

https://manpages.ubuntu.com/manpages/bionic/man8/mkswap.8.html

Happy coding.

4,885 views

Need help? Let me take care of your IT issues.

Share this page

Scroll to Top