Add Swap

Posted on Sunday March 13, 2016 by Eric Potvin

Some pre-installed Ubuntu Server are not configured with SWAP. Linux swaps allow a system to harness more memory than was originally physically available

Check for SWAP space:

Let's check if a SWAP file exists and it's enabled before we create one.

sudo swapon -s

If there's no SWAP file, you should get a result like this:

Filename				Type		Size	Used	Priority

Create and Enable the Swap File

Before we create the SWAP file, we need to find out how much we need. Here's a quick guide to help you.

RAM in your Server Recommended swap space
2GB of RAM or less 2 times the amount of RAM
2GB to 8GB of RAM Equal to the amount of RAM
8GB to 64GB of RAM 0.5 times the amount of RAM
64GB of RAM or more 4GB of swap space

To create the SWAP file, you will need to use the dd command:

sudo dd if=/dev/zero of=/swapfile bs=1024 count=512k

All of this means:

if=/dev/zero  : Read from /dev/zero file. /dev/zero is a special file in that provides as many null characters to build storage file called /swapfile1.
of=/swapfile1 : Read from /dev/zero write stoage file to /swapfile1.
bs=1024       : Read and write 1024 BYTES bytes at a time.
count=524288  : Copy only 523288 BLOCKS input blocks.

Prepare the swap file by creating a linux swap area:

sudo mkswap /swapfile

The results display:

Setting up swapspace version 1, size = 524284 KiB
no label, UUID=265d3e61-6e2b-4126-baba-6e6185e97b46

Activate the swap file:

sudo swapon /swapfile

Confirm that the swap partition exists.

$ sudo swapon -s

This will output something like:

Filename				Type		Size	Used	Priority
/swapfile                               file		524284	0	-1

This will last until the server reboots. Before, rebooting the server. Let's create the entry in the fstab:

sudo vi /etc/fstab

and add the following line:

/swapfile       none    swap    sw      0       0

Improve performance

Swappiness in the file should be set to 0. Skipping this step may cause both poor performance, whereas setting it to 0 will cause swap to act as an emergency buffer, preventing out-of-memory crashes. You can do this with the following commands:

echo 0 | sudo tee /proc/sys/vm/swappiness
echo vm.swappiness = 0 | sudo tee -a /etc/sysctl.conf

Secure SWAP

To prevent the file from being world-readable, you should set up the correct permissions on the swap file:

sudo chown root:root /swapfile
sudo chmod 0600 /swapfile

Reboot to make sure the new swap gets activated properly at startup.