I ran across an issue today where my npm install
was failing with a cryptic 'killed' error. I knew the issue was probably due to RAM pressure as I was running on a Digital Ocean 512MB droplet. Instead of upgrading the droplet to 1GB just to get past npm, I added a swapfile.
It's not a good idea to rely on swap, especially on VPS systems with SSDs. It's much slower than RAM and constant writes to SSDs can cause issues due to durability limits. If you consistently need more RAM than is available, you should likely upgrade your VM.
1. Prep
First, check to see if you have any swap set up already:
$ sudo swapon -s
If you only see the table headers, you don't have any swap configured. Proceed.
You can also check free -m
to see if there is a line beginning with Swap:
.
You also need to have available disk space to use. Check with:
$ df -h
There should be a /dev/___
with some free space.
2. Create
Create a 2GB swap file at your root:
$ sudo fallocate -l 2G /swapfile
You can make this any size you need by changing the 2G
to your desired size.
Adjust permissions so only root can read/write:
$ sudo chmod 600 /swapfile
Check permissions
$ ls -lh /swapfile
# -rw------- 1 root root 2.0G Aug 16 13:26 /swapfile
3. Enable
Set up the swap file:
$ sudo mkswap /swapfile
Enable the swap file:
$ sudo swapon /swapfile
This can be checked with:
$ sudo swapon -s
Now, instead of just the headers returned in step 1, you should see an entry for the new swap file we just created.
4. Persist
The swap will not persist across reboots by default. To make it persist, we need to add it to the fstab (file systems table) file:
$ sudo nano /etc/fstab
Add the following to the end of the file:
/swapfile none swap sw 0 0
5. Tweak swappiness (optional)
The defaults aren't the best for VMs and SSDs. We can make the OS swap as little as possible by changing the swappiness
setting:
$ sudo sysctl vm.swappiness=10
Again, this will not persist across reboots, so we need to add it to 'sysctl.conf`:
$ sudo nano /etc/sysctl.conf
Add the following line to the very bottom:
vm.swappiness=10
That's it. You now have a 2GB swap file and your npm installs
should now complete without error. Well, without errors due to RAM limits anyway...