Development notes

Thoughts, notes and ideas about development

How to add a swap file on Ubuntu 16.04

2016-10-12 2 min read linux Alexey Bogdanov

Into one of my posts (How to install Ghost on Ubuntu 16.04) I mentioned that error Killedt:iconv-lite → gunz may occur because of using npm on VPS instance with low RAM. I’ve got such error while installing Ghost on VPS instance with 512MB of RAM. That happened because npm run out of memory and Linux OOM killer started to kill processed to get memory back to the system. Such problem could be resolved by increasing RAM from 512MB to 1GB or by creating a swap file. In this tutorial I will describe how to add a swap file on Ubuntu 16.04.

Create a file for swapping

We’ll store the swap file in /var/swap/ folder. So let’s create required folders first.

sudo mkdir -p /var/swap

Now let’s create a swap file

cd /var/swap
sudo touch swap.img
sudo chmod 600 swap.img

We created a file which will be used for swapping and restricted file’s permissions to read and write only for file’s owner (root in that case).

Swap file size

According to some sources it’s recommended to create a swap with size 2X of instance RAM. But in case of Ghost 512Mb of RAM should be enough. Lets change file’s size to 512MB

sudo dd if=/dev/zero of=/var/swap/swap.img bs=1024k count=512

The output will look like

512+0 records in
512+0 records out
536870912 bytes (537 MB, 512 MiB) copied, 1.03334 s, 520 MB/s

We are using a dd utility which fills a swap file with zeroes to required size (in our case it’s 512Mb) with blocks size equal to 1024k. Creating swap file with such parameters should not take too long.

Set up a swap area

Our file for swapping is ready. Now we need to set up a swap area on our created file.

sudo mkswap /var/swap/swap.img

Our swap area is ready for use. Now let’s enable it

sudo swapon /var/swap/swap.img

swapon is an utility which permanently enables swap. After system reboot it will be disabled. To make swap constantly enabled we should add the following line into the file /etc/fstab

# Swap file
/var/swap/swap.img    none    swap    sw    0    0

/etc/fstab is a config file which contains information about how file systems and devices will be mounted and used during system boot.

comments powered by Disqus