# 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)