Resizing swap

I use small Digital Ocean virtual machines, and they come with little RAM and little drive space. I originally allocated 4 GB for the swap, but now I want to reduce it to 2 GB.

Initially to prevent the server from going out of RAM and randomly killing processes like it happened in Fixing `Error: Authentication failed.` on a previously perfectly running MongoDB server, I had set up a 4 GB swapfile.

But now I have the opposite problem. I run out of drive space too easily. Considering the fact that the server uses on average only 500 MB out of 1 GB, I am unlikely to need 4 GB of swapfile. 2 GB should be sufficiently.

Setting up the swap

Here's how I originally set up swap, based on https://www.digitalocean.com/community/tutorials/how-to-add-swap-on-ubuntu-14-04. Note that they should be run as root (or use sudo):

fallocate -l 4G /swapfile
chmod 600 /swapfile
mkswap /swapfile
swapon /swapfile

Then in /etc/fstab (nano /etc/fstab), add the following line:

/swapfile   none    swap    sw    0   0

Downsizing the swap

TLDR

swapoff /swapfile
rm /swapfile
fallocate -l 2G /swapfile
chmod 600 /swapfile
mkswap /swapfile
swapon /swapfile

How I got there

Here's what I found on StackOverflow:

swapoff /swapfile
fallocate -l 2G /swapfile
chmod 600 /swapfile
mkswap /swapfile
swapon /swapfile

However, when I ran the first command, I got this:

# swapoff /swapfile
Killed

Does it mean it successfully killed the swapfile, ie closed the swap? Nope.

# fallocate -l 2G /swapfile
fallocate: fallocate failed: Text file busy

This error means that the swapfile is still being used. You can verify it like so:

# swapon --show
NAME      TYPE SIZE  USED PRIO
/swapfile file   4G 41.5M   -2

So it turned out that Killed meant that since the drive was full, there was not enough space to execute swapoff and the process was Killed. After freeing up some space, I ran swapoff again and this time it worked.

However when running mkswap, I got this:

# mkswap /swapfile
mkswap: /swapfile: warning: wiping old swap signature.
Setting up swapspace version 1, size = 4 GiB (4294963200 bytes)
no label, UUID=b2a6f46e-7731-40f7-83a5-7893ad12d147

So it turned out that even if I had used fallocate to tell it to allocate 2GB, the command didn't actually reduce the size of the file. So it looks like before allocating that file, I should remove the old file.

After I completed all the steps, I verified that all was well by running top:

top - 00:02:21 up XXX days, 23:39,  1 user,  load average: 0.02, 0.07, 0.07
Tasks: 118 total,   1 running, 117 sleeping,   0 stopped,   0 zombie
%Cpu(s):  0.3 us,  0.3 sy,  0.0 ni, 99.0 id,  0.0 wa,  0.0 hi,  0.3 si,  0.0 st
MiB Mem :    478.1 total,      8.9 free,    375.6 used,     93.6 buff/cache
MiB Swap:   2048.0 total,   2046.0 free,      2.0 used.     76.2 avail Mem 

MiB Swap: 2048 MB. Good!